text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Change confusing variable name in e2e test | describe('the Basic example page', function () {
var basicExamplePage = require('./page.js');
beforeEach(function () {
basicExamplePage.get();
});
describe('rendering of the tree data', function () {
it('should render a tree with 3 root nodes', function () {
basicExamplePage.rootNodes.count().then(function (rootNodeCount) {
expect(rootNodeCount).toEqual(3);
});
});
it('should show 2 subnodes for the first root node', function () {
basicExamplePage.firstSubNodes.count().then(function (rootNodeCount) {
expect(rootNodeCount).toEqual(2);
});
});
it('should show the correct text for the subnodes', function () {
var subnodes = basicExamplePage.firstSubNodes;
subnodes.get(0).all(by.css('.tree-node-content')).first().getText().then(function (text) {
expect(text).toEqual('node1.1');
});
subnodes.get(1).all(by.css('.tree-node-content')).first().getText().then(function (text) {
expect(text).toEqual('node1.2');
});
});
});
describe('the dragging and dropping of nodes', function () {
it('should allow moving a node below another node', function () {
// TODO
});
it('should allow adding a node to another node to make it a child-node', function () {
// TODO
});
it('should allow removing a child-node from a node to put it on the same tree level', function () {
// TODO
});
});
});
| describe('the Basic example page', function () {
var basicExamplePage = require('./page.js');
beforeEach(function () {
basicExamplePage.get();
});
describe('rendering of the tree data', function () {
it('should render a tree with 3 root nodes', function () {
basicExamplePage.rootNodes.count().then(function (meetupCount) {
expect(meetupCount).toEqual(3);
});
});
it('should show 2 subnodes for the first root node', function () {
basicExamplePage.firstSubNodes.count().then(function (meetupCount) {
expect(meetupCount).toEqual(2);
});
});
it('should show the correct text for the subnodes', function () {
var subnodes = basicExamplePage.firstSubNodes;
subnodes.get(0).all(by.css('.tree-node-content')).first().getText().then(function (text) {
expect(text).toEqual('node1.1');
});
subnodes.get(1).all(by.css('.tree-node-content')).first().getText().then(function (text) {
expect(text).toEqual('node1.2');
});
});
});
describe('the dragging and dropping of nodes', function () {
it('should allow moving a node below another node', function () {
// TODO
});
it('should allow adding a node to another node to make it a child-node', function () {
// TODO
});
it('should allow removing a child-node from a node to put it on the same tree level', function () {
// TODO
});
});
});
|
Throw an error if includeLanguages option is used. | /* eslint-env node */
'use strict';
let path = require('path');
let Funnel = require('broccoli-funnel');
module.exports = {
name: 'ember-cli-numeral',
included: function(app) {
this.app = app;
if (typeof app.import !== 'function' && app.app) {
this.app = app = app.app;
}
this._super.included.apply(this, arguments);
let appOptions = app.options || {};
let options = appOptions.numeral || {};
app.import({
development: 'vendor/numeral/numeral.js',
production: 'vendor/numeral/min/numeral.min.js'
}, {
using: [{ transformation: 'amd', as: 'numeral' }]
});
if (options.includeLanguages) {
throw new Error('includeLanguages option is no longer available. Please use includeLocales (see the README for usage).');
}
if (options.includeLocales) {
for (let locale of options.includeLocales) {
app.import({
development: `vendor/numeral/locales/${locale}.js`,
production: `vendor/numeral/min/locales/${locale}.min.js`
}, {
using: [{ transformation: 'amd', as: `numeral/${locale}` }]
});
}
}
},
treeForVendor: function(/* vendorTree */) {
let numeralPath = path.dirname(require.resolve('numeral'));
let numeralTree = new Funnel(numeralPath, {
include: ['numeral.js', 'locales/**/*', 'min/**/*'],
destDir: 'numeral'
});
return numeralTree;
},
};
| /* eslint-env node */
'use strict';
let path = require('path');
let Funnel = require('broccoli-funnel');
module.exports = {
name: 'ember-cli-numeral',
included: function(app) {
this.app = app;
if (typeof app.import !== 'function' && app.app) {
this.app = app = app.app;
}
this._super.included.apply(this, arguments);
let appOptions = app.options || {};
let options = appOptions.numeral || {};
app.import({
development: 'vendor/numeral/numeral.js',
production: 'vendor/numeral/min/numeral.min.js'
}, {
using: [{ transformation: 'amd', as: 'numeral' }]
});
if (options.includeLocales) {
for (let locale of options.includeLocales) {
app.import({
development: `vendor/numeral/locales/${locale}.js`,
production: `vendor/numeral/min/locales/${locale}.min.js`
}, {
using: [{ transformation: 'amd', as: `numeral/${locale}` }]
});
}
}
},
treeForVendor: function(/* vendorTree */) {
let numeralPath = path.dirname(require.resolve('numeral'));
let numeralTree = new Funnel(numeralPath, {
include: ['numeral.js', 'locales/**/*', 'min/**/*'],
destDir: 'numeral'
});
return numeralTree;
},
};
|
Make mystery man the default Gravatar image | # place inside a 'templatetags' directory inside the top level of a Django app (not project, must be inside an app)
# at the top of your page template include this:
# {% load gravatar %}
# and to use the url do this:
# <img src="{% gravatar_url '[email protected]' %}">
# or
# <img src="{% gravatar_url sometemplatevariable %}">
# just make sure to update the "default" image path below
from __future__ import absolute_import, unicode_literals
import hashlib
from django import template
from django.utils.six.moves.urllib.parse import urlencode
register = template.Library()
class GravatarUrlNode(template.Node):
def __init__(self, email, size=50):
self.email = template.Variable(email)
self.size = size
def render(self, context):
try:
email = self.email.resolve(context)
except template.VariableDoesNotExist:
return ''
default = "mm"
size = int(self.size) * 2 # requested at retina size by default and scaled down at point of use with css
gravatar_url = "//www.gravatar.com/avatar/{hash}?{params}".format(
hash=hashlib.md5(email.lower().encode('utf-8')).hexdigest(),
params=urlencode({'s': size, 'd': default})
)
return gravatar_url
@register.tag
def gravatar_url(parser, token):
bits = token.split_contents()
return GravatarUrlNode(*bits[1:])
| # place inside a 'templatetags' directory inside the top level of a Django app (not project, must be inside an app)
# at the top of your page template include this:
# {% load gravatar %}
# and to use the url do this:
# <img src="{% gravatar_url '[email protected]' %}">
# or
# <img src="{% gravatar_url sometemplatevariable %}">
# just make sure to update the "default" image path below
from __future__ import absolute_import, unicode_literals
import hashlib
from django import template
from django.utils.six.moves.urllib.parse import urlencode
register = template.Library()
class GravatarUrlNode(template.Node):
def __init__(self, email, size=50):
self.email = template.Variable(email)
self.size = size
def render(self, context):
try:
email = self.email.resolve(context)
except template.VariableDoesNotExist:
return ''
default = "blank"
size = int(self.size) * 2 # requested at retina size by default and scaled down at point of use with css
gravatar_url = "//www.gravatar.com/avatar/{hash}?{params}".format(
hash=hashlib.md5(email.lower().encode('utf-8')).hexdigest(),
params=urlencode({'s': size, 'd': default})
)
return gravatar_url
@register.tag
def gravatar_url(parser, token):
bits = token.split_contents()
return GravatarUrlNode(*bits[1:])
|
Add name to User model. | from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.translation import ugettext_lazy as _
class Organization(models.Model):
name = models.CharField(_('Name'), max_length=80)
slug = models.SlugField()
def __unicode__(self):
return self.name
class Team(models.Model):
name = models.CharField(_('Name'), max_length=80)
organization = models.ForeignKey('Organization')
def __unicode__(self):
return self.name
class User(AbstractUser):
name = models.CharField(_('Name'), max_length=40)
teams = models.ManyToManyField(Team, blank=True, related_name='users')
def __unicode__(self):
return self.name
class Contract(models.Model):
name = models.CharField(_('Name'), max_length=150)
def __unicode__(self):
return self.name
class ContractOrganization(models.Model):
contract = models.ForeignKey('Contract')
organization = models.ForeignKey('Organization')
default_team = models.ForeignKey('Team')
def __unicode__(self):
return self.contract.name + ' - ' + self.organization.name
class Meta:
verbose_name = _('Contracted organization')
verbose_name_plural = _('Contracted organizations')
class ContractTeam(models.Model):
contract = models.ForeignKey('Contract')
team = models.ForeignKey('Team')
def __unicode__(self):
return self.contract.name + ' - ' + self.team.name
class Meta:
verbose_name = _('Contracted team')
verbose_name_plural = _('Contracted teams')
| from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.translation import ugettext_lazy as _
class Organization(models.Model):
name = models.CharField(_('Name'), max_length=80)
slug = models.SlugField()
def __unicode__(self):
return self.name
class Team(models.Model):
name = models.CharField(_('Name'), max_length=80)
organization = models.ForeignKey('Organization')
def __unicode__(self):
return self.name
class User(AbstractUser):
teams = models.ManyToManyField(Team, blank=True, related_name='users')
def __unicode__(self):
return self.username
class Contract(models.Model):
name = models.CharField(_('Name'), max_length=150)
def __unicode__(self):
return self.name
class ContractOrganization(models.Model):
contract = models.ForeignKey('Contract')
organization = models.ForeignKey('Organization')
default_team = models.ForeignKey('Team')
def __unicode__(self):
return self.contract.name + ' - ' + self.organization.name
class Meta:
verbose_name = _('Contracted organization')
verbose_name_plural = _('Contracted organizations')
class ContractTeam(models.Model):
contract = models.ForeignKey('Contract')
team = models.ForeignKey('Team')
def __unicode__(self):
return self.contract.name + ' - ' + self.team.name
class Meta:
verbose_name = _('Contracted team')
verbose_name_plural = _('Contracted teams')
|
Rename svg output based on sort attribute | import pygal
def horizontal_bar(sorted_streaks, sort):
"""
Render a horizontal bar chart of streaks.
Values have already been sorted by sort.
"""
users = [user for user, _ in sorted_streaks][::-1]
streaks = [getattr(streak, sort) for _, streak in sorted_streaks][::-1]
chart = pygal.HorizontalStackedBar(show_y_labels=False,
show_x_labels=False,
show_legend=False,
print_values=True,
print_zeroes=False,
print_labels=True)
chart.title = 'Top contributors by {} streak'.format(sort)
chart.x_labels = users
values = []
for value, user in zip(streaks, users):
if value > 0:
values.append({
'value': value,
'label': user,
'xlink': 'https://github.com/{}'.format(user)
})
else:
values.append(0) # Let zeroes be boring
chart.add('Streaks', values)
chart.render_to_file('top_{}.svg'.format(sort))
| import pygal
def horizontal_bar(sorted_streaks, sort_attrib):
"""
Render a horizontal bar chart of streaks.
Values have already been sorted by sort_attrib.
"""
users = [user for user, _ in sorted_streaks][::-1]
streaks = [getattr(streak, sort_attrib) for _, streak in sorted_streaks][::-1]
chart = pygal.HorizontalStackedBar(show_y_labels=False,
show_x_labels=False,
show_legend=False,
print_values=True,
print_zeroes=False,
print_labels=True)
chart.title = 'Top contributors by {} streak'.format(sort_attrib)
chart.x_labels = users
values = []
for value, user in zip(streaks, users):
if value > 0:
values.append({
'value': value,
'label': user,
'xlink': 'https://github.com/{}'.format(user)
})
else:
values.append(0) # Let zeroes be boring
chart.add('Streaks', values)
chart.render_to_file('top.svg')
|
Add bridge.user to the config. | package org.sagebionetworks.bridge.config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class BridgeConfigTest {
@Before
public void before() {
System.setProperty("bridge.pwd", "when.the.password.is.not.a.password");
System.setProperty("bridge.salt", "when.the.salt.is.some.random.sea.salt");
System.setProperty("bridge.user", "unit.test");
}
@After
public void after() {
System.clearProperty("bridge.pwd");
System.clearProperty("bridge.salt");
System.clearProperty("bridge.user");
System.clearProperty("bridge.env");
}
@Test
public void testDefault() {
BridgeConfig config = new BridgeConfig();
assertTrue(config.isStub());
assertNull(config.getProperty("someFakePropertyThatDoesNotExist"));
}
@Test
public void testEncryption() {
BridgeConfig config = new BridgeConfig();
assertEquals("example.value", config.getProperty("example.property"));
assertEquals("example.value.encrypted", config.getProperty("example.property.encrypted"));
}
@Test
public void testEnvironment() {
System.setProperty("bridge.env", "dev");
BridgeConfig config = new BridgeConfig();
assertEquals("example.value.for.dev", config.getProperty("example.property"));
}
@Test
public void testUser() {
BridgeConfig config = new BridgeConfig();
assertEquals("unit.test", config.getProperty("bridge.user"));
}
}
| package org.sagebionetworks.bridge.config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class BridgeConfigTest {
@Before
public void before() {
System.setProperty("bridge.pwd", "when.the.password.is.not.a.password");
System.setProperty("bridge.salt", "when.the.salt.is.some.random.sea.salt");
}
@After
public void after() {
System.clearProperty("bridge.pwd");
System.clearProperty("bridge.salt");
System.clearProperty("bridge.env");
}
@Test
public void testDefault() {
BridgeConfig config = new BridgeConfig();
assertTrue(config.isStub());
assertNull(config.getProperty("someFakePropertyThatDoesNotExist"));
}
@Test
public void testEncryption() {
BridgeConfig config = new BridgeConfig();
assertEquals("example.value", config.getProperty("example.property"));
assertEquals("example.value.encrypted", config.getProperty("example.property.encrypted"));
}
@Test
public void testEnvironment() {
System.setProperty("bridge.env", "dev");
BridgeConfig config = new BridgeConfig();
assertEquals("example.value.for.dev", config.getProperty("example.property"));
}
}
|
Use abstract classes in the runlistener | package de.pitkley.jenkins.plugins.dockerswarmslave;
import hudson.Extension;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildableItemWithBuildWrappers;
import hudson.model.Run;
import hudson.model.listeners.RunListener;
@Extension
public class DockerSwarmSlaveRunListener extends RunListener<Run<?, ?>> {
@Override
public void onFinalized(Run<?, ?> run) {
// Check that we have a build
if (!AbstractBuild.class.isAssignableFrom(run.getClass())) {
return;
}
AbstractBuild<?, ?> b = (AbstractBuild) run;
// Check that it is a project
if (!AbstractProject.class.isAssignableFrom(b.getProject().getClass())) {
return;
}
AbstractProject<?, ?> project = b.getProject();
if (!BuildableItemWithBuildWrappers.class.isAssignableFrom(project.getClass())) {
return;
}
// Was our build-wrapper active?
DockerSwarmSlaveBuildWrapper buildWrapper = DockerSwarmSlaveLabelAssignment.getDockerSwarmSlaveBuildWrapper((BuildableItemWithBuildWrappers) project);
if (buildWrapper == null) {
return;
}
// Do we have a matching DockerSwarmSlave?
DockerSwarmSlave dockerSwarmSlave = DockerSwarmSlave.get(project);
if (dockerSwarmSlave == null) {
return;
}
// Clean everything up
dockerSwarmSlave.cleanup();
}
}
| package de.pitkley.jenkins.plugins.dockerswarmslave;
import hudson.Extension;
import hudson.model.Build;
import hudson.model.Project;
import hudson.model.Run;
import hudson.model.listeners.RunListener;
@Extension
public class DockerSwarmSlaveRunListener extends RunListener<Run<?, ?>> {
@Override
public void onFinalized(Run<?, ?> run) {
// Check that we have a build
if (!Build.class.isAssignableFrom(run.getClass())) {
return;
}
Build<?, ?> b = (Build) run;
// Check that it is a project
if (!Project.class.isAssignableFrom(b.getProject().getClass())) {
return;
}
Project<?, ?> project = b.getProject();
// Was our build-wrapper active?
DockerSwarmSlaveBuildWrapper buildWrapper = DockerSwarmSlaveLabelAssignment.getDockerSwarmSlaveBuildWrapper(project);
if (buildWrapper == null) {
return;
}
// Do we have a matching DockerSwarmSlave?
DockerSwarmSlave dockerSwarmSlave = DockerSwarmSlave.get(project);
if (dockerSwarmSlave == null) {
return;
}
// Clean everything up
dockerSwarmSlave.cleanup();
}
}
|
Fix install ways triggering re-indexing recommendation | <?php
class SV_WordCountSearch_Installer
{
public static function install($installedAddon, array $addonData, SimpleXMLElement $xml)
{
$version = isset($installedAddon['version_id']) ? $installedAddon['version_id'] : 0;
if (!(XenForo_Application::get('options')->enableElasticsearch) || !($XenEs = XenForo_Model::create('XenES_Model_Elasticsearch')))
{
throw new Exception("Require Enhanced Search to be installed and enabled");
}
$requireIndexing = array();
if ($version == 0)
{
$requireIndexing['post'] = true;
}
$db = XenForo_Application::getDb();
$db->query("
CREATE TABLE IF NOT EXISTS `xf_post_words`
(
`post_id` int(10) unsigned NOT NULL,
`word_count` int(10) unsigned NOT NULL,
PRIMARY KEY (`post_id`)
) ENGINE=InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci
");
// if Elastic Search is installed, determine if we need to push optimized mappings for the search types
SV_Utils_Install::updateXenEsMapping($requireIndexing, array(
'post' => array(
"properties" => array(
"word_count" => array("type" => "long"),
)
)
));
}
public static function uninstall()
{
$db = XenForo_Application::getDb();
$db->query("
DROP TABLE IF EXISTS `xf_post_words`
");
}
} | <?php
class SV_WordCountSearch_Installer
{
public static function install($installedAddon, array $addonData, SimpleXMLElement $xml)
{
$version = isset($installedAddon['version_id']) ? $installedAddon['version_id'] : 0;
if (!(XenForo_Application::get('options')->enableElasticsearch) || !($XenEs = XenForo_Model::create('XenES_Model_Elasticsearch')))
{
throw new Exception("Require Enhanced Search to be installed and enabled");
}
$requireIndexing = array();
if ($version == 0)
{
$requireIndexing['post'] = true;
}
$db = XenForo_Application::getDb();
$db->query("
CREATE TABLE IF NOT EXISTS `xf_post_words`
(
`post_id` int(10) unsigned NOT NULL,
`word_count` int(10) unsigned NOT NULL,
PRIMARY KEY (`post_id`)
) ENGINE=InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci
");
// if Elastic Search is installed, determine if we need to push optimized mappings for the search types
SV_Utils_Install::updateXenEsMapping($requireIndexing, array(
'post' => array(
"properties" => array(
"word_count" => array("type" => "long", "store" => "yes"),
)
)
));
}
public static function uninstall()
{
$db = XenForo_Application::getDb();
$db->query("
DROP TABLE IF EXISTS `xf_post_words`
");
}
} |
Fix test for checking resource PDF generation | """Tests for resource generation."""
import os
import re
import copy
from django.core import management
from config.settings.base import DEFAULT_LANGUAGES as LANGUAGES
from tests.BaseTestWithDB import BaseTestWithDB
from resources.models import Resource
class ResourceGenerationTest(BaseTestWithDB):
"""Tests for resource generation."""
def test_all_resource_pdfs_are_generated(self):
# Check all resources are generated for each langage
management.call_command("loadresources")
# Generate all resource combinations in dictionary
modes = ["dev", "prod"]
resource_slugs = set(Resource.objects.values_list("slug", flat=True))
languages = [lang[0] for lang in LANGUAGES]
required_resources = dict()
for mode in modes:
required_resources[mode] = dict()
for resource_slug in resource_slugs:
required_resources[mode][resource_slug] = languages[:]
# Check files for resource generations
regex = re.compile(r'makeresources \"([^\n\"]*)\"(?: \"([^\n\"]*)\")?')
path = "../infrastructure/{}-deploy/".format(mode)
for filename in sorted(os.listdir(path)):
if filename.startswith("deploy-resources"):
with open(os.path.join(path, filename), "r") as f:
contents = f.read()
results = re.findall(regex, contents)
update_mode_list(mode, required_resources, results)
# Check if any languages are missed
error_text = ''
for mode in modes:
for (resource_slug, languages) in required_resources[mode].items():
if languages:
error_text += f"\n{resource_slug} does not generate PDFs for the {mode} website for the following languages: {languages}"
if error_text:
raise Exception(error_text)
def update_mode_list(mode, required_resources, results):
for (resource_slug, language) in results:
if not language:
del required_resources[mode][resource_slug]
if language:
required_resources[mode][resource_slug].remove(language)
| """Tests for resource generation."""
import os
import re
from django.core import management
from tests.BaseTestWithDB import BaseTestWithDB
from resources.models import Resource
class ResourceGenerationTest(BaseTestWithDB):
"""Tests for resource generation."""
def test_all_resources_are_generated(self):
# Check all resources are generated for each langage
management.call_command("loadresources")
modes = ["dev", "prod"]
for mode in modes:
generated_resource_names = set()
path = "../infrastructure/{}-deploy/".format(mode)
for filename in sorted(os.listdir(path)):
if filename.startswith("deploy-resources"):
with open(os.path.join(path, filename), "r") as f:
contents = f.read()
results = re.findall(
'makeresources \"(?P<resource_name>[^\"]*)\"',
contents,
re.M
)
generated_resource_names.update(results)
self.assertEqual(
generated_resource_names,
set(Resource.objects.values_list("name", flat=True))
)
|
Use multiprocessing to get quicker updates from PyPI. | from functools import partial
import subprocess
import multiprocessing
import requests
def get_pkg_info(pkg_name, session):
r = session.get('http://pypi.python.org/pypi/%s/json' % (pkg_name,))
if r.status_code == requests.codes.ok:
return r.json
else:
raise ValueError('Package %r not found on PyPI.' % (pkg_name,))
def latest_version(pkg_name, session, silent=False):
try:
info = get_pkg_info(pkg_name, session)
except ValueError:
if silent:
return None
else:
raise
return info['info']['version']
def get_latest_versions(pkg_names):
with requests.session() as session:
pool = multiprocessing.Pool(min(12, len(pkg_names)))
get_latest = partial(latest_version, session=session, silent=True)
versions = pool.map(get_latest, pkg_names)
return zip(pkg_names, versions)
def get_installed_pkgs(editables=False):
for line in subprocess.check_output(['pip', 'freeze']).split('\n'):
if not line:
continue
if line.startswith('-e'):
if editables:
yield line.split('#egg=', 1)[1], None, True
else:
name, version = line.split('==')
yield name, version, False
| from functools import partial
import subprocess
import requests
def get_pkg_info(pkg_name, session):
r = session.get('http://pypi.python.org/pypi/%s/json' % (pkg_name,))
if r.status_code == requests.codes.ok:
return r.json
else:
raise ValueError('Package %r not found on PyPI.' % (pkg_name,))
def latest_version(pkg_name, session, silent=False):
try:
info = get_pkg_info(pkg_name, session)
except ValueError:
if silent:
return None
else:
raise
return info['info']['version']
def get_latest_versions(pkg_names):
with requests.session() as session:
get_latest = partial(latest_version, session=session, silent=True)
versions = map(get_latest, pkg_names)
return zip(pkg_names, versions)
def get_installed_pkgs(editables=False):
for line in subprocess.check_output(['pip', 'freeze']).split('\n'):
if not line:
continue
if line.startswith('-e'):
if editables:
yield line.split('#egg=', 1)[1], None, True
else:
name, version = line.split('==')
yield name, version, False
|
Support for reading deployment types from beans.xml
git-svn-id: 811cd8a17a8c3c0c263af499002feedd54a892d0@1531 1c488680-804c-0410-94cd-c6b725194a0e | package org.jboss.webbeans.tck;
import java.lang.annotation.Annotation;
import java.net.URL;
import java.util.List;
import org.jboss.jsr299.tck.api.DeploymentException;
import org.jboss.jsr299.tck.spi.StandaloneContainers;
import org.jboss.webbeans.ManagerImpl;
import org.jboss.webbeans.mock.MockBootstrap;
import org.jboss.webbeans.mock.MockWebBeanDiscovery;
public class StandaloneContainersImpl implements StandaloneContainers
{
public void deploy(List<Class<? extends Annotation>> enabledDeploymentTypes, Iterable<Class<?>> classes) throws DeploymentException
{
deploy(enabledDeploymentTypes, classes, null);
}
public void deploy(List<Class<? extends Annotation>> enabledDeploymentTypes, Iterable<Class<?>> classes, Iterable<URL> beansXml) throws DeploymentException
{
try
{
MockBootstrap bootstrap = new MockBootstrap();
ManagerImpl manager = bootstrap.getManager();
if (enabledDeploymentTypes != null)
{
manager.setEnabledDeploymentTypes(enabledDeploymentTypes);
}
MockWebBeanDiscovery discovery = new MockWebBeanDiscovery();
discovery.setWebBeanClasses(classes);
if (beansXml != null)
{
discovery.setWebBeansXmlFiles(beansXml);
}
bootstrap.setWebBeanDiscovery(discovery);
bootstrap.boot();
}
catch (Exception e)
{
throw new DeploymentException("Error deploying beans", e);
}
}
public void deploy(Iterable<Class<?>> classes) throws DeploymentException
{
deploy(null, classes, null);
}
public void deploy(Iterable<Class<?>> classes, Iterable<URL> beansXml) throws DeploymentException
{
deploy(null, classes, beansXml);
}
}
| package org.jboss.webbeans.tck;
import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.List;
import javax.inject.manager.Manager;
import org.jboss.jsr299.tck.api.DeploymentException;
import org.jboss.jsr299.tck.spi.StandaloneContainers;
import org.jboss.webbeans.ManagerImpl;
import org.jboss.webbeans.mock.MockBootstrap;
import org.jboss.webbeans.mock.MockWebBeanDiscovery;
public class StandaloneContainersImpl implements StandaloneContainers
{
public Manager deploy(List<Class<? extends Annotation>> enabledDeploymentTypes, Class<?>... classes) throws DeploymentException
{
try
{
MockBootstrap bootstrap = new MockBootstrap();
ManagerImpl manager = bootstrap.getManager();
if (enabledDeploymentTypes != null)
{
manager.setEnabledDeploymentTypes(enabledDeploymentTypes);
}
MockWebBeanDiscovery discovery = new MockWebBeanDiscovery();
discovery.setWebBeanClasses(Arrays.asList(classes));
bootstrap.setWebBeanDiscovery(discovery);
bootstrap.boot();
return manager;
}
catch (Exception e)
{
throw new DeploymentException("Error deploying beans", e);
}
}
public Manager deploy(java.lang.Class<?>... classes) throws DeploymentException
{
return deploy(null, classes);
}
}
|
Add path when calling object | <?php
namespace Politix\PolitikportalBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
// use Politix\PolitikportalBundle\Model;
class SourcesController extends Controller {
public function indexAction($name) {
$out['items'] = $this->getSource('tagesschau');
$out['name'] = $name;
return $this->render('PolitikportalBundle:Default:items.html.twig', $out);
}
function getSourceAction($source) {
$out['source'] = $source;
$sql = 'SELECT * FROM rss_items WHERE source LIKE "' . $source . '" ORDER BY pubDate DESC LIMIT 0,10';
$out['items'] = $this->getDB($sql);
return $this->render('PolitikportalBundle:Default:items.html.twig', $out);
}
function getSourcesAction() {
require ('/var/www/vhosts/politikportal.eu/subdomains/new/httpdocs/politix/src/Politix/PolitikportalBundle/Model/SourceModel.php');
$db = new Politix\PolitikportalBundle\Model\SourceModel();
$out['sources'] = $db->getSources;
return $this->render('PolitikportalBundle:Default:sources.html.twig', $out);
}
function getDB($sql) {
$conn = $this->container->get('database_connection');
return $conn->query($sql);
}
}
| <?php
namespace Politix\PolitikportalBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
// use Politix\PolitikportalBundle\Model;
class SourcesController extends Controller {
public function indexAction($name) {
$out['items'] = $this->getSource('tagesschau');
$out['name'] = $name;
return $this->render('PolitikportalBundle:Default:items.html.twig', $out);
}
function getSourceAction($source) {
$out['source'] = $source;
$sql = 'SELECT * FROM rss_items WHERE source LIKE "' . $source . '" ORDER BY pubDate DESC LIMIT 0,10';
$out['items'] = $this->getDB($sql);
return $this->render('PolitikportalBundle:Default:items.html.twig', $out);
}
function getSourcesAction() {
require ('/var/www/vhosts/politikportal.eu/subdomains/new/httpdocs/politix/src/Politix/PolitikportalBundle/Model/SourceModel.php');
$db = new SourceModel();
$out['sources'] = $db->getSources;
return $this->render('PolitikportalBundle:Default:sources.html.twig', $out);
}
function getDB($sql) {
$conn = $this->container->get('database_connection');
return $conn->query($sql);
}
}
|
Throw error to console if app fails to boot | <!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>{{ $title }}</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1">
<meta name="theme-color" content="{{ $forum->attributes->themePrimaryColor }}">
@foreach ($styles as $file)
<link rel="stylesheet" href="{{ str_replace(public_path(), '', $file) }}">
@endforeach
{!! $head !!}
</head>
<body>
@include($layout)
<div id="modal"></div>
<div id="alerts"></div>
@foreach ($scripts as $file)
<script src="{{ str_replace(public_path(), '', $file) }}"></script>
@endforeach
<script>
var app;
System.import('flarum/app').then(function(module) {
try {
app = module.default;
app.preload = {
data: {!! json_encode($data) !!},
document: {!! json_encode($document) !!},
session: {!! json_encode($session) !!}
};
initLocale(app);
app.boot();
} catch (e) {
document.write('<div class="container">Something went wrong.</div>');
throw e;
}
});
</script>
@if ($content)
<noscript>
{!! $content !!}
</noscript>
@endif
{!! $foot !!}
</body>
</html>
| <!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>{{ $title }}</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1">
<meta name="theme-color" content="{{ $forum->attributes->themePrimaryColor }}">
@foreach ($styles as $file)
<link rel="stylesheet" href="{{ str_replace(public_path(), '', $file) }}">
@endforeach
{!! $head !!}
</head>
<body>
@include($layout)
<div id="modal"></div>
<div id="alerts"></div>
@foreach ($scripts as $file)
<script src="{{ str_replace(public_path(), '', $file) }}"></script>
@endforeach
<script>
var app;
System.import('flarum/app').then(function(module) {
try {
app = module.default;
app.preload = {
data: {!! json_encode($data) !!},
document: {!! json_encode($document) !!},
session: {!! json_encode($session) !!}
};
initLocale(app);
app.boot();
} catch (e) {
document.write('<div class="container">Something went wrong.</div>');
}
});
</script>
@if ($content)
<noscript>
{!! $content !!}
</noscript>
@endif
{!! $foot !!}
</body>
</html>
|
Drop duplicates when listing transform types
Signed-off-by: Robert D Anderson <[email protected]> | /*
* This file is part of the DITA Open Toolkit project.
*
* Copyright 2011 Jarno Elovirta
*
* See the accompanying LICENSE file for applicable license.
*/
package org.dita.dost.platform;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
/**
* List transtypes integration action.
*
* @since 1.5.4
* @author Jarno Elovirta
*/
final class ListTranstypeAction extends ImportAction {
/**
* Get result.
*/
@Override
public void getResult(final ContentHandler buf) throws SAXException {
final String separator = paramTable.getOrDefault("separator", "|");
final List<String> v = valueSet.stream()
.map(fileValue -> fileValue.value)
.distinct()
.collect(Collectors.toList());
Collections.sort(v);
final StringBuilder retBuf = new StringBuilder();
for (final Iterator<String> i = v.iterator(); i.hasNext();) {
retBuf.append(i.next());
if (i.hasNext()) {
retBuf.append(separator);
}
}
final char[] ret = retBuf.toString().toCharArray();
buf.characters(ret, 0, ret.length);
}
@Override
public String getResult() {
throw new UnsupportedOperationException();
}
}
| /*
* This file is part of the DITA Open Toolkit project.
*
* Copyright 2011 Jarno Elovirta
*
* See the accompanying LICENSE file for applicable license.
*/
package org.dita.dost.platform;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
/**
* List transtypes integration action.
*
* @since 1.5.4
* @author Jarno Elovirta
*/
final class ListTranstypeAction extends ImportAction {
/**
* Get result.
*/
@Override
public void getResult(final ContentHandler buf) throws SAXException {
final String separator = paramTable.getOrDefault("separator", "|");
final List<String> v = valueSet.stream()
.map(fileValue -> fileValue.value)
.collect(Collectors.toList());
Collections.sort(v);
final StringBuilder retBuf = new StringBuilder();
for (final Iterator<String> i = v.iterator(); i.hasNext();) {
retBuf.append(i.next());
if (i.hasNext()) {
retBuf.append(separator);
}
}
final char[] ret = retBuf.toString().toCharArray();
buf.characters(ret, 0, ret.length);
}
@Override
public String getResult() {
throw new UnsupportedOperationException();
}
}
|
Use old array notation because gnomo is not updated
srsly 2.0. | <?php
class StatisticsHandler
{
function get()
{
/*if (isset($_GET['startDate']) && isset($_GET['endDate'])) {
$start = $_GET['startDate'];
$end = $_GET['endDate'];
global $conn;
$stmt = $conn->prepare("SELECT * FROM get_counts_per_month_year(:startDate, :endDate)");
$stmt->execute([':startDate' => $start, ':endDate' => $end]);
$result = $stmt->fetchAll();
echo json_encode($result);
return;
}*/
global /** @noinspection PhpUnusedLocalVariableInspection */
$smarty;
global $BASE_DIR;
include($BASE_DIR . 'pages/common/header.php');
include($BASE_DIR . 'pages/stats.php');
include($BASE_DIR . 'pages/common/footer.php');
}
function get_xhr()
{
if (isset($_GET['startDate']) && isset($_GET['endDate'])) {
$start = $_GET['startDate'];
$end = $_GET['endDate'];
global $conn;
$stmt = $conn->prepare("SELECT * FROM get_counts_per_month_year(:startDate, :endDate)");
$stmt->execute(array(':startDate' => $start, ':endDate' => $end));
$result = $stmt->fetchAll();
echo json_encode($result);
return;
}
global /** @noinspection PhpUnusedLocalVariableInspection */
$smarty;
global $BASE_DIR;
include($BASE_DIR . 'pages/stats.php');
}
}
| <?php
class StatisticsHandler
{
function get()
{
/*if (isset($_GET['startDate']) && isset($_GET['endDate'])) {
$start = $_GET['startDate'];
$end = $_GET['endDate'];
global $conn;
$stmt = $conn->prepare("SELECT * FROM get_counts_per_month_year(:startDate, :endDate)");
$stmt->execute([':startDate' => $start, ':endDate' => $end]);
$result = $stmt->fetchAll();
echo json_encode($result);
return;
}*/
global /** @noinspection PhpUnusedLocalVariableInspection */
$smarty;
global $BASE_DIR;
include($BASE_DIR . 'pages/common/header.php');
include($BASE_DIR . 'pages/stats.php');
include($BASE_DIR . 'pages/common/footer.php');
}
function get_xhr()
{
if (isset($_GET['startDate']) && isset($_GET['endDate'])) {
$start = $_GET['startDate'];
$end = $_GET['endDate'];
global $conn;
$stmt = $conn->prepare("SELECT * FROM get_counts_per_month_year(:startDate, :endDate)");
$stmt->execute([':startDate' => $start, ':endDate' => $end]);
$result = $stmt->fetchAll();
echo json_encode($result);
return;
}
global /** @noinspection PhpUnusedLocalVariableInspection */
$smarty;
global $BASE_DIR;
include($BASE_DIR . 'pages/stats.php');
}
}
|
Test complex polygons and nonsensical nested boxes | // Copyright 2012 - 2015 The ASCIIToSVG Contributors
// All rights reserved.
package asciitosvg
import "testing"
func TestNewCanvas(t *testing.T) {
data := `
+------+
|Editor|-------------+--------+
+------+ | |
| | v
v | +--------+
+------+ | |Document|
|Window| | +--------+
+------+ |
| |
+-----+-------+ |
| | |
v v |
+------+ +------+ |
|Window| |Window| |
+------+ +------+ |
| |
v |
+----+ |
|View| |
+----+ |
| |
v |
+--------+ |
|Document|<----+
+--------+
+----+
| |
+---+ +----+
| |
+-------------+
+----+
| |
| +---+
| |
| +---+
| |
+----+
+----+
| |
+---+ |
| |
+---+ |
| |
+----+
+-----+-------+
| | |
| | |
+----+-----+---- |
--------+----+-----+-------+---+
| | | | |
| | | | | | |
| | | | | | |
| | | | | | |
--------+----+-----+-------+---+-----+---+--+
| | | | | | | |
| | | | | | | |
| -+-----+-------+---+-----+ | |
| | | | | | | |
| | | | +-----+---+--+
| | | | |
| | | | |
--------+-----+-------+---------+---+-----
| | | | |
+-----+-------+---------+---+
`
NewCanvas([]byte(data))
}
| // Copyright 2012 - 2015 The ASCIIToSVG Contributors
// All rights reserved.
package asciitosvg
import "testing"
func TestNewCanvas(t *testing.T) {
data := `
+------+
|Editor|-------------+--------+
+------+ | |
| | v
v | +--------+
+------+ | |Document|
|Window| | +--------+
+------+ |
| |
+-----+-------+ |
| | |
v v |
+------+ +------+ |
|Window| |Window| |
+------+ +------+ |
| |
v |
+----+ |
|View| |
+----+ |
| |
v |
+--------+ |
|Document|<----+
+--------+
`
NewCanvas([]byte(data))
}
|
Revert "Revert "Added support for multiple files (excluding minified scripts)""
This reverts commit fde48e384ec241fef5d6c4c80a62e3f32f9cc7ab. | 'use strict';
module.exports = function (grunt) {
require('time-grunt')(grunt);
require('load-grunt-tasks')(grunt);
grunt.initConfig({
// Configurable paths
config: {
lintFiles: [
'**/*.js',
'!*.min.js'
]
},
jshint: {
options: {
jshintrc: '.jshintrc'
},
all: [
'<%= config.lintFiles %>'
]
},
jscs: {
options: {
config: '.jscsrc'
},
src: '<%= config.lintFiles %>'
},
uglify: {
build: {
files: {
'angular-bind-html-compile.min.js': 'angular-bind-html-compile.js'
}
}
}
});
grunt.registerTask('lint', [
'jshint',
'jscs'
]);
grunt.registerTask('test', [
'lint'
]);
grunt.registerTask('build', [
'uglify'
]);
};
| 'use strict';
module.exports = function (grunt) {
require('time-grunt')(grunt);
require('load-grunt-tasks')(grunt);
grunt.initConfig({
// Configurable paths
config: {
lintFiles: [
'angular-bind-html-compile.js'
]
},
jshint: {
options: {
jshintrc: '.jshintrc'
},
all: [
'<%= config.lintFiles %>'
]
},
jscs: {
options: {
config: '.jscsrc'
},
src: '<%= config.lintFiles %>'
},
uglify: {
build: {
files: {
'angular-bind-html-compile.min.js': 'angular-bind-html-compile.js'
}
}
}
});
grunt.registerTask('lint', [
'jshint',
'jscs'
]);
grunt.registerTask('test', [
'lint'
]);
grunt.registerTask('build', [
'uglify'
]);
};
|
Return dict with selected utxo list and total |
'''Communicate with local or remote peercoin-daemon via JSON-RPC'''
from operator import itemgetter
try:
from peercoin_rpc import Client
except:
raise EnvironmentError("peercoin_rpc library is required for this to work,\
use pip to install it.")
def select_inputs(cls, total_amount):
'''finds apropriate utxo's to include in rawtx, while being careful
to never spend old transactions with a lot of coin age.
Argument is intiger, returns list of apropriate UTXO's'''
utxo = []
utxo_sum = float(-0.01) ## starts from negative due to minimal fee
for tx in sorted(cls.listunspent(), key=itemgetter('confirmations')):
utxo.append({
"txid": tx["txid"],
"vout": tx["vout"],
"scriptSig": tx["scriptPubKey"],
"amount": tx["amount"]
})
utxo_sum += float(tx["amount"])
if utxo_sum >= total_amount:
return {'utxos':utxo, 'total':utxo_sum}
if utxo_sum < total_amount:
raise ValueError("Not enough funds.")
class RpcNode(Client):
select_inputs = select_inputs
@property
def is_testnet(self):
'''check if node is configured to use testnet or mainnet'''
if self.getinfo()["testnet"] is True:
return True
else:
return False
|
'''Communicate with local or remote peercoin-daemon via JSON-RPC'''
from operator import itemgetter
try:
from peercoin_rpc import Client
except:
raise EnvironmentError("peercoin_rpc library is required for this to work,\
use pip to install it.")
def select_inputs(cls, total_amount):
'''finds apropriate utxo's to include in rawtx, while being careful
to never spend old transactions with a lot of coin age.
Argument is intiger, returns list of apropriate UTXO's'''
utxo = []
utxo_sum = float(-0.01) ## starts from negative due to minimal fee
for tx in sorted(cls.listunspent(), key=itemgetter('confirmations')):
utxo.append({
"txid": tx["txid"],
"vout": tx["vout"],
"scriptSig": tx["scriptPubKey"],
"amount": cls.gettransaction(tx["txid"])["amount"]
})
utxo_sum += float(tx["amount"])
if utxo_sum >= total_amount:
return utxo
if utxo_sum < total_amount:
raise ValueError("Not enough funds.")
class RpcNode(Client):
select_inputs = select_inputs
@property
def is_testnet(self):
'''check if node is configured to use testnet or mainnet'''
if self.getinfo()["testnet"] is True:
return True
else:
return False
|
Add property to delay repeat | var React = require('react');
var { Repeat } = require('Immutable');
class ReactTypeInAndOut extends React.Component {
constructor (props) {
super(props);
var words = props.words;
words = words.reduce((acc, word) => {
// include empty string as start/end
word = [''].concat(word.split(''));
var forwards = word.map((lc, lIdx, lw) => {
return lw.slice(0, lIdx + 1).join('');
});
var backwards = forwards.slice(0, -1).reverse();
return acc.concat(forwards, backwards);
}, []);
this.state = {
words: words
};
}
startTyping (words) {
var start = 0;
var running = setInterval(() => {
this.setState({
currentWord: words[start]
});
start = (start + 1) % words.length;
if (start === 0) {
clearInterval(running);
setTimeout(this.startTyping.bind(this, words), this.props.delayRepeat);
}
}, this.props.speed);
}
componentDidMount () {
this.startTyping(this.state.words);
}
render () {
var currentWord = this.state.currentWord;
return <div>{currentWord}</div>;
}
}
ReactTypeInAndOut.propTypes = {
words: React.PropTypes.arrayOf(React.PropTypes.string),
speed: React.PropTypes.number,
delayRepeat: React.PropTypes.number
};
ReactTypeInAndOut.defaultProps = {
speed: 200,
delayRepeat: 0
};
export default ReactTypeInAndOut;
| var React = require('react');
var { Repeat } = require('Immutable');
class ReactTypeInAndOut extends React.Component {
constructor (props) {
super(props);
var words = props.words;
words = words.reduce((acc, word) => {
// include empty string as start/end
word = [''].concat(word.split(''));
var forwards = word.map((lc, lIdx, lw) => {
return lw.slice(0, lIdx + 1).join('');
});
var backwards = forwards.slice(0, -1).reverse();
return acc.concat(forwards, backwards);
}, []);
this.state = {
words: words
};
}
componentDidMount () {
var words = this.state.words;
var start = 0;
var running = setInterval(() => {
this.setState({
currentWord: words[start]
});
start = (start + 1) % words.length;
}, this.props.speed);
}
render () {
var currentWord = this.state.currentWord;
return <div>{currentWord}</div>;
}
}
ReactTypeInAndOut.propTypes = {
words: React.PropTypes.arrayOf(React.PropTypes.string),
speed: React.PropTypes.number
};
ReactTypeInAndOut.defaultProps = {
speed: 200
};
export default ReactTypeInAndOut;
|
Remove an invalid trove classifier.
* setup.py(setuptools.setup): Remove "Intended Audience :: BigDate"
since it's not in pypi's list of valid trove classifiers and
prevents successful upload of the package when present.
Change-Id: Iee487d1737a12158bb181d21ae841d07e0820e10 | import setuptools
from savanna.openstack.common import setup as common_setup
requires = common_setup.parse_requirements()
depend_links = common_setup.parse_dependency_links()
project = 'savanna'
setuptools.setup(
name=project,
version=common_setup.get_version(project, '0.1'),
description='Savanna project',
author='Mirantis Inc.',
author_email='[email protected]',
url='http://savanna.mirantis.com',
classifiers=[
'Environment :: OpenStack',
'Intended Audience :: Information Technology',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: Apache Software License',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
],
license='Apache Software License',
cmdclass=common_setup.get_cmdclass(),
packages=setuptools.find_packages(exclude=['bin']),
package_data={'savanna': ['resources/*.template']},
install_requires=requires,
dependency_links=depend_links,
include_package_data=True,
test_suite='nose.collector',
scripts=[
'bin/savanna-api',
'bin/savanna-manage',
],
py_modules=[],
data_files=[
('share/savanna',
[
'etc/savanna/savanna.conf.sample',
'etc/savanna/savanna.conf.sample-full',
]),
],
)
| import setuptools
from savanna.openstack.common import setup as common_setup
requires = common_setup.parse_requirements()
depend_links = common_setup.parse_dependency_links()
project = 'savanna'
setuptools.setup(
name=project,
version=common_setup.get_version(project, '0.1'),
description='Savanna project',
author='Mirantis Inc.',
author_email='[email protected]',
url='http://savanna.mirantis.com',
classifiers=[
'Environment :: OpenStack',
'Intended Audience :: Information Technology',
'Intended Audience :: System Administrators',
'Intended Audience :: BigDate',
'License :: OSI Approved :: Apache Software License',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
],
license='Apache Software License',
cmdclass=common_setup.get_cmdclass(),
packages=setuptools.find_packages(exclude=['bin']),
package_data={'savanna': ['resources/*.template']},
install_requires=requires,
dependency_links=depend_links,
include_package_data=True,
test_suite='nose.collector',
scripts=[
'bin/savanna-api',
'bin/savanna-manage',
],
py_modules=[],
data_files=[
('share/savanna',
[
'etc/savanna/savanna.conf.sample',
'etc/savanna/savanna.conf.sample-full',
]),
],
)
|
Hide Python 2.6 Exception.message deprecation warnings | """
Module containing package exception classes.
"""
class Invalid(Exception):
def __init__(self, message, exceptions=None, validator=None):
Exception.__init__(self, message, exceptions)
self.message = message
self.exceptions = exceptions
self.validator = validator
def __str__(self):
return self.message
__unicode__ = __str__
def __repr__(self):
if self.exceptions:
return 'validatish.Invalid("%s", exceptions=%s, validator=%s)' % (self.message, self.exceptions, self.validator)
else:
return 'validatish.Invalid("%s", validator=%s)' % (self.message, self.validator)
@property
def errors(self):
return list(_flatten(self._fetch_errors(), _keepstrings))
def _fetch_errors(self):
if self.exceptions is None:
yield self.message
else:
for e in self.exceptions:
yield e._fetch_errors()
# Hide Python 2.6 deprecation warning.
def _get_message(self): return self._message
def _set_message(self, message): self._message = message
message = property(_get_message, _set_message)
def _flatten(s, toiter=iter):
try:
it = toiter(s)
except TypeError:
yield s
else:
for elem in it:
for subelem in _flatten(elem, toiter):
yield subelem
def _keepstrings(seq):
if isinstance(seq, basestring):
raise TypeError
return iter(seq)
| """
Module containing package exception classes.
"""
class Invalid(Exception):
def __init__(self, message, exceptions=None, validator=None):
Exception.__init__(self, message, exceptions)
self.message = message
self.exceptions = exceptions
self.validator = validator
def __str__(self):
return self.message
__unicode__ = __str__
def __repr__(self):
if self.exceptions:
return 'validatish.Invalid("%s", exceptions=%s, validator=%s)' % (self.message, self.exceptions, self.validator)
else:
return 'validatish.Invalid("%s", validator=%s)' % (self.message, self.validator)
@property
def errors(self):
return list(_flatten(self._fetch_errors(), _keepstrings))
def _fetch_errors(self):
if self.exceptions is None:
yield self.message
else:
for e in self.exceptions:
yield e._fetch_errors()
def _flatten(s, toiter=iter):
try:
it = toiter(s)
except TypeError:
yield s
else:
for elem in it:
for subelem in _flatten(elem, toiter):
yield subelem
def _keepstrings(seq):
if isinstance(seq, basestring):
raise TypeError
return iter(seq)
|
Use session.store instead of session for Guard instance.
On September 30, commit 3816e425ae3fdaa69474763737d5e906e073c9a9 to
the Laravel framework changed the arguments of the Guard constructor,
so it now takes a Store object instead of a Session object. This one
line patch fixes the issue. | <?php namespace Ccovey\LdapAuth;
use Exception;
use adLDAP\adLDAP;
use Illuminate\Auth\Guard;
use Illuminate\Auth\AuthManager;
/**
*
*/
class LdapAuthManager extends AuthManager
{
/**
*
* @return \Config\Packages\Guard
*/
protected function createLdapDriver()
{
$provider = $this->createLdapProvider();
return new Guard($provider, $this->app['session.store']);
}
/**
*
* @return \Config\Packages\LdapUserProvider
*/
protected function createLdapProvider()
{
$ad = new adLDAP($this->getLdapConfig());
$model = null;
if ($this->app['config']['auth.model']) {
$model = $this->app['config']['auth.model'];
}
return new LdapAuthUserProvider($ad, $this->getAuthConfig(), $model);
}
protected function getAuthConfig()
{
if ( ! is_null($this->app['config']['auth']) ) {
return $this->app['config']['auth'];
}
throw new MissingAuthConfigException;
}
protected function getLdapConfig()
{
if (is_array($this->app['config']['adldap'])) return $this->app['config']['adldap'];
return array();
}
}
/**
* MissingAuthConfigException
*/
class MissingAuthConfigException extends Exception
{
function __construct()
{
$message = "Please Ensure a config file is present at app/config/auth.php";
parent::__construct($message);
}
}
| <?php namespace Ccovey\LdapAuth;
use Exception;
use adLDAP\adLDAP;
use Illuminate\Auth\Guard;
use Illuminate\Auth\AuthManager;
/**
*
*/
class LdapAuthManager extends AuthManager
{
/**
*
* @return \Config\Packages\Guard
*/
protected function createLdapDriver()
{
$provider = $this->createLdapProvider();
return new Guard($provider, $this->app['session']);
}
/**
*
* @return \Config\Packages\LdapUserProvider
*/
protected function createLdapProvider()
{
$ad = new adLDAP($this->getLdapConfig());
$model = null;
if ($this->app['config']['auth.model']) {
$model = $this->app['config']['auth.model'];
}
return new LdapAuthUserProvider($ad, $this->getAuthConfig(), $model);
}
protected function getAuthConfig()
{
if ( ! is_null($this->app['config']['auth']) ) {
return $this->app['config']['auth'];
}
throw new MissingAuthConfigException;
}
protected function getLdapConfig()
{
if (is_array($this->app['config']['adldap'])) return $this->app['config']['adldap'];
return array();
}
}
/**
* MissingAuthConfigException
*/
class MissingAuthConfigException extends Exception
{
function __construct()
{
$message = "Please Ensure a config file is present at app/config/auth.php";
parent::__construct($message);
}
} |
Add test for too short isin | package name.abuchen.portfolio.util;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class IsinTest
{
@Test
public void testValidIsin()
{
String ubsIsin = "CH0244767585";
assertTrue(Isin.isValid(ubsIsin));
String adidasIsin = "DE000A1EWWW0";
assertTrue(Isin.isValid(adidasIsin));
String toyotaIsin = "JP3633400001";
assertTrue(Isin.isValid(toyotaIsin));
}
@Test
public void testInvalidIsin()
{
String invalidUbsIsin = "CH0244767586"; // Wrong Checksum
assertFalse(Isin.isValid(invalidUbsIsin));
}
@Test
public void testIsinInvalidLength()
{
String isinTooLong = "CH0244767585222222";
assertFalse(Isin.isValid(isinTooLong));
String isinTooShort = "CH02381";
assertFalse(Isin.isValid(isinTooShort));
}
@Test
public void testIsinNull()
{
String nullIsin = null;
assertFalse(Isin.isValid(nullIsin));
}
@Test
public void testInvalidChar()
{
String invalidCharIsin = "ÜE0244767585";
assertFalse(Isin.isValid(invalidCharIsin));
}
}
| package name.abuchen.portfolio.util;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class IsinTest
{
@Test
public void testValidIsin()
{
String ubsIsin = "CH0244767585";
assertTrue(Isin.isValid(ubsIsin));
String adidasIsin = "DE000A1EWWW0";
assertTrue(Isin.isValid(adidasIsin));
String toyotaIsin = "JP3633400001";
assertTrue(Isin.isValid(toyotaIsin));
}
@Test
public void testInvalidIsin()
{
String invalidUbsIsin = "CH0244767586"; // Wrong Checksum
assertFalse(Isin.isValid(invalidUbsIsin));
}
@Test
public void testIsinTooLong()
{
String isinTooLong = "CH0244767585222222";
assertFalse(Isin.isValid(isinTooLong));
}
@Test
public void testIsinNull()
{
String nullIsin = null;
assertFalse(Isin.isValid(nullIsin));
}
@Test
public void testInvalidChar()
{
String invalidCharIsin = "ÜE0244767585";
assertFalse(Isin.isValid(invalidCharIsin));
}
}
|
Fix JUnit errors - 11E, 2F
Down from 13E, 2F
Fixed an error related to deleting tasks and unintentionally fixed
another error too. | package seedu.gtd.ui;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import seedu.gtd.model.task.ReadOnlyTask;
public class TaskCard extends UiPart{
private static final String FXML = "TaskListCard.fxml";
@FXML
private HBox cardPane;
@FXML
private Label name;
@FXML
private Label id;
@FXML
private Label dueDate;
@FXML
private Label address;
@FXML
private Label priority;
@FXML
private Label tags;
private ReadOnlyTask task;
private int displayedIndex;
public TaskCard(){
}
public static TaskCard load(ReadOnlyTask task, int displayedIndex){
TaskCard card = new TaskCard();
card.task = task;
card.displayedIndex = displayedIndex;
return UiPartLoader.loadUiPart(card);
}
@FXML
public void initialize() {
name.setText(task.getName().fullName);
id.setText(displayedIndex + ". ");
dueDate.setText(task.getDueDate().value);
address.setText(task.getAddress().value);
priority.setText(task.getPriority().value);
tags.setText(task.tagsString());
}
public HBox getLayout() {
return cardPane;
}
@Override
public void setNode(Node node) {
cardPane = (HBox)node;
}
@Override
public String getFxmlPath() {
return FXML;
}
} | package seedu.gtd.ui;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import seedu.gtd.model.task.ReadOnlyTask;
public class TaskCard extends UiPart{
private static final String FXML = "TaskListCard.fxml";
@FXML
private HBox cardPane;
@FXML
private Label name;
@FXML
private Label id;
@FXML
private Label phone;
@FXML
private Label address;
@FXML
private Label email;
@FXML
private Label tags;
private ReadOnlyTask task;
private int displayedIndex;
public TaskCard(){
}
public static TaskCard load(ReadOnlyTask task, int displayedIndex){
TaskCard card = new TaskCard();
card.task = task;
card.displayedIndex = displayedIndex;
return UiPartLoader.loadUiPart(card);
}
@FXML
public void initialize() {
name.setText(task.getName().fullName);
id.setText(displayedIndex + ". ");
phone.setText(task.getDueDate().value);
address.setText(task.getPriority().value);
email.setText(task.getAddress().value);
tags.setText(task.tagsString());
}
public HBox getLayout() {
return cardPane;
}
@Override
public void setNode(Node node) {
cardPane = (HBox)node;
}
@Override
public String getFxmlPath() {
return FXML;
}
} |
Remove entry from coverage reporter | package fixtures.report;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public final class CoverageReporter {
private static AutoRestReportService client = new AutoRestReportServiceImpl("http://localhost:3000");
private CoverageReporter() { }
public static void main(String[] args) throws Exception {
Map<String, Integer> report = client.getReport().getBody();
// Body cannot be null
report.put("putStringNull", 1);
report.put("OptionalIntegerParameter", 1);
report.put("OptionalStringParameter", 1);
report.put("OptionalClassParameter", 1);
report.put("OptionalArrayParameter", 1);
// Put must contain a body
report.put("OptionalImplicitBody", 1);
// OkHttp can actually overwrite header "Content-Type"
report.put("HeaderParameterProtectedKey", 1);
// Redirects not suppoted by OkHttp
report.put("HttpRedirect301Put", 1);
report.put("HttpRedirect302Patch", 1);
int total = report.size();
int hit = 0;
List<String> missing = new ArrayList<>();
for (Map.Entry<String, Integer> entry : report.entrySet()) {
if (entry.getValue() != 0) {
hit++;
} else {
missing.add(entry.getKey());
}
}
System.out.println(hit + " out of " + total + " tests hit. Missing tests:");
for (String scenario : missing) {
System.out.println(scenario);
}
}
}
| package fixtures.report;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public final class CoverageReporter {
private static AutoRestReportService client = new AutoRestReportServiceImpl("http://localhost:3000");
private CoverageReporter() { }
public static void main(String[] args) throws Exception {
Map<String, Integer> report = client.getReport().getBody();
// Body cannot be null
report.put("putStringNull", 1);
report.put("OptionalIntegerParameter", 1);
report.put("OptionalStringParameter", 1);
report.put("OptionalClassParameter", 1);
report.put("OptionalArrayParameter", 1);
// Put must contain a body
report.put("OptionalImplicitBody", 1);
// OkHttp can actually overwrite header "Content-Type"
report.put("HeaderParameterProtectedKey", 1);
// Redirects not suppoted by OkHttp
report.put("HttpRedirect301Put", 1);
report.put("HttpRedirect302Patch", 1);
report.put("FileStreamVeryLarge", 1);
int total = report.size();
int hit = 0;
List<String> missing = new ArrayList<>();
for (Map.Entry<String, Integer> entry : report.entrySet()) {
if (entry.getValue() != 0) {
hit++;
} else {
missing.add(entry.getKey());
}
}
System.out.println(hit + " out of " + total + " tests hit. Missing tests:");
for (String scenario : missing) {
System.out.println(scenario);
}
}
}
|
Fix builder to return a literal React component, and supply correct context/args | const babel = require('babel');
const ast = require('./ast');
const extraction = require('./extraction');
const freeVariables = require('./free-variables');
module.exports = function({Plugin, types: t}) {
return new Plugin('transformation', {
visitor: {
JSXElement: function(node, parent) {
if (ast.isElementMarker(node)) {
const vars = freeVariables.freeVariablesInMessage(node);
const message = extraction.extractElementMessage(node);
return t.callExpression(
t.memberExpression(
t.identifier('React'),
t.identifier('createElement')
),
[
t.identifier('I18N'),
t.objectExpression([
t.property('init', t.identifier('message'), t.literal(message)),
t.property('init', t.identifier('context'), t.identifier('this')),
t.property('init', t.identifier('args'), t.arrayExpression(
vars.map(v => t.identifier(v))
)),
t.property('init', t.identifier('fallback'), t.functionExpression(
null,
[],
t.blockStatement([
t.returnStatement(
t.callExpression(
t.memberExpression(
t.identifier('React'),
t.identifier('createElement')
),
[
t.literal('span'),
t.identifier('null'),
t.arrayExpression(node.children)
]
)
)
])
))
]),
t.identifier('null')
]
)
}
}
}
});
};
| const babel = require('babel');
const ast = require('./ast');
const extraction = require('./extraction');
const freeVariables = require('./free-variables');
module.exports = function({Plugin, types: t}) {
return new Plugin('transformation', {
visitor: {
JSXElement: function(node, parent) {
if (ast.isElementMarker(node)) {
const vars = freeVariables.freeVariablesInMessage(node);
const message = extraction.extractElementMessage(node);
return t.callExpression(
t.memberExpression(
t.identifier('React'),
t.identifier('createElement')
),
[
t.literal('I18N'),
t.objectExpression([
t.property('init', t.identifier('message'), t.literal(message)),
t.property('init', t.identifier('context'), t.arrayExpression(
vars.map(v => t.identifier(v))
)),
t.property('init', t.identifier('fallback'), t.functionExpression(
null,
[],
t.blockStatement([
t.returnStatement(
t.callExpression(
t.memberExpression(
t.identifier('React'),
t.identifier('createElement')
),
[
t.literal('span'),
t.identifier('null'),
t.arrayExpression(node.children)
]
)
)
])
))
]),
t.identifier('null')
]
)
}
}
}
});
};
|
Fix a bug that caused improper initialization with overrides | (function( $ ){
$.fn.placeholder = function(restoreOverride, removeOverride){
return $(this).each(function(){
var $this = $(this)
original_color = $this.css('color')
function remove(){
$this.css('color', original_color)
$this.val('')
}
function restore(){
$this.css('color', '#999')
$this.val($this.attr('placeholder'))
}
$this.parent('form').bind('submit', function(e){
if($this.val() == $this.attr('placeholder')) remove()
})
$this.bind('focus', function(){
if(!$this.val() || $this.val() == $this.attr('placeholder')){
removeOverride ? removeOverride() : remove()
}
})
$this.bind('blur', function(){
if(!$this.val()){
restoreOverride ? restoreOverride() : restore()
}
})
restoreOverride ? restoreOverride() : restore()
})
}
})( jQuery ) | (function( $ ){
$.fn.placeholder = function(restoreOverride, removeOverride){
return $(this).each(function(){
var $this = $(this)
original_color = $this.css('color')
function remove(){
$this.css('color', original_color)
$this.val('')
}
function restore(){
$this.css('color', '#999')
$this.val($this.attr('placeholder'))
}
$this.parent('form').bind('submit', function(e){
if($this.val() == $this.attr('placeholder')) remove()
})
$this.bind('focus', function(){
if(!$this.val() || $this.val() == $this.attr('placeholder')){
removeOverride ? removeOverride() : remove()
}
})
$this.bind('blur', function(){
if(!$this.val()){
restoreOverride ? restoreOverride() : restore()
}
})
restore()
})
}
})( jQuery ) |
Make Dotenv to search for .env file in the document root always | <?php
/**
* This helper package makes a database connection for package Kola\PotatoOrm\Model.
*
* @package Kola\PotatoOrm\Helper\DbConn
* @author Kolawole ERINOSO <[email protected]>
* @license MIT <https://opensource.org/licenses/MIT>
*/
namespace Kola\PotatoOrm\Helper;
use Kola\PotatoOrm\Exception\UnsuccessfulDbConnException as ConnEx;
use \PDO;
final class DbConn extends PDO implements DbConnInterface
{
/**
* Override the parent class PDO constructor to prevent instantiation-argument requirement
*/
public function __construct()
{
}
/**
* Make a database connection
*
* @return PDO|string
*/
public static function connect()
{
self::loadDotenv();
try {
$dbConn = new PDO(getenv('DB_ENGINE') . ':host=' . getenv('DB_HOST') . ';dbname=' . getenv('DB_DATABASE'), getenv('DB_USERNAME'), getenv('DB_PASSWORD'));
$dbConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (ConnEx $e) {
return $e->message();
}
return $dbConn;
}
/**
* Load Dotenv to grant getenv() access to environment variables in .env file
*/
private static function loadDotenv()
{
$dotenv = new \Dotenv\Dotenv($_SERVER['DOCUMENT_ROOT']);
$dotenv->load();
}
}
| <?php
/**
* This helper package makes a database connection for package Kola\PotatoOrm\Model.
*
* @package Kola\PotatoOrm\Helper\DbConn
* @author Kolawole ERINOSO <[email protected]>
* @license MIT <https://opensource.org/licenses/MIT>
*/
namespace Kola\PotatoOrm\Helper;
use Kola\PotatoOrm\Exception\UnsuccessfulDbConnException as ConnEx;
use \PDO;
final class DbConn extends PDO implements DbConnInterface
{
/**
* Override the parent class PDO constructor to prevent instantiation-argument requirement
*/
public function __construct()
{
}
/**
* Make a database connection
*
* @return PDO|string
*/
public static function connect()
{
self::loadDotenv();
try {
$dbConn = new PDO(getenv('DB_ENGINE') . ':host=' . getenv('DB_HOST') . ';dbname=' . getenv('DB_DATABASE'), getenv('DB_USERNAME'), getenv('DB_PASSWORD'));
$dbConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (ConnEx $e) {
return $e->message();
}
return $dbConn;
}
/**
* Load Dotenv to grant getenv() access to environment variables in .env file
*/
private static function loadDotenv()
{
$dotenv = new \Dotenv\Dotenv(__DIR__ . '/../..');
$dotenv->load();
}
}
|
Return all don't executed commands | <?php
namespace Command;
use Database\Connect;
use Config\Config;
class getData
{
/**
* setData constructor.
*
* @param \Aura\Web\Request $request
* @param \Aura\Web\Response $response
* @param \Aura\View\View $view
*/
public function __construct($request, $response, $view)
{
$status = 'success';
$secureToken = (new Config)->getConfig()['secure_token'];
$retrievedSecureToken = $request->query->get('key', '');
$host = $request->query->get('host', '');
if ($secureToken !== $retrievedSecureToken) {
$status = 'error';
$message = 'Incorrect secure token.';
} else {
try {
$message = json_encode($this->getCommands($host));
} catch (\Exception $e) {
$status = 'error';
$message = $e->getMessage();
}
}
$view->setData([
'status' => $status,
'message' => $message,
]);
$response->content->set($view->__invoke());
}
/**
* get all don't executed commands from database
*
* @param string $host
* @return array
* @throws \Exception
*/
protected function getCommands($host)
{
$query = (new\Database\Query)
->select()
->from('commands')
->cols([
'command_id',
'command',
'to_be_exec',
])
->where('executed = 0')
->where('consumed = 0')
->where("host = '$host'");
return (new Connect)->query($query)->fetchAll(\PDO::FETCH_ASSOC);
}
}
| <?php
namespace Command;
use Database\Connect;
use Config\Config;
class getData
{
/**
* setData constructor.
*
* @param \Aura\Web\Request $request
* @param \Aura\Web\Response $response
* @param \Aura\View\View $view
*/
public function __construct($request, $response, $view)
{
$status = 'success';
$message = '';
$secureToken = (new Config)->getConfig()['secure_token'];
$retrievedSecureToken = $request->query->get('key', '');
$host = $request->query->get('host', '');
if ($secureToken !== $retrievedSecureToken) {
$status = 'error';
$message = 'Incorrect secure token.';
} else {
$post = $request->post;
}
$view->setData([
'status' => $status,
'message' => $message,
]);
$response->content->set($view->__invoke());
}
protected function _getCommands($host)
{
$query = (new\Database\Query)
->select()
->from('commands')
->cols([
'command_id',
'command',
'to_be_exec',
])
->where('executed = 0')
->where('consumed = 0')
->where("host = '$host'");
return (new Connect)->query($query);
}
}
|
Replace bankid with fid to avoid duplicate config options. | """OFX downloader."""
from ofxtools.Client import OFXClient, BankAcct
from ofxtools.Types import DateTime
from yapsy.IPlugin import IPlugin
def make_date_kwargs(config):
return {k:DateTime().convert(v) for k,v in config.items() if k.startswith('dt')}
class OFXDownload(IPlugin):
"""OFX plugin class."""
def download(self, config):
"""Setup account info and credentials."""
client = OFXClient(
config['url'],
config['org'],
config['fid'],
version=config['version'],
appid=config['appid'],
appver=config['appver']
)
account = [BankAcct(config['fid'], config['acctnum'], config['type'])]
kwargs = make_date_kwargs(config)
request = client.statement_request(
config['ofxuser'],
config['ofxpswd'],
account,
**kwargs
)
response = client.download(request)
fname = '{}_{}.ofx'.format(config['fid'], config['acctnum'])
with open(fname, 'w') as ofxfile:
print(response.text, file=ofxfile)
return fname
| """OFX downloader."""
from ofxtools.Client import OFXClient, BankAcct
from ofxtools.Types import DateTime
from yapsy.IPlugin import IPlugin
def make_date_kwargs(config):
return {k:DateTime().convert(v) for k,v in config.items() if k.startswith('dt')}
class OFXDownload(IPlugin):
"""OFX plugin class."""
def download(self, config):
"""Setup account info and credentials."""
client = OFXClient(
config['url'],
config['org'],
config['fid'],
version=config['version'],
appid=config['appid'],
appver=config['appver']
)
account = [BankAcct(config['bankid'], config['acctnum'], config['type'])]
kwargs = make_date_kwargs(config)
request = client.statement_request(
config['ofxuser'],
config['ofxpswd'],
account,
**kwargs
)
response = client.download(request)
fname = '{}_{}.ofx'.format(config['bankid'], config['acctnum'])
with open(fname, 'w') as ofxfile:
print(response.text, file=ofxfile)
return fname
|
Call 'getSystemInfo' only on success | (function(globalSettings, $, _, window, undefined) {
var Application = window.Application,
settings = globalSettings.SysMonitor;
var SystemMonitorView = Backbone.View.extend({
initialize: function(options) {
this.templateSelectorPrefix = '#js-tmpl-sysmonitor-';
this.systemInfoTemplateSelector = this.templateSelectorPrefix + 'system-info';
this.getSystemInfo();
},
getTemplate: _.memoize(function(templateSelector) {
return $(templateSelector).html();
}),
setTemplate: function(templateSelector, data) {
var template = this.getTemplate(templateSelector);
this.$el.html(_.template(template, data));
},
getSystemInfo: function() {
var onSuccess = _.bind(function(response) {
this.setTemplate(this.systemInfoTemplateSelector, response.data);
_.delay(_.bind(this.getSystemInfo, this), 2000);
}, this);
Application.trigger('submit-form-ajax', {
params: {
action: settings.systemInfoUrl,
success: onSuccess
}
});
}
});
$(function() {
var systemMonitorView = new SystemMonitorView({
el: $('#js-sysmonitor-content')
});
});
})(window.Settings || {}, jQuery, _, window);
| (function(globalSettings, $, _, window, undefined) {
var Application = window.Application,
settings = globalSettings.SysMonitor;
var SystemMonitorView = Backbone.View.extend({
initialize: function(options) {
this.templateSelectorPrefix = '#js-tmpl-sysmonitor-';
this.systemInfoTemplateSelector = this.templateSelectorPrefix + 'system-info';
this.getSystemInfo();
},
getTemplate: _.memoize(function(templateSelector) {
return $(templateSelector).html();
}),
setTemplate: function(templateSelector, data) {
var template = this.getTemplate(templateSelector);
this.$el.html(_.template(template, data));
},
getSystemInfo: function() {
var onSuccess = _.bind(function(response) {
this.setTemplate(this.systemInfoTemplateSelector, response.data);
}, this);
Application.trigger('submit-form-ajax', {
params: {
action: settings.systemInfoUrl,
success: onSuccess
}
});
_.delay(_.bind(this.getSystemInfo, this), 2000);
}
});
$(function() {
var systemMonitorView = new SystemMonitorView({
el: $('#js-sysmonitor-content')
});
});
})(window.Settings || {}, jQuery, _, window);
|
Correct argument type for event collection creation | <?php
/**
* Copyright 2017 SURFnet B.V.
*
* 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.
*/
namespace Surfnet\StepupMiddleware\MiddlewareBundle\EventSourcing;
use Surfnet\StepupMiddleware\MiddlewareBundle\Exception\InvalidArgumentException;
final class EventCollection
{
/**
* @var string[]
*/
private $eventNames = [];
public function __construct(array $eventNames)
{
foreach ($eventNames as $eventName) {
if (!is_string($eventName) || empty($eventName)) {
throw InvalidArgumentException::invalidType('non-empty string', 'eventName', $eventName);
}
if (!class_exists($eventName)) {
throw new InvalidArgumentException(sprintf(
'Cannot create EventCollection: class "%s" does not exist',
$eventName
));
}
$this->eventNames[] = $eventName;
}
}
}
| <?php
/**
* Copyright 2017 SURFnet B.V.
*
* 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.
*/
namespace Surfnet\StepupMiddleware\MiddlewareBundle\EventSourcing;
use Surfnet\StepupMiddleware\MiddlewareBundle\Exception\InvalidArgumentException;
final class EventCollection
{
/**
* @var string[]
*/
private $eventNames = [];
public function __construct($eventNames)
{
foreach ($eventNames as $eventName) {
if (!is_string($eventName) || empty($eventName)) {
throw InvalidArgumentException::invalidType('non-empty string', 'eventName', $eventName);
}
if (!class_exists($eventName)) {
throw new InvalidArgumentException(sprintf(
'Cannot create EventCollection: class "%s" does not exist',
$eventName
));
}
$this->eventNames[] = $eventName;
}
}
}
|
Add --dev command line arg | import coloredlogs
import logging.handlers
from argparse import ArgumentParser
def get_args():
parser = ArgumentParser()
parser.add_argument(
"-H", "--host",
dest="host",
help="hostname to listen on"
)
parser.add_argument(
"-p", "--port",
dest="port",
help="port to listen on"
)
parser.add_argument(
"-v", "--verbose",
dest="verbose",
action="store_true",
default=False,
help="log debug messages"
)
parser.add_argument(
"--dev",
dest="dev",
action="store_true",
default=False,
help="run in dev mode"
)
parser.add_argument(
"--force-version",
dest="force_version",
help="make the server think it is the passed FORCE_VERSION or v1.8.5 if none provided",
nargs="?",
const="v1.8.5"
)
return parser.parse_args()
def configure(verbose=False):
logging_level = logging.INFO if verbose else logging.DEBUG
logging.captureWarnings(True)
log_format = "%(asctime)-20s %(module)-11s %(levelname)-8s %(message)s"
coloredlogs.install(
level=logging_level,
fmt=log_format
)
logger = logging.getLogger("virtool")
handler = logging.handlers.RotatingFileHandler("virtool.log", maxBytes=1000000, backupCount=5)
handler.setFormatter(logging.Formatter(log_format))
logger.addHandler(handler)
return logger
| import coloredlogs
import logging.handlers
from argparse import ArgumentParser
def get_args():
parser = ArgumentParser()
parser.add_argument(
"-H", "--host",
dest="host",
help="hostname to listen on"
)
parser.add_argument(
"-p", "--port",
dest="port",
help="port to listen on"
)
parser.add_argument(
"-v", "--verbose",
dest="verbose",
action="store_true",
default=False,
help="log debug messages"
)
parser.add_argument(
action="store_true",
default=False,
)
parser.add_argument(
"--force-version",
dest="force_version",
help="make the server think it is the passed FORCE_VERSION or v1.8.5 if none provided",
nargs="?",
const="v1.8.5"
)
return parser.parse_args()
def configure(verbose=False):
logging_level = logging.INFO if verbose else logging.DEBUG
logging.captureWarnings(True)
log_format = "%(asctime)-20s %(module)-11s %(levelname)-8s %(message)s"
coloredlogs.install(
level=logging_level,
fmt=log_format
)
logger = logging.getLogger("virtool")
handler = logging.handlers.RotatingFileHandler("virtool.log", maxBytes=1000000, backupCount=5)
handler.setFormatter(logging.Formatter(log_format))
logger.addHandler(handler)
return logger
|
Add doc string to Snippet.get_files | import os
from os import path
import glob
import json
import subprocess
class Snippet(object):
def __init__(self, config, username, snippet_id):
self.config = config
self.username = username
self.snippet_id = snippet_id
repo_parent = path.join(self.config.get('snippet_home'), username)
self.repo_path = glob.glob(path.join(repo_parent, '*{}'.format(self.snippet_id)))[0]
@staticmethod
def clone(url, clone_to):
#TODO: Add log line for notifying user.
# subprocess.DEVNULL
subprocess.call(['git', 'clone', url, clone_to])
@staticmethod
def pull(repo_dir):
# TODO: Add log line for notifying user.
subprocess.call(['git', '--git-dir={}/.git'.format(repo_dir), 'pull'])
def get_files(self):
""" Return files of snippet """
metadata_file = path.join(self.config.get('snippet_home'), 'metadata.json')
with open(metadata_file, 'r') as f:
data = json.loads(f.read())
for item in data['values']:
if item['id'] != self.snippet_id:
continue
return [f for f in os.listdir(self.repo_path) if path.isfile(path.join(self.repo_path, f))]
| import os
from os import path
import glob
import json
import subprocess
class Snippet(object):
def __init__(self, config, username, snippet_id):
self.config = config
self.username = username
self.snippet_id = snippet_id
repo_parent = path.join(self.config.get('snippet_home'), username)
self.repo_path = glob.glob(path.join(repo_parent, '*{}'.format(self.snippet_id)))[0]
@staticmethod
def clone(url, clone_to):
#TODO: Add log line for notifying user.
# subprocess.DEVNULL
subprocess.call(['git', 'clone', url, clone_to])
@staticmethod
def pull(repo_dir):
# TODO: Add log line for notifying user.
subprocess.call(['git', '--git-dir={}/.git'.format(repo_dir), 'pull'])
def get_files(self):
metadata_file = path.join(self.config.get('snippet_home'), 'metadata.json')
with open(metadata_file, 'r') as f:
data = json.loads(f.read())
for item in data['values']:
if item['id'] != self.snippet_id:
continue
return [f for f in os.listdir(self.repo_path) if path.isfile(path.join(self.repo_path, f))]
|
Add Wikidata as shared data repository for Commons.
Change-Id: Ie79e3157d016fc74e400ddc618c04f2d1d39f17d | # -*- coding: utf-8 -*-
__version__ = '$Id$'
from pywikibot import family
# The Wikimedia Commons family
class Family(family.WikimediaFamily):
def __init__(self):
super(Family, self).__init__()
self.name = 'commons'
self.langs = {
'commons': 'commons.wikimedia.org',
}
self.interwiki_forward = 'wikipedia'
self.category_redirect_templates = {
'commons': (u'Category redirect',
u'Categoryredirect',
u'Synonym taxon category redirect',
u'Invalid taxon category redirect',
u'Monotypic taxon category redirect',
u'See cat',
u'Seecat',
u'See category',
u'Catredirect',
u'Cat redirect',
u'Cat-red',
u'Catredir',
u'Redirect category'),
}
self.disambcatname = {
'commons': u'Disambiguation'
}
def ssl_pathprefix(self, code):
return "/wikipedia/commons"
def shared_data_repository(self, code, transcluded=False):
return ('wikidata', 'wikidata')
| # -*- coding: utf-8 -*-
__version__ = '$Id$'
from pywikibot import family
# The Wikimedia Commons family
class Family(family.WikimediaFamily):
def __init__(self):
super(Family, self).__init__()
self.name = 'commons'
self.langs = {
'commons': 'commons.wikimedia.org',
}
self.interwiki_forward = 'wikipedia'
self.category_redirect_templates = {
'commons': (u'Category redirect',
u'Categoryredirect',
u'Synonym taxon category redirect',
u'Invalid taxon category redirect',
u'Monotypic taxon category redirect',
u'See cat',
u'Seecat',
u'See category',
u'Catredirect',
u'Cat redirect',
u'Cat-red',
u'Catredir',
u'Redirect category'),
}
self.disambcatname = {
'commons': u'Disambiguation'
}
def ssl_pathprefix(self, code):
return "/wikipedia/commons"
|
Fix server config in client | module.exports = function(RED) {
var artemisNet = require('./artemisNet'),
artemisModel = require('./public/javascripts/worldmodel');
function ArtemisClient(config) {
RED.nodes.createNode(this, config);
var node = this;
this.status({fill:"red", shape:"ring",text:"disconnected"});
this.server = RED.nodes.getNode(config.server);
try {
this.status({fill:"yellow", shape:"ring",text:"connecting"});
artemisNet.connect(this.server, 10);
RegisterNetMsgAndSend('playerUpdate',node);
RegisterNetMsgAndSend('damcon',node);
RegisterNetMsgAndSend('playerShipDamage',node);
RegisterNetMsgAndSend('gameOver',node);
this.status({fill:"green",shape:"dot",text:"connected"});
}
catch(e) {
this.status({fill:"red", shape:"ring",text:"error"});
node.warn(e);
}
this.on('input', function(msg) {
msg.payload = msg.payload.toLowerCase();
node.send(msg);
});
this.on('close', function() {
artemisNet.disconnect();
});
}
function RegisterNetMsgAndSend(messageType,node){
artemisNet.on(messageType,function(data){
node.status({fill:"green",shape:"dot",text:messageType});
msg = {
payload: data,
topic: messageType
};
node.send(msg);
});
}
RED.nodes.registerType("artemis-client",ArtemisClient);
};
| module.exports = function(RED) {
var artemisNet = require('./artemisNet'),
artemisModel = require('./public/javascripts/worldmodel');
function ArtemisClient(config) {
RED.nodes.createNode(this,config);
var node = this;
this.status({fill:"red", shape:"ring",text:"disconnected"});
this.server = RED.nodes.getNode(config.server);
try {
this.status({fill:"yellow", shape:"ring",text:"connecting"});
artemisNet.connect(server, 10);
RegisterNetMsgAndSend('playerUpdate',node);
RegisterNetMsgAndSend('damcon',node);
RegisterNetMsgAndSend('playerShipDamage',node);
RegisterNetMsgAndSend('gameOver',node);
this.status({fill:"green",shape:"dot",text:"connected"});
}
catch(e) {
this.status({fill:"red", shape:"ring",text:"error"});
node.warn(e);
}
this.on('input', function(msg) {
msg.payload = msg.payload.toLowerCase();
node.send(msg);
});
this.on('close', function() {
artemisNet.disconnect();
});
}
function RegisterNetMsgAndSend(messageType,node){
artemisNet.on(messageType,function(data){
node.status({fill:"green",shape:"dot",text:messageType});
msg = {
payload: data,
topic: messageType
};
node.send(msg);
});
}
RED.nodes.registerType("artemis-client",ArtemisClient);
};
|
Work around deprecation warning with new cssutils versions. | import logging
import logging.handlers
from django.conf import settings
from django_assets.filter import BaseFilter
__all__ = ('CSSUtilsFilter',)
class CSSUtilsFilter(BaseFilter):
"""Minifies CSS by removing whitespace, comments etc., using the Python
`cssutils <http://cthedot.de/cssutils/>`_ library.
Note that since this works as a parser on the syntax level, so invalid
CSS input could potentially result in data loss.
"""
name = 'cssutils'
def setup(self):
import cssutils
self.cssutils = cssutils
try:
# cssutils logs to stdout by default, hide that in production
if not settings.DEBUG:
log = logging.getLogger('assets.cssutils')
log.addHandler(logging.handlers.MemoryHandler(10))
# Newer versions of cssutils print a deprecation warning
# for 'setlog'.
if hasattr(cssutils.log, 'setLog'):
func = cssutils.log.setLog
else:
func = cssutils.log.setlog
func(log)
except ImportError:
# During doc generation, Django is not going to be setup and will
# fail when the settings object is accessed. That's ok though.
pass
def apply(self, _in, out):
sheet = self.cssutils.parseString(_in.read())
self.cssutils.ser.prefs.useMinified()
out.write(sheet.cssText) | import logging
import logging.handlers
from django.conf import settings
from django_assets.filter import BaseFilter
__all__ = ('CSSUtilsFilter',)
class CSSUtilsFilter(BaseFilter):
"""Minifies CSS by removing whitespace, comments etc., using the Python
`cssutils <http://cthedot.de/cssutils/>`_ library.
Note that since this works as a parser on the syntax level, so invalid
CSS input could potentially result in data loss.
"""
name = 'cssutils'
def setup(self):
import cssutils
self.cssutils = cssutils
try:
# cssutils logs to stdout by default, hide that in production
if not settings.DEBUG:
log = logging.getLogger('assets.cssutils')
log.addHandler(logging.handlers.MemoryHandler(10))
cssutils.log.setlog(log)
except ImportError:
# During doc generation, Django is not going to be setup and will
# fail when the settings object is accessed. That's ok though.
pass
def apply(self, _in, out):
sheet = self.cssutils.parseString(_in.read())
self.cssutils.ser.prefs.useMinified()
out.write(sheet.cssText) |
Raise an error if no file is specified | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""Command line utility for proselint."""
import click
import os
import imp
def log_error(line, column, error_code, msg):
"""Print a message to the command line."""
click.echo(str(line) + ":" +
str(column) + " \t" +
error_code + ": " +
msg + " " +
"http://lifelinter.com/" + error_code)
@click.command()
@click.option('--version/--whatever', default=False)
@click.argument('file', default=False)
def proselint(version, file):
"""Run the linter."""
if not file:
raise ValueError("Specify a file to lint using the --file flag.")
# Extract functions from the checks folder.
checks = []
listing = os.listdir(
os.path.join(os.path.dirname(os.path.realpath(__file__)), "checks"))
for f in listing:
if f[-3:] == ".py" and not f == "__init__.py":
m = imp.load_source("rule", os.path.join("proselint", "checks", f))
checks.append(getattr(m, 'check'))
# Return the version number.
if version:
print "v0.0.1"
# Apply all the checks.
else:
with open(file, "r") as f:
text = f.read()
for check in checks:
errors = check(text)
for error in errors:
log_error(*error)
| #!/usr/bin/python
# -*- coding: utf-8 -*-
"""Command line utility for proselint."""
import click
import os
import imp
def log_error(line, column, error_code, msg):
"""Print a message to the command line."""
click.echo(str(line) + ":" +
str(column) + " \t" +
error_code + ": " +
msg + " " +
"http://lifelinter.com/" + error_code)
@click.command()
@click.option('--version/--whatever', default=False)
@click.argument('file', default=False)
def proselint(version, file):
"""Run the linter."""
# Extract functions from the checks folder.
checks = []
listing = os.listdir(
os.path.join(os.path.dirname(os.path.realpath(__file__)), "checks"))
for f in listing:
if f[-3:] == ".py" and not f == "__init__.py":
m = imp.load_source("rule", os.path.join("proselint", "checks", f))
checks.append(getattr(m, 'check'))
# Return the version number.
if version:
print "v0.0.1"
# Apply all the checks.
else:
with open(file, "r") as f:
text = f.read()
for check in checks:
errors = check(text)
for error in errors:
log_error(*error)
|
Update form to handle notes about funding | from django.forms import ModelForm, widgets
from .models import Fellow, Event, Expense, Blog
class FellowForm(ModelForm):
class Meta:
model = Fellow
exclude = [
"home_lon",
"home_lat",
"inauguration_year",
"funding_notes",
"mentor",
]
class EventForm(ModelForm):
class Meta:
model = Event
exclude = [
"status",
"budget_approve",
]
# We don't want to expose fellows' data
# so we will request the email
# and match on the database.
labels = {
'fellow': 'Fellow',
'url': "Event's homepage url",
'name': "Event's name",
}
class ExpenseForm(ModelForm):
class Meta:
model = Expense
exclude = [
'id',
'status',
]
class BlogForm(ModelForm):
class Meta:
model = Blog
fields = '__all__'
| from django.forms import ModelForm, widgets
from .models import Fellow, Event, Expense, Blog
class FellowForm(ModelForm):
class Meta:
model = Fellow
exclude = [
"home_lon",
"home_lat",
"inauguration_year",
"mentor",
]
class EventForm(ModelForm):
class Meta:
model = Event
exclude = [
"status",
"budget_approve",
]
# We don't want to expose fellows' data
# so we will request the email
# and match on the database.
labels = {
'fellow': 'Fellow',
'url': "Event's homepage url",
'name': "Event's name",
}
class ExpenseForm(ModelForm):
class Meta:
model = Expense
exclude = [
'id',
'status',
]
class BlogForm(ModelForm):
class Meta:
model = Blog
fields = '__all__'
|
Allow proxy minions to load static grains
Add the `__proxyenabled__` global var so the extra grains are loaded.
Inside the `config` function of the extra grains check if the minion
is a proxy, then try loading from <conf_file>/proxy.d/<proxy id>/grains. | # -*- coding: utf-8 -*-
from __future__ import absolute_import
# Import python libs
import os
# Import third party libs
import yaml
import logging
# Import salt libs
import salt.utils
__proxyenabled__ = ['*']
log = logging.getLogger(__name__)
def shell():
'''
Return the default shell to use on this system
'''
# Provides:
# shell
return {'shell': os.environ.get('SHELL', '/bin/sh')}
def config():
'''
Return the grains set in the grains file
'''
if 'conf_file' not in __opts__:
return {}
if os.path.isdir(__opts__['conf_file']):
if salt.utils.is_proxy():
gfn = os.path.join(
__opts__['conf_file'],
'proxy.d',
__opts__['id'],
'grains'
)
else:
gfn = os.path.join(
__opts__['conf_file'],
'grains'
)
else:
if salt.utils.is_proxy():
gfn = os.path.join(
os.path.dirname(__opts__['conf_file']),
'proxy.d',
__opts__['id'],
'grains'
)
else:
gfn = os.path.join(
os.path.dirname(__opts__['conf_file']),
'grains'
)
if os.path.isfile(gfn):
log.debug('Loading static grains from %s', gfn)
with salt.utils.fopen(gfn, 'rb') as fp_:
try:
return yaml.safe_load(fp_.read())
except Exception:
log.warning("Bad syntax in grains file! Skipping.")
return {}
return {}
| # -*- coding: utf-8 -*-
from __future__ import absolute_import
# Import python libs
import os
# Import third party libs
import yaml
import logging
# Import salt libs
import salt.utils
log = logging.getLogger(__name__)
def shell():
'''
Return the default shell to use on this system
'''
# Provides:
# shell
return {'shell': os.environ.get('SHELL', '/bin/sh')}
def config():
'''
Return the grains set in the grains file
'''
if 'conf_file' not in __opts__:
return {}
if os.path.isdir(__opts__['conf_file']):
gfn = os.path.join(
__opts__['conf_file'],
'grains'
)
else:
gfn = os.path.join(
os.path.dirname(__opts__['conf_file']),
'grains'
)
if os.path.isfile(gfn):
with salt.utils.fopen(gfn, 'rb') as fp_:
try:
return yaml.safe_load(fp_.read())
except Exception:
log.warning("Bad syntax in grains file! Skipping.")
return {}
return {}
|
Update JavaDoc references in EvalCommand | package org.metaborg.spoofax.shell.commands;
import java.util.function.Consumer;
import com.google.inject.Inject;
import com.google.inject.name.Named;
/**
* Command for evaluating the String as an expression in some language.
*/
public class SpoofaxEvaluationCommand implements IReplCommand {
private static final String DESCRIPTION = "Given an expression, evaluate it and show the result"
+ " of it when it succeeded, otherwise show the"
+ " error.";
private Consumer<String> onSuccess;
private Consumer<String> onError;
/**
* Create an {@link SpoofaxEvaluationCommand}.
*
* TODO: Create more specific interfaces for the hooks, which can accept more parameters. The
* parameters that are needed are currently unknown.
*
* @param onSuccess
* Called upon success by the created {@link SpoofaxEvaluationCommand}.
* @param onError
* Called upon an error by the created {@link SpoofaxEvaluationCommand}.
*/
@Inject
SpoofaxEvaluationCommand(@Named("onSuccess") Consumer<String> onSuccess,
@Named("onError") Consumer<String> onError) {
this.onSuccess = onSuccess;
this.onError = onError;
}
@Override
public String description() {
return DESCRIPTION;
}
/**
* Evaluate the given String as an expression in some language.
*
* @param args
* The String to be parsed and executed.
*/
public void execute(String... args) {
onSuccess.accept("Hai, good job.");
onError.accept("Oh no..");
}
}
| package org.metaborg.spoofax.shell.commands;
import java.util.function.Consumer;
import com.google.inject.Inject;
import com.google.inject.name.Named;
/**
* Command for evaluating the String as an expression in some language.
*/
public class SpoofaxEvaluationCommand implements IReplCommand {
private static final String DESCRIPTION = "Given an expression, evaluate it and show the result"
+ " of it when it succeeded, otherwise show the"
+ " error.";
private Consumer<String> onSuccess;
private Consumer<String> onError;
/**
* Create an {@link IEvaluationCommand}.
*
* TODO: Create more specific interfaces for the hooks, which can accept more parameters. The
* parameters that are needed are currently unknown.
*
* @param onSuccess
* Called upon success by the created {@link IEvaluationCommand}.
* @param onError
* Called upon an error by the created {@link IEvaluationCommand}.
*/
@Inject
SpoofaxEvaluationCommand(@Named("onSuccess") Consumer<String> onSuccess,
@Named("onError") Consumer<String> onError) {
this.onSuccess = onSuccess;
this.onError = onError;
}
@Override
public String description() {
return DESCRIPTION;
}
/**
* Evaluate the given String as an expression in some language.
*
* @param args
* The String to be parsed and executed.
*/
public void execute(String... args) {
onSuccess.accept("Hai, good job.");
onError.accept("Oh no..");
}
}
|
Fix home virtool version display | import React from "react";
import { get } from "lodash-es";
import { connect } from "react-redux";
import { Panel } from "react-bootstrap";
import { getSoftwareUpdates } from "../../updates/actions";
import { Icon } from "../../base";
class Welcome extends React.Component {
componentDidMount () {
this.props.onGet();
}
render () {
let version;
if (this.props.version) {
version = (
<small className="text-muted">
{this.props.version}
</small>
);
}
return (
<div className="container">
<Panel>
<Panel.Body>
<h3>Virtool {version}</h3>
<p>Viral infection diagnostics using next-generation sequencing</p>
<a
className="btn btn-default"
href="http://www.virtool.ca/"
target="_blank"
rel="noopener noreferrer"
>
<Icon name="globe" /> Website
</a>
</Panel.Body>
</Panel>
</div>
);
}
}
const mapStateToProps = (state) => ({
version: get(state.updates, "version")
});
const mapDispatchToProps = (dispatch) => ({
onGet: () => {
dispatch(getSoftwareUpdates());
}
});
export default connect(mapStateToProps, mapDispatchToProps)(Welcome);
| import React from "react";
import { get } from "lodash-es";
import { connect } from "react-redux";
import { Panel } from "react-bootstrap";
import { getSoftwareUpdates } from "../../updates/actions";
import { Icon } from "../../base";
class Welcome extends React.Component {
componentDidMount () {
this.props.onGet();
}
render () {
let version;
if (this.props.version) {
version = (
<small className="text-muted">
{this.props.version}
</small>
);
}
return (
<div className="container">
<Panel>
<Panel.Body>
<h3>Virtool {version}</h3>
<p>Viral infection diagnostics using next-generation sequencing</p>
<a
className="btn btn-default"
href="http://www.virtool.ca/"
target="_blank"
rel="noopener noreferrer"
>
<Icon name="globe" /> Website
</a>
</Panel.Body>
</Panel>
</div>
);
}
}
const mapStateToProps = (state) => ({
version: get(state.updates.software, "version")
});
const mapDispatchToProps = (dispatch) => ({
onGet: () => {
dispatch(getSoftwareUpdates());
}
});
export default connect(mapStateToProps, mapDispatchToProps)(Welcome);
|
Return null for an empty patch for now | import React from 'react';
import PropTypes from 'prop-types';
import yubikiri from 'yubikiri';
import {autobind} from '../helpers';
import ObserveModel from '../views/observe-model';
import FilePatchController from '../controllers/file-patch-controller';
export default class FilePatchContainer extends React.Component {
static propTypes = {
repository: PropTypes.object.isRequired,
stagingStatus: PropTypes.oneOf(['staged', 'unstaged']),
relPath: PropTypes.string.isRequired,
tooltips: PropTypes.object.isRequired,
}
constructor(props) {
super(props);
autobind(this, 'fetchData', 'renderWithData');
}
fetchData(repository) {
return yubikiri({
filePatch: repository.getFilePatchForPath(this.props.relPath, {staged: this.props.stagingStatus === 'staged'}),
isPartiallyStaged: repository.isPartiallyStaged(this.props.relPath),
});
}
render() {
return (
<ObserveModel model={this.props.repository} fetchData={this.fetchData}>
{this.renderWithData}
</ObserveModel>
);
}
renderWithData(data) {
if (data === null) {
return null;
}
if (data.filePatch === null) {
return null;
}
return (
<FilePatchController
isPartiallyStaged={data.isPartiallyStaged}
filePatch={data.filePatch}
stagingStatus={this.props.stagingStatus}
tooltips={this.props.tooltips}
/>
);
}
}
| import React from 'react';
import PropTypes from 'prop-types';
import yubikiri from 'yubikiri';
import {autobind} from '../helpers';
import ObserveModel from '../views/observe-model';
import FilePatchController from '../controllers/file-patch-controller';
export default class FilePatchContainer extends React.Component {
static propTypes = {
repository: PropTypes.object.isRequired,
stagingStatus: PropTypes.oneOf(['staged', 'unstaged']),
relPath: PropTypes.string.isRequired,
tooltips: PropTypes.object.isRequired,
}
constructor(props) {
super(props);
autobind(this, 'fetchData', 'renderWithData');
}
fetchData(repository) {
return yubikiri({
filePatch: repository.getFilePatchForPath(this.props.relPath, {staged: this.props.stagingStatus === 'staged'}),
isPartiallyStaged: repository.isPartiallyStaged(this.props.relPath),
});
}
render() {
return (
<ObserveModel model={this.props.repository} fetchData={this.fetchData}>
{this.renderWithData}
</ObserveModel>
);
}
renderWithData(data) {
if (data === null) {
return null;
}
return (
<FilePatchController
isPartiallyStaged={data.isPartiallyStaged}
filePatch={data.filePatch}
stagingStatus={this.props.stagingStatus}
tooltips={this.props.tooltips}
/>
);
}
}
|
Use two LSTM LM’s instead of single huge one | from keras.layers import LSTM, Input, Reshape
from keras.models import Model
from ..layers import LMMask, Projection
class LanguageModel(Model):
def __init__(self, n_batch, d_W, d_L, trainable=True):
"""
n_batch :: batch size for model application
d_L :: language model state dimension (and output vector size)
d_W :: input word embedding size (word features)
"""
w_n = Input(batch_shape=(n_batch, d_W), name='w_n', dtype='floatX')
w_nmask = Input(batch_shape=(n_batch, 1), name='w_nmask', dtype='int8')
# Prevent padded samples to affect internal state (and cause NaN loss in worst
# case) by masking them by using w_nmask masking values
w_nmasked = LMMask(0.)([Reshape((1, d_W))(w_n), w_nmask])
# Using stateful LSTM for language model - model fitting code resets the
# state after each sentence
w_np1Ei = LSTM(d_L,
trainable=trainable,
return_sequences=True,
stateful=True,
consume_less='gpu')(w_nmasked)
w_np1Ei = LSTM(d_L,
trainable=trainable,
return_sequences=False,
stateful=True,
consume_less='gpu')(w_np1Ei)
w_np1E = Projection(d_W)(w_np1Ei)
super(LanguageModel, self).__init__(input=[w_n, w_nmask], output=w_np1E, name='LanguageModel')
| from keras.layers import LSTM, Input, Reshape
from keras.models import Model
from ..layers import LMMask, Projection
class LanguageModel(Model):
def __init__(self, n_batch, d_W, d_L, trainable=True):
"""
n_batch :: batch size for model application
d_L :: language model state dimension (and output vector size)
d_W :: input word embedding size (word features)
"""
w_n = Input(batch_shape=(n_batch, d_W), name='w_n', dtype='floatX')
w_nmask = Input(batch_shape=(n_batch, 1), name='w_nmask', dtype='int8')
# Prevent padded samples to affect internal state (and cause NaN loss in worst
# case) by masking them by using another input value
w_nmasked = LMMask(0.)([Reshape((1, d_W))(w_n), w_nmask])
# Using stateful LSTM for language model - model fitting code resets the
# state after each sentence
w_np1Ei = LSTM(d_L,
trainable=trainable,
return_sequences=False,
stateful=True,
consume_less='gpu')(w_nmasked)
w_np1E = Projection(d_W)(w_np1Ei)
super(LanguageModel, self).__init__(input=[w_n, w_nmask], output=w_np1E, name='LanguageModel')
|
Check before casting a null. | package com.kolinkrewinkel.BitLimitBlockRegression;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
/**
* Created with IntelliJ IDEA.
* User: kolin
* Date: 7/14/13
* Time: 4:26 PM
* To change this template use File | Settings | File Templates.
*/
public class BlockGrowthManager {
private final BitLimitBlockRegression plugin;
public BlockGrowthManager(BitLimitBlockRegression plugin) {
this.plugin = plugin;
this.startRandomizationEvents();
}
private void startRandomizationEvents() {
class RepeatingGrowthTask implements Runnable {
private final BitLimitBlockRegression plugin;
public RepeatingGrowthTask(BitLimitBlockRegression plugin) {
this.plugin = plugin;
}
@Override
public void run() {
Object rawConditions = plugin.getConfig().get("conditions");
ArrayList<HashMap> conditionsList = null;
if (rawConditions != null) {
conditionsList = (ArrayList<HashMap>)rawConditions;
}
if (conditionsList != null) {
} else {
Bukkit.broadcastMessage(ChatColor.RED + "No conditions to grow were found.");
}
}
}
Bukkit.getScheduler().runTaskTimer(this.plugin, new RepeatingGrowthTask(this.plugin), 20L, 0L);
}
boolean randomWithLikelihood(float likelihood) {
Random rand = new Random();
return (rand.nextInt((int)likelihood * 100) == 0);
}
}
| package com.kolinkrewinkel.BitLimitBlockRegression;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
/**
* Created with IntelliJ IDEA.
* User: kolin
* Date: 7/14/13
* Time: 4:26 PM
* To change this template use File | Settings | File Templates.
*/
public class BlockGrowthManager {
private final BitLimitBlockRegression plugin;
public BlockGrowthManager(BitLimitBlockRegression plugin) {
this.plugin = plugin;
this.startRandomizationEvents();
}
private void startRandomizationEvents() {
class RepeatingGrowthTask implements Runnable {
private final BitLimitBlockRegression plugin;
public RepeatingGrowthTask(BitLimitBlockRegression plugin) {
this.plugin = plugin;
}
@Override
public void run() {
ArrayList<HashMap> conditionsList = (ArrayList<HashMap>) plugin.getConfig().get("conditions");
if (conditionsList != null) {
} else {
Bukkit.broadcastMessage(ChatColor.RED + "No conditions to grow were found.");
}
}
}
Bukkit.getScheduler().runTaskTimer(this.plugin, new RepeatingGrowthTask(this.plugin), 20L, 0L);
}
boolean randomWithLikelihood(float likelihood) {
Random rand = new Random();
return (rand.nextInt((int)likelihood * 100) == 0);
}
}
|
Add contrib package to deployment | #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
requirements = [
'pyjwt',
'requests',
'requests_oauthlib',
'money',
'babel',
'six',
]
setup(
name='fulfil_client',
version='0.13.2',
description="Fulfil REST API Client in Python",
long_description=readme + '\n\n' + history,
author="Fulfil.IO Inc.",
author_email='[email protected]',
url='https://github.com/fulfilio/fulfil-python-api',
packages=[
'fulfil_client',
'fulfil_client.contrib',
],
package_dir={
'fulfil_client': 'fulfil_client',
'fulfil_client.contrib': 'fulfil_client/contrib'
},
include_package_data=True,
install_requires=requirements,
license="ISCL",
zip_safe=False,
keywords='fulfil_client',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: ISC License (ISCL)',
'Natural Language :: English',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
],
setup_requires=['pytest-runner'],
tests_require=['pytest', 'redis'],
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
requirements = [
'pyjwt',
'requests',
'requests_oauthlib',
'money',
'babel',
'six',
]
setup(
name='fulfil_client',
version='0.13.2',
description="Fulfil REST API Client in Python",
long_description=readme + '\n\n' + history,
author="Fulfil.IO Inc.",
author_email='[email protected]',
url='https://github.com/fulfilio/fulfil-python-api',
packages=[
'fulfil_client',
],
package_dir={
'fulfil_client': 'fulfil_client'
},
include_package_data=True,
install_requires=requirements,
license="ISCL",
zip_safe=False,
keywords='fulfil_client',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: ISC License (ISCL)',
'Natural Language :: English',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
],
setup_requires=['pytest-runner'],
tests_require=['pytest', 'redis'],
)
|
Fix missing space between base icon classes and extra icon classes. | <?php
/**
* FontAwesome Helper
*
* PHP 5
*
* @copyright Copyright (c) Sylvain Lévesque (http://www.gezere.com)
* @link http://www.gezere.com
* @package app.View.Helper
*/
class FontawesomeHelper extends AppHelper {
/**
* Create a Fontawesome Icon
*
* Inspired by @webandcow Thanks !
*
* @param string $iconLabel label of the icon
* @param array $classes like 'fixed-width', 'large', '2x', etc.
* @param array $attributes more attributes for the tag
* @return string
*/
public function icon($iconLabel, $classes = array(), $attributes = array()) {
$class = '';
// Added more classes to the generated icon html tag.
if( isset( $attributes[ 'class' ] ) ) {
$class = ' ' . $attributes[ 'class' ];
unset( $attributes[ 'class' ] );
}
$more = '';
if (!empty($classes)) {
foreach ($classes as $opt) {
$class .= ' fa-' . $opt;
}
}
if (!empty($attributes)) {
foreach ($attributes as $key => $attr) {
$more .= ' ' . $key . '="' . $attr . '"';
}
}
return '<i class="fa fa-' . $iconLabel . $class . '"' . $more . '></i>';
}
}
| <?php
/**
* FontAwesome Helper
*
* PHP 5
*
* @copyright Copyright (c) Sylvain Lévesque (http://www.gezere.com)
* @link http://www.gezere.com
* @package app.View.Helper
*/
class FontawesomeHelper extends AppHelper {
/**
* Create a Fontawesome Icon
*
* Inspired by @webandcow Thanks !
*
* @param string $iconLabel label of the icon
* @param array $classes like 'fixed-width', 'large', '2x', etc.
* @param array $attributes more attributes for the tag
* @return string
*/
public function icon($iconLabel, $classes = array(), $attributes = array()) {
$class = '';
// Added more classes to the generated icon html tag.
if( isset( $attributes[ 'class' ] ) ) {
$class = $attributes[ 'class' ];
unset( $attributes[ 'class' ] );
}
$more = '';
if (!empty($classes)) {
foreach ($classes as $opt) {
$class .= ' fa-' . $opt;
}
}
if (!empty($attributes)) {
foreach ($attributes as $key => $attr) {
$more .= ' ' . $key . '="' . $attr . '"';
}
}
return '<i class="fa fa-' . $iconLabel . $class . '"' . $more . '></i>';
}
}
|
Set attachment color based on log level | import json
import traceback
from logging import Handler, CRITICAL, ERROR, WARNING
from slacker import Slacker
ERROR_COLOR = 'danger' # color name is built in to Slack API
WARNING_COLOR = 'warning' # color name is built in to Slack API
INFO_COLOR = '#439FE0'
COLORS = {
CRITICAL: ERROR_COLOR,
ERROR: ERROR_COLOR,
WARNING: WARNING_COLOR
}
class SlackLogHandler(Handler):
def __init__(self, api_key, channel, stack_trace=False, username='Python logger', icon_url=None, icon_emoji=None):
Handler.__init__(self)
self.slack_chat = Slacker(api_key)
self.channel = channel
self.stack_trace = stack_trace
self.username = username
self.icon_url = icon_url
self.icon_emoji = icon_emoji if (icon_emoji or icon_url) else ':heavy_exclamation_mark:'
if not self.channel.startswith('#'):
self.channel = '#' + self.channel
def emit(self, record):
message = str(record.getMessage())
attachments = [{
'fallback': message,
'color': COLORS.get(self.level, INFO_COLOR),
'text': '\n'.join(traceback.format_exception(*record.exc_info))
}]
self.slack_chat.chat.post_message(
text=message,
channel=self.channel,
username=self.username,
icon_url=self.icon_url,
icon_emoji=self.icon_emoji,
attachments=json.dumps(attachments)
)
| import json
import traceback
from logging import Handler
from slacker import Slacker
class SlackLogHandler(Handler):
def __init__(self, api_key, channel, stack_trace=False, username='Python logger', icon_url=None, icon_emoji=None):
Handler.__init__(self)
self.slack_chat = Slacker(api_key)
self.channel = channel
self.stack_trace = stack_trace
self.username = username
self.icon_url = icon_url
self.icon_emoji = icon_emoji if (icon_emoji or icon_url) else ':heavy_exclamation_mark:'
if not self.channel.startswith('#'):
self.channel = '#' + self.channel
def emit(self, record):
message = str(record.getMessage())
attachments = [{
'fallback': message,
'color': 'danger',
'text': '\n'.join(traceback.format_exception(*record.exc_info))
}]
self.slack_chat.chat.post_message(
text=message,
channel=self.channel,
username=self.username,
icon_url=self.icon_url,
icon_emoji=self.icon_emoji,
attachments=json.dumps(attachments)
)
|
Fix meetup date in builder | <?php
namespace Techlancaster\Bundle\WebBundle\Menu;
use Knp\Menu\FactoryInterface;
use Symfony\Component\DependencyInjection\ContainerAware;
class Builder extends ContainerAware
{
public function mainMenu(FactoryInterface $factory, array $options)
{
$menu = $factory->createItem('root');
$menu->addChild('Home', array('route' => 'techlancaster_web_homepage'));
$menu->addChild('Resources for Meetups', array('route' => 'techlancaster_resources'));
$menu->addChild('Calendar', array('uri' => '/#calendar'));
return $menu;
}
public function rightMenu(FactoryInterface $factory, array $options)
{
$menu = $factory->createItem('root');
$menu->addChild('Meetup - October 18th', array('route' => 'techlancaster_meetup'));
$menu->addChild('Members', array('route' => 'fos_user_security_login'));
if ($this->container->get('security.context')->isGranted('ROLE_USER')) {
$menu['Members']->addChild('Logout', array('route' => 'fos_user_security_logout'));
} else {
$menu['Members']->addChild('Login', array('route' => 'fos_user_security_login'));
$menu['Members']->addChild('Register', array('route' => 'fos_user_registration_register'));
}
return $menu;
}
}
| <?php
namespace Techlancaster\Bundle\WebBundle\Menu;
use Knp\Menu\FactoryInterface;
use Symfony\Component\DependencyInjection\ContainerAware;
class Builder extends ContainerAware
{
public function mainMenu(FactoryInterface $factory, array $options)
{
$menu = $factory->createItem('root');
$menu->addChild('Home', array('route' => 'techlancaster_web_homepage'));
$menu->addChild('Resources for Meetups', array('route' => 'techlancaster_resources'));
$menu->addChild('Calendar', array('uri' => '/#calendar'));
return $menu;
}
public function rightMenu(FactoryInterface $factory, array $options)
{
$menu = $factory->createItem('root');
$menu->addChild('Meetup - September 20th', array('route' => 'techlancaster_meetup'));
$menu->addChild('Members', array('route' => 'fos_user_security_login'));
if ($this->container->get('security.context')->isGranted('ROLE_USER')) {
$menu['Members']->addChild('Logout', array('route' => 'fos_user_security_logout'));
} else {
$menu['Members']->addChild('Login', array('route' => 'fos_user_security_login'));
$menu['Members']->addChild('Register', array('route' => 'fos_user_registration_register'));
}
return $menu;
}
}
|
Make tests work with php 5.4 | <?php
use PHPUnit\Framework\TestCase;
use Ratchet\Client\Connector;
use React\EventLoop\Factory;
use React\Promise\RejectedPromise;
class ConnectorTest extends TestCase
{
public function uriDataProvider() {
return [
['ws://127.0.0.1', 'tcp://127.0.0.1:80'],
['wss://127.0.0.1', 'tls://127.0.0.1:443'],
['ws://127.0.0.1:1234', 'tcp://127.0.0.1:1234'],
['wss://127.0.0.1:4321', 'tls://127.0.0.1:4321']
];
}
/**
* @dataProvider uriDataProvider
*/
public function testSecureConnectionUsesTlsScheme($uri, $expectedConnectorUri) {
$loop = Factory::create();
$connector = $this->getMock('React\Socket\ConnectorInterface');
$connector->expects($this->once())
->method('connect')
->with($this->callback(function ($uri) use ($expectedConnectorUri) {
return $uri === $expectedConnectorUri;
}))
// reject the promise so that we don't have to mock a connection here
->willReturn(new RejectedPromise(new Exception('')));
$pawlConnector = new Connector($loop, $connector);
$pawlConnector($uri);
}
}
| <?php
use PHPUnit\Framework\TestCase;
use Ratchet\Client\Connector;
use React\EventLoop\Factory;
use React\Promise\RejectedPromise;
use React\Socket\ConnectorInterface as ReactConnector;
class ConnectorTest extends TestCase
{
public function uriDataProvider() {
return [
['ws://127.0.0.1', 'tcp://127.0.0.1:80'],
['wss://127.0.0.1', 'tls://127.0.0.1:443'],
['ws://127.0.0.1:1234', 'tcp://127.0.0.1:1234'],
['wss://127.0.0.1:4321', 'tls://127.0.0.1:4321']
];
}
/**
* @requires PHP 5.5
* @dataProvider uriDataProvider
*/
public function testSecureConnectionUsesTlsScheme($uri, $expectedConnectorUri) {
$loop = Factory::create();
$connector = $this->getMock(ReactConnector::class);
$connector->expects($this->once())
->method('connect')
->with($this->callback(function ($uri) use ($expectedConnectorUri) {
return $uri === $expectedConnectorUri;
}))
// reject the promise so that we don't have to mock a connection here
->willReturn(new RejectedPromise(new Exception('')));
$pawlConnector = new Connector($loop, $connector);
$pawlConnector($uri);
}
}
|
Document the application name parameter. | <?php
namespace Nubs\PwMan;
use Exception;
/**
* Manage the collection of passwords.
*/
class PasswordManager
{
/** @type array<array> The passwords. */
private $_passwords;
/**
* Initialize the password manager.
*
* @param array<array> The passwords.
*/
public function __construct(array $passwords)
{
$this->_passwords = $passwords;
}
/**
* Find all the passwords that match the given application name.
*
* The application name is used as a regex.
*
* @param string $application The application name.
* @return array<array> The passwords for the applications that match the
* application.
*/
public function matchingApplication($application)
{
$result = [];
foreach ($this->_passwords as $key => $value) {
if (preg_match("/{$application}/i", $key)) {
$result[$key] = $value;
}
}
return $result;
}
/**
* Add the new application to the password list.
*
* @param string $name The unique application name.
* @param array $newApplication The application information.
* @return void
*/
public function addPassword($name, array $newApplication)
{
if (isset($this->_passwords[$name])) {
throw new Exception("Password already exists for {$name}");
}
$this->_passwords[$name] = $newApplication;
}
/**
* Get the passwords.
*
* @return array<array> The passwords.
*/
public function getPasswords()
{
return $this->_passwords;
}
}
| <?php
namespace Nubs\PwMan;
use Exception;
/**
* Manage the collection of passwords.
*/
class PasswordManager
{
/** @type array<array> The passwords. */
private $_passwords;
/**
* Initialize the password manager.
*
* @param array<array> The passwords.
*/
public function __construct(array $passwords)
{
$this->_passwords = $passwords;
}
/**
* Find all the passwords that match the given application name.
*
* The application name is used as a regex.
*
* @param string $application The application name.
* @return array<array> The passwords for the applications that match the
* application.
*/
public function matchingApplication($application)
{
$result = [];
foreach ($this->_passwords as $key => $value) {
if (preg_match("/{$application}/i", $key)) {
$result[$key] = $value;
}
}
return $result;
}
/**
* Add the new application to the password list.
*
* @param array $newApplication The application information.
* @return void
*/
public function addPassword($name, array $newApplication)
{
if (isset($this->_passwords[$name])) {
throw new Exception("Password already exists for {$name}");
}
$this->_passwords[$name] = $newApplication;
}
/**
* Get the passwords.
*
* @return array<array> The passwords.
*/
public function getPasswords()
{
return $this->_passwords;
}
}
|
Clean up autocomplete API load code
Move the logic to a separate function, call it from componentDidMount(). | 'use strict';
import React, { Component, PropTypes } from 'react';
import Button from './Button';
import TextInput from './TextInput';
import { destTextInputStyle, errorMessageStyle } from '../stylesheets/styles';
class CreateTripPage extends Component {
componentDidMount() {
this.loadGoogleAutocompleteAPI();
}
render() {
const {
error,
onCreateTripPress,
onEnterTitle
} = this.props;
return (
<div>
<h1>New Trip</h1>
<div>
<TextInput
onChange={onEnterTitle}
placeholder="Trip Title"
/>
<TextInput
id="destinationInput"
placeholder="Where do you want to go?"
style={destTextInputStyle}
/>
<div style={errorMessageStyle}>{error}</div>
<Button label="Create Trip" onClick={onCreateTripPress} />
</div>
</div>
);
}
loadGoogleAutocompleteAPI() {
const { onEnterDestination } = this.props;
// API documentation: https://developers.google.com/maps/documentation/javascript/places-autocomplete#add_autocomplete
const input = document.getElementById('destinationInput');
const options = { types: ['(regions)'] };
const ac = new window.google.maps.places.Autocomplete(input, options);
ac.addListener(
'place_changed',
() => { onEnterDestination(ac.getPlace()); }
);
}
}
CreateTripPage.propTypes = {
error: PropTypes.string,
onCreateTripPress: PropTypes.func.isRequired,
onEnterTitle: PropTypes.func.isRequired,
onEnterDestination: PropTypes.func.isRequired
};
export default CreateTripPage;
| 'use strict';
import React, { Component, PropTypes } from 'react';
import Button from './Button';
import TextInput from './TextInput';
import { destTextInputStyle, errorMessageStyle } from '../stylesheets/styles';
class CreateTripPage extends Component {
componentDidMount() {
const { onEnterDestination } = this.props;
// API documentation: https://developers.google.com/maps/documentation/javascript/places-autocomplete#add_autocomplete
const input = document.getElementById('destinationInput');
const options = { types: ['(regions)'] };
const ac = new window.google.maps.places.Autocomplete(input, options);
ac.addListener('place_changed', destinationChanged);
function destinationChanged() {
onEnterDestination(ac.getPlace());
}
}
render() {
const {
error,
onCreateTripPress,
onEnterTitle
} = this.props;
return (
<div>
<h1>New Trip</h1>
<div>
<TextInput
onChange={onEnterTitle}
placeholder="Trip Title"
/>
<TextInput
id="destinationInput"
placeholder="Where do you want to go?"
style={destTextInputStyle}
/>
<div style={errorMessageStyle}>{error}</div>
<Button label="Create Trip" onClick={onCreateTripPress} />
</div>
</div>
);
}
}
CreateTripPage.propTypes = {
error: PropTypes.string,
onCreateTripPress: PropTypes.func.isRequired,
onEnterTitle: PropTypes.func.isRequired,
onEnterDestination: PropTypes.func.isRequired
};
export default CreateTripPage;
|
Add Ordering and PaginationMixin on Listview | from django.views.generic import DetailView
from django.views.generic import ListView
from django.shortcuts import redirect, render
from pure_pagination import PaginationMixin
from .forms import PresentationCreateForm
from .models import Presentation, Slide
class PresentationList(PaginationMixin, ListView):
model = Presentation
paginate_by = 9
context_object_name = 'presentations'
ordering = ['-pk']
class PresentationDetail(DetailView):
model = Presentation
context_object_name = 'presentation'
template_name = 'presentation/presentation_list.html'
def presentation_create(request):
form = PresentationCreateForm(request.POST)
if request.method == 'POST':
if form.is_valid():
presentation = Presentation.objects.create(
subject=form.cleaned_data.get('subject'),
author=request.user,
is_public=form.cleaned_data.get('is_public')
)
slide_list = request.POST.getlist('slide_list[]', [])
for slide in slide_list:
Slide.objects.create(
presentation=presentation,
slide_order=slide['slide_order'],
markdown=slide['markdown'],
html=slide['html'],
)
return redirect('presentation:list')
context = {'form': form}
return render(request, 'presentation/presentation_create.html', context)
| from django.views.generic import DetailView
from django.views.generic import ListView
from django.shortcuts import redirect, render
from .forms import PresentationCreateForm
from .models import Presentation, Slide
class PresentationList(ListView):
model = Presentation
paginate_by = 9
context_object_name = 'presentations'
class PresentationDetail(DetailView):
model = Presentation
context_object_name = 'presentation'
template_name = 'presentation/presentation_list.html'
def presentation_create(request):
form = PresentationCreateForm(request.POST)
if request.method == 'POST':
if form.is_valid():
presentation = Presentation.objects.create(
subject=form.cleaned_data.get('subject'),
author=request.user,
is_public=form.cleaned_data.get('is_public')
)
slide_list = request.POST.getlist('slide_list[]', [])
for slide in slide_list:
Slide.objects.create(
presentation=presentation,
slide_order=slide['slide_order'],
markdown=slide['markdown'],
html=slide['html'],
)
return redirect('presentation:list')
context = {'form': form}
return render(request, 'presentation/presentation_create.html', context)
|
Create metaproject with user-provided description. | # -*- coding: utf-8 -*-
# Ingestion service: create a metaproject (tag) with user-defined name in given space
def process(transaction, parameters, tableBuilder):
"""Create a project with user-defined name in given space.
"""
# Prepare the return table
tableBuilder.addHeader("success")
tableBuilder.addHeader("message")
# Add a row for the results
row = tableBuilder.addRow()
# Retrieve parameters from client
username = parameters.get("userName")
metaprojectCode = parameters.get("metaprojectCode")
metaprojectDescr = parameters.get("metaprojectDescr")
if metaprojectDescr is None:
metaprojectDescr = ""
# Try retrieving the metaproject (tag)
metaproject = transaction.getMetaproject(metaprojectCode, username)
if metaproject is None:
# Create the metaproject (tag)
metaproject = transaction.createNewMetaproject(metaprojectCode,
metaprojectDescr,
username)
# Check that creation was succcessful
if metaproject is None:
success = "false"
message = "Could not create metaproject " + metaprojectCode + "."
else:
success = "true"
message = "Tag " + metaprojectCode + " successfully created."
else:
success = "false"
message = "Tag " + metaprojectCode + " exists already."
# Add the results to current row
row.setCell("success", success)
row.setCell("message", message)
| # -*- coding: utf-8 -*-
# Ingestion service: create a metaproject (tag) with user-defined name in given space
def process(transaction, parameters, tableBuilder):
"""Create a project with user-defined name in given space.
"""
# Prepare the return table
tableBuilder.addHeader("success")
tableBuilder.addHeader("message")
# Add a row for the results
row = tableBuilder.addRow()
# Retrieve parameters from client
metaprojectCode = parameters.get("metaprojectCode")
username = parameters.get("userName")
# Try retrieving the metaproject (tag)
metaproject = transaction.getMetaproject(metaprojectCode, username)
if metaproject is None:
# Create the metaproject (tag)
metaproject = transaction.createNewMetaproject(metaprojectCode,
"Test",
username)
# Check that creation was succcessful
if metaproject is None:
success = "false"
message = "Could not create metaproject " + metaprojectCode + "."
else:
success = "true"
message = "Tag " + metaprojectCode + " successfully created."
else:
success = "false"
message = "Tag " + metaprojectCode + " exists already."
# Add the results to current row
row.setCell("success", success)
row.setCell("message", message)
|
Disable tests that aren't network-stable. | #!/usr/bin/env python3
"""
test for the Psas module.
"""
import unittest
from base_test import PschedTestBase
from pscheduler.psas import as_bulk_resolve
class TestPsas(PschedTestBase):
"""
Psas tests.
"""
def test_bulk_resolve(self):
"""Bulk resolve test"""
ips = [
'8.8.8.8',
'2607:f8b0:4002:c06::67',
'198.6.1.1',
'this-is-not-valid',
]
ret = as_bulk_resolve(ips)
# Do these only if it looks like anything worked at all.
# Otherwise, we probably don't have a network connection.
assert(ret.get('this-is-not-valid') is None)
# TODO: These aren't going to be stable forever.
if False:
if [key for key in ret if ret[key] is not None]:
self.assertEqual(
ret.get('8.8.8.8')[0],
15169, 'GOOGLE, US')
self.assertEqual(
ret.get('2607:f8b0:4002:c06::67')[0],
15169)
self.assertEqual(
ret.get('198.6.1.1')[0],
701)
if __name__ == '__main__':
unittest.main()
| #!/usr/bin/env python3
"""
test for the Psas module.
"""
import unittest
from base_test import PschedTestBase
from pscheduler.psas import as_bulk_resolve
class TestPsas(PschedTestBase):
"""
Psas tests.
"""
def test_bulk_resolve(self):
"""Bulk resolve test"""
ips = [
'8.8.8.8',
'2607:f8b0:4002:c06::67',
'198.6.1.1',
'this-is-not-valid',
]
ret = as_bulk_resolve(ips)
# Do these only if it looks like anything worked at all.
# Otherwise, we probably don't have a network connection.
if [key for key in ret if ret[key] is not None]:
assert(ret.get('this-is-not-valid') is None)
self.assertEqual(
ret.get('8.8.8.8')[0],
15169, 'GOOGLE, US')
self.assertEqual(
ret.get('2607:f8b0:4002:c06::67')[0],
15169)
self.assertEqual(
ret.get('198.6.1.1')[0],
701)
if __name__ == '__main__':
unittest.main()
|
fix(select-feed): Make sure the feed exists before checking its routes | /** Select a (group of) patterns from the GTFS feed */
import React, {Component, PropTypes} from 'react'
import SelectPatterns from './select-patterns'
import SelectFeedAndRoutes from './select-feed-and-routes'
export default class SelectFeedRouteAndPatterns extends Component {
static propTypes = {
feed: PropTypes.object,
feeds: PropTypes.array.isRequired,
onChange: PropTypes.func.isRequired,
routes: PropTypes.array,
selectedFeed: PropTypes.object,
trips: PropTypes.array // trips can be null indicating a wildcard
}
selectTrips = ({ patterns, trips }) => {
this.props.onChange(Object.assign({}, this.props, { patterns, trips }))
}
selectFeedAndRoutes = ({
feed,
routes
}) => {
this.props.onChange(Object.assign({}, this.props, { routes, feed, trips: null }))
}
render () {
const {selectedFeed, feeds, routes, trips} = this.props
const routePatterns = selectedFeed && routes && routes.length === 1
? selectedFeed.routesById[routes[0]].patterns
: false
return (
<div>
<SelectFeedAndRoutes
feeds={feeds}
onChange={this.selectFeedAndRoutes}
selectedFeed={selectedFeed}
selectedRouteId={routes && routes[0]}
/>
{routePatterns &&
<SelectPatterns
onChange={this.selectTrips}
routePatterns={routePatterns}
trips={trips}
/>
}
</div>
)
}
}
| /** Select a (group of) patterns from the GTFS feed */
import React, {Component, PropTypes} from 'react'
import SelectPatterns from './select-patterns'
import SelectFeedAndRoutes from './select-feed-and-routes'
export default class SelectFeedRouteAndPatterns extends Component {
static propTypes = {
feed: PropTypes.object,
feeds: PropTypes.array.isRequired,
onChange: PropTypes.func.isRequired,
routes: PropTypes.array,
selectedFeed: PropTypes.object,
trips: PropTypes.array // trips can be null indicating a wildcard
}
selectTrips = ({ patterns, trips }) => {
this.props.onChange(Object.assign({}, this.props, { patterns, trips }))
}
selectFeedAndRoutes = ({
feed,
routes
}) => {
this.props.onChange(Object.assign({}, this.props, { routes, feed, trips: null }))
}
render () {
const {selectedFeed, feeds, routes, trips} = this.props
const routePatterns = routes && routes.length === 1
? selectedFeed.routesById[routes[0]].patterns
: false
return (
<div>
<SelectFeedAndRoutes
feeds={feeds}
onChange={this.selectFeedAndRoutes}
selectedFeed={selectedFeed}
selectedRouteId={routes && routes[0]}
/>
{routePatterns &&
<SelectPatterns
onChange={this.selectTrips}
routePatterns={routePatterns}
trips={trips}
/>
}
</div>
)
}
}
|
Update dashboard nav sign out. | import React from 'react';
import Anchor from 'grommet/components/Anchor';
import Box from 'grommet/components/Box';
import Header from 'grommet/components/Header';
import Heading from 'grommet/components/Heading';
import Menu from 'grommet/components/Menu';
import Image from 'grommet/components/Image';
const CLASS_ROOT = "grommet-cms-header";
export default function Nav({ onLogoutClick }) {
return (
<Header
className={CLASS_ROOT}
justify="between"
pad={{ horizontal: 'medium', vertical: 'none' }}
colorIndex="accent-2"
align="center"
size="small">
<Heading tag="h4" strong={true} margin="none">
Grommet CMS Dashboard
</Heading>
<Box direction="row" responsive={false} align="center"
pad={{ between: 'medium' }}>
<Menu label="Menu" inline={true} direction="row">
<Anchor path="/dashboard/homepage" label="Home Page" />
<Anchor path="/dashboard/press-releases" label="Press Releases" />
<Anchor path="/dashboard/assets" label="Assets" />
<Anchor path="/dashboard/users" label="Users" />
</Menu>
<Menu responsive={true}
inline={false}
dropAlign={{ right: 'right'}}
icon={
<Image
src="/img/dashboard/user-thumb.jpg"
style={{
borderRadius: 25,
width: '25px',
height: '25px'
}}
/>
}>
<Anchor onClick={onLogoutClick}>
Sign Out
</Anchor>
</Menu>
</Box>
</Header>
);
};
| import React from 'react';
import Anchor from 'grommet/components/Anchor';
import Box from 'grommet/components/Box';
import Header from 'grommet/components/Header';
import Heading from 'grommet/components/Heading';
import Menu from 'grommet/components/Menu';
import Image from 'grommet/components/Image';
const CLASS_ROOT = "grommet-cms-header";
export default function Nav({ onLogoutClick }) {
return (
<Header
className={CLASS_ROOT}
justify="between"
pad={{ horizontal: 'medium', vertical: 'none' }}
colorIndex="accent-2"
align="center"
size="small">
<Heading tag="h4" strong={true} margin="none">
Grommet CMS Dashboard
</Heading>
<Box direction="row" responsive={false} align="center"
pad={{ between: 'medium' }}>
<Menu label="Menu" inline={true} direction="row">
<Anchor path="/dashboard/homepage" label="Home Page" />
<Anchor path="/dashboard/press-releases" label="Press Releases" />
<Anchor path="/dashboard/assets" label="Assets" />
<Anchor path="/dashboard/users" label="Users" />
<Anchor onClick={onLogoutClick} label="Sign Out" />
</Menu>
<Image
src="/img/dashboard/user-thumb.jpg"
style={{
borderRadius: 25,
width: '25px',
height: '25px'
}}
/>
</Box>
</Header>
);
};
|
BAP-2013: Create locale kernel listener
- added listener | <?php
namespace Oro\Bundle\LocaleBundle\EventListener;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Translation\TranslatorInterface;
use Oro\Bundle\LocaleBundle\Model\LocaleSettings;
class LocaleListener implements EventSubscriberInterface
{
private $localeSettings;
private $translator;
public function __construct(LocaleSettings $localeSettings, TranslatorInterface $translator)
{
$this->localeSettings = $localeSettings;
$this->translator = $translator;
}
public function setRequest(Request $request = null)
{
if (!$request) {
return;
}
if (!$request->attributes->get('_locale')) {
$request->setLocale($this->localeSettings->getLanguage());
}
$this->setPhpDefaultLocale($this->localeSettings->getLocale());
}
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
$this->setRequest($request);
}
public function setPhpDefaultLocale($locale)
{
\Locale::setDefault($locale);
}
public static function getSubscribedEvents()
{
return array(
// must be registered after Symfony's original LocaleListener
KernelEvents::REQUEST => array(array('onKernelRequest', 15)),
);
}
}
| <?php
namespace Oro\Bundle\LocaleBundle\EventListener;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Translation\TranslatorInterface;
use Oro\Bundle\LocaleBundle\Model\LocaleSettings;
class LocaleListener implements EventSubscriberInterface
{
private $localeSettings;
private $translator;
public function __construct(
LocaleSettings $localeSettings,
TranslatorInterface $translator
) {
$this->localeSettings = $localeSettings;
$this->translator = $translator;
}
public function setRequest(Request $request = null)
{
if (!$request) {
return;
}
if (!$request->attributes->get('_locale')) {
$request->attributes->set('_locale', $this->localeSettings->getLocale());
}
$this->translator->setLocale($this->localeSettings->getLanguage());
}
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
$this->setRequest($request);
}
public static function getSubscribedEvents()
{
return array(
// must be registered before Symfony's original LocaleListener
KernelEvents::REQUEST => array(array('onKernelRequest', 17)),
);
}
}
|
Dimension: Add dtype of iteration variable | import cgen
import numpy as np
from sympy import Symbol
__all__ = ['Dimension', 'x', 'y', 'z', 't', 'p']
class Dimension(Symbol):
"""Index object that represents a problem dimension and thus
defines a potential iteration space.
:param size: Optional, size of the array dimension.
:param buffered: Optional, boolean flag indicating whether to
buffer variables when iterating this dimension.
"""
def __new__(cls, name, **kwargs):
newobj = Symbol.__new__(cls, name)
newobj.size = kwargs.get('size', None)
newobj.buffered = kwargs.get('buffered', None)
newobj._count = 0
return newobj
def __str__(self):
return self.name
def get_varname(self):
"""Generates a new variables name based on an internal counter"""
name = "%s%d" % (self.name, self._count)
self._count += 1
return name
@property
def ccode(self):
"""C-level variable name of this dimension"""
return "%s_size" % self.name if self.size is None else "%d" % self.size
@property
def decl(self):
"""Variable declaration for C-level kernel headers"""
return cgen.Value("const int", self.ccode)
@property
def dtype(self):
"""The data type of the iteration variable"""
return np.int32
# Set of default dimensions for space and time
x = Dimension('x')
y = Dimension('y')
z = Dimension('z')
t = Dimension('t')
p = Dimension('p')
| import cgen
from sympy import Symbol
__all__ = ['Dimension', 'x', 'y', 'z', 't', 'p']
class Dimension(Symbol):
"""Index object that represents a problem dimension and thus
defines a potential iteration space.
:param size: Optional, size of the array dimension.
:param buffered: Optional, boolean flag indicating whether to
buffer variables when iterating this dimension.
"""
def __new__(cls, name, **kwargs):
newobj = Symbol.__new__(cls, name)
newobj.size = kwargs.get('size', None)
newobj.buffered = kwargs.get('buffered', None)
newobj._count = 0
return newobj
def __str__(self):
return self.name
def get_varname(self):
"""Generates a new variables name based on an internal counter"""
name = "%s%d" % (self.name, self._count)
self._count += 1
return name
@property
def ccode(self):
"""C-level variable name of this dimension"""
return "%s_size" % self.name if self.size is None else "%d" % self.size
@property
def decl(self):
"""Variable declaration for C-level kernel headers"""
return cgen.Value("const int", self.ccode)
# Set of default dimensions for space and time
x = Dimension('x')
y = Dimension('y')
z = Dimension('z')
t = Dimension('t')
p = Dimension('p')
|
Use `modules: false` for client-side code | module.exports = {
presets: [
['@babel/preset-env', { shippedProposals: true, useBuiltIns: 'usage', modules: false }],
'@babel/preset-react',
'@babel/preset-flow',
],
plugins: [
'babel-plugin-emotion',
'babel-plugin-macros',
'@babel/plugin-proposal-class-properties',
'@babel/plugin-proposal-object-rest-spread',
'@babel/plugin-proposal-export-default-from',
],
env: {
test: {
plugins: ['babel-plugin-require-context-hook', 'babel-plugin-dynamic-import-node'],
},
},
overrides: [
{
test: './examples/vue-kitchen-sink',
presets: ['babel-preset-vue'],
},
{
test: [
'./lib/core/src/server',
'./lib/node-logger',
'./lib/codemod',
'./addons/storyshots',
'./addons/storysource/src/loader',
'./app/**/src/server/**',
],
presets: [
[
'@babel/preset-env',
{
targets: {
node: '8.11',
},
},
],
],
},
],
};
| module.exports = {
presets: [
['@babel/preset-env', { shippedProposals: true, useBuiltIns: 'usage' }],
'@babel/preset-react',
'@babel/preset-flow',
],
plugins: [
'babel-plugin-emotion',
'babel-plugin-macros',
'@babel/plugin-proposal-class-properties',
'@babel/plugin-proposal-object-rest-spread',
'@babel/plugin-proposal-export-default-from',
],
env: {
test: {
plugins: ['babel-plugin-require-context-hook', 'babel-plugin-dynamic-import-node'],
},
},
overrides: [
{
test: './examples/vue-kitchen-sink',
presets: ['babel-preset-vue'],
},
{
test: [
'./lib/core/src/server',
'./lib/node-logger',
'./lib/codemod',
'./addons/storyshots',
'./addons/storysource/src/loader',
'./app/**/src/server/**',
],
presets: [
[
'@babel/preset-env',
{
targets: {
node: '8.11',
},
},
],
],
},
],
};
|
Fix errors with new thumbnail helper. | @extends('app')
@section('title', $candidate->name)
@section('meta_title', $candidate->name)
@section('meta_description', 'Vote for ' . $candidate->name . ' in ' . setting('site_title') . '.')
@section('meta_image', URL::to($candidate->thumbnail))
@section('content')
<div class="candidate">
<div class="candidate__info">
<article class="tile -alternate">
<a class="wrapper" href="{{ route('candidates.show', [$candidate->slug]) }}">
<div class="tile__meta">
<h1>{{ $candidate->name }}</h1>
</div>
<img alt="{{ $candidate->name }}" src="{{ $candidate->thumbnail }}"/>
</a>
</article>
@if($candidate->description)
<p class="candidate__description">{{ $candidate->description }}</p>
@endif
@if ($candidate->photo_source)
<a href="{{ $candidate->photo_source }}">Photo Credit</a>
@endif
</div>
<div class="candidate__actions">
@include('votes.form', ['category' => $candidate->category, 'id' => $candidate->id])
@if(Auth::user() && Auth::user()->admin && $vote_count)
<h4>This candidate has {{ $vote_count }} {{ str_plural('vote', $vote_count)}}.</h4>
<div class="form-actions">
<a href="{{ route('candidates.edit', [$candidate->slug]) }}">Edit Candidate</a>
</div>
@endif
</div>
</div>
@stop
| @extends('app')
@section('title', $candidate->name)
@section('meta_title', $candidate->name)
@section('meta_description', 'Vote for ' . $candidate->name . ' in ' . setting('site_title') . '.')
@section('meta_image', URL::to($candidate->thumbnail()))
@section('content')
<div class="candidate">
<div class="candidate__info">
<article class="tile -alternate">
<a class="wrapper" href="{{ route('candidates.show', [$candidate->slug]) }}">
<div class="tile__meta">
<h1>{{ $candidate->name }}</h1>
</div>
<img alt="{{ $candidate->name }}" src="{{ $candidate->thumbnail() }}"/>
</a>
</article>
@if($candidate->description)
<p class="candidate__description">{{ $candidate->description }}</p>
@endif
@if ($candidate->photo_source)
<a href="{{ $candidate->photo_source }}">Photo Credit</a>
@endif
</div>
<div class="candidate__actions">
@include('votes.form', ['category' => $candidate->category, 'id' => $candidate->id])
@if(Auth::user() && Auth::user()->admin && $vote_count)
<h4>This candidate has {{ $vote_count }} {{ str_plural('vote', $vote_count)}}.</h4>
<div class="form-actions">
<a href="{{ route('candidates.edit', [$candidate->slug]) }}">Edit Candidate</a>
</div>
@endif
</div>
</div>
@stop
|
Move the render_index() function out of the constructor and use add_url_rule() instead of the route() decorator to connect it to Flask. | """Analysis module for Databench."""
from flask import Blueprint, render_template
import databench.signals
LIST_ALL = []
class Analysis(object):
"""Databench's analysis class.
An optional :class:`databench.Signals` instance and :class:`flask.Blueprint`
can be dependency-injected, however that should not be necessary for
standard use cases.
Args:
name (str): Name of this analysis. If ``signals`` is not specified, this
also becomes the namespace for the Socket.IO connection and has
to match the frontend's :js:class:`Databench` ``name``.
import_name (str): Usually the file name ``__name__`` where this
analysis is instantiated.
signals (optional): Inject an instance of :class:`databench.Signals`.
blueprint (optional): Inject an instance of a :class:`flask.Blueprint`.
"""
def __init__(
self,
name,
import_name,
signals=None,
blueprint=None
):
LIST_ALL.append(self)
self.show_in_index = True
self.name = name
self.import_name = import_name
if not signals:
self.signals = databench.signals.Signals(name)
else:
self.signals = signals
if not blueprint:
self.blueprint = Blueprint(
name,
import_name,
template_folder='templates',
static_folder='static',
)
else:
self.blueprint = blueprint
self.blueprint.add_url_rule('/', 'render_index', self.render_index)
def render_index(self):
"""Renders the main analysis frontend template."""
return render_template(self.name+'.html')
| """Analysis module for Databench."""
from flask import Blueprint, render_template
import databench.signals
LIST_ALL = []
class Analysis(object):
"""Databench's analysis class.
An optional :class:`databench.Signals` instance and :class:`flask.Blueprint`
can be dependency-injected, however that should not be necessary for
standard use cases.
Args:
name (str): Name of this analysis. If ``signals`` is not specified, this
also becomes the namespace for the Socket.IO connection and has
to match the frontend's :js:class:`Databench` ``name``.
import_name (str): Usually the file name ``__name__`` where this
analysis is instantiated.
signals (optional): Inject an instance of :class:`databench.Signals`.
blueprint (optional): Inject an instance of a :class:`flask.Blueprint`.
"""
def __init__(
self,
name,
import_name,
signals=None,
blueprint=None
):
LIST_ALL.append(self)
self.name = name
self.import_name = import_name
if not signals:
self.signals = databench.signals.Signals(name)
else:
self.signals = signals
if not blueprint:
self.blueprint = Blueprint(
name,
import_name,
template_folder='templates',
static_folder='static',
)
else:
self.blueprint = blueprint
self.show_in_index = True
@self.blueprint.route('/')
def render_index():
"""Renders the main analysis frontend template."""
return render_template(self.name+'.html')
|
Use node id (not project id) to create component Subscriptions | from framework.auth.decorators import must_be_logged_in
from model import Subscription
from flask import request
from modularodm import Q
from modularodm.exceptions import NoResultsFound
from modularodm.storage.mongostorage import KeyExistsException
@must_be_logged_in
def subscribe(auth, **kwargs):
user = auth.user
pid = kwargs.get('pid')
nid = kwargs.get('nid')
subscriptions = request.json
for event in subscriptions:
if event == 'comment_replies':
category = user._id
else:
category = nid if nid else pid
event_id = category + "_" + event
# Create subscription or find existing
for notification_type in subscriptions[event]:
if subscriptions[event][notification_type]:
try:
s = Subscription(_id=event_id)
s.object_id = category
s.event_name = event
s.save()
except KeyExistsException:
s = Subscription.find_one(Q('_id', 'eq', event_id))
s.object_id = category
s.event_name = event
s.save()
# Add user to list of subscribers
if notification_type not in s._fields:
setattr(s, notification_type, [])
s.save()
if user not in getattr(s, notification_type):
getattr(s, notification_type).append(user)
s.save()
else:
try:
s = Subscription.find_one(Q('_id', 'eq', event_id))
if user in getattr(s, notification_type):
getattr(s, notification_type).remove(user)
s.save()
except NoResultsFound:
pass
return {} | from framework.auth.decorators import must_be_logged_in
from model import Subscription
from flask import request
from modularodm import Q
from modularodm.exceptions import NoResultsFound
from modularodm.storage.mongostorage import KeyExistsException
@must_be_logged_in
def subscribe(auth, **kwargs):
user = auth.user
pid = kwargs.get('pid')
subscriptions = request.json
for event in subscriptions:
if event == 'comment_replies':
category = user._id
else:
category = pid
event_id = category + "_" + event
# Create subscription or find existing
for notification_type in subscriptions[event]:
if subscriptions[event][notification_type]:
try:
s = Subscription(_id=event_id)
s.object_id = category
s.event_name = event
s.save()
except KeyExistsException:
s = Subscription.find_one(Q('_id', 'eq', event_id))
s.object_id = category
s.event_name = event
s.save()
# Add user to list of subscribers
if notification_type not in s._fields:
setattr(s, notification_type, [])
s.save()
if user not in getattr(s, notification_type):
getattr(s, notification_type).append(user)
s.save()
else:
try:
s = Subscription.find_one(Q('_id', 'eq', event_id))
if user in getattr(s, notification_type):
getattr(s, notification_type).remove(user)
s.save()
except NoResultsFound:
pass
return {} |
Fix regression in displaying a thumbnail for newly selected images on FileBrowseField. | function FileSubmit(FilePath, FileURL, ThumbURL, FileType) {
// var input_id=window.name.split("___").join(".");
var input_id=window.name.replace(/____/g,'-').split("___").join(".");
var preview_id = 'image_' + input_id;
var link_id = 'link_' + input_id;
var help_id = 'help_' + input_id;
var clear_id = 'clear_' + input_id;
input = opener.document.getElementById(input_id);
preview = opener.document.getElementById(preview_id);
link = opener.document.getElementById(link_id);
help = opener.document.getElementById(help_id);
clear = opener.document.getElementById(clear_id);
// set new value for input field
input.value = FilePath;
// enable the clear "button"
jQuery(clear).css("display", "inline");
if (ThumbURL && FileType != "") {
// selected file is an image and thumbnail is available:
// display the preview-image (thumbnail)
// link the preview-image to the original image
link.setAttribute("href", FileURL);
link.setAttribute("target", "_blank");
link.setAttribute("style", "display:inline");
preview.setAttribute("src", ThumbURL);
help.setAttribute("style", "display:inline");
jQuery(help).addClass("mezz-fb-thumbnail");
} else {
// hide preview elements
link.setAttribute("href", "");
link.setAttribute("target", "");
preview.setAttribute("src", "");
help.setAttribute("style", "display:none");
}
this.close();
}
| function FileSubmit(FilePath, FileURL, ThumbURL, FileType) {
// var input_id=window.name.split("___").join(".");
var input_id=window.name.replace(/____/g,'-').split("___").join(".");
var preview_id = 'image_' + input_id;
var link_id = 'link_' + input_id;
var help_id = 'help_' + input_id;
var clear_id = 'clear_' + input_id;
input = opener.document.getElementById(input_id);
preview = opener.document.getElementById(preview_id);
link = opener.document.getElementById(link_id);
help = opener.document.getElementById(help_id);
clear = opener.document.getElementById(clear_id);
// set new value for input field
input.value = FilePath;
// enable the clear "button"
jQuery(clear).css("display", "inline");
if (ThumbURL && FileType != "") {
// selected file is an image and thumbnail is available:
// display the preview-image (thumbnail)
// link the preview-image to the original image
link.setAttribute("href", FileURL);
link.setAttribute("target", "_blank");
preview.setAttribute("src", ThumbURL);
help.setAttribute("style", "display:inline");
jQuery(help).addClass("mezz-fb-thumbnail");
} else {
// hide preview elements
link.setAttribute("href", "");
link.setAttribute("target", "");
preview.setAttribute("src", "");
help.setAttribute("style", "display:none");
}
this.close();
}
|
Use official Flask-Script distribution (>= 0.3.2) | """
Flask-Celery
------------
Celery integration for Flask
"""
from setuptools import setup
setup(
name='Flask-Celery',
version='2.4.1',
url='http://github.com/ask/flask-celery/',
license='BSD',
author='Ask Solem',
author_email='[email protected]',
description='Celery integration for Flask',
long_description=__doc__,
py_modules=['flask_celery'],
zip_safe=False,
platforms='any',
test_suite="nose.collector",
install_requires=[
'Flask>=0.8',
'Flask-Script>=0.3.2',
'celery>=2.3.0',
],
tests_require=[
'nose',
'nose-cover3',
'mock',
],
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.5',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
| """
Flask-Celery
------------
Celery integration for Flask
"""
from setuptools import setup
setup(
name='Flask-Celery',
version='2.4.1',
url='http://github.com/ask/flask-celery/',
license='BSD',
author='Ask Solem',
author_email='[email protected]',
description='Celery integration for Flask',
long_description=__doc__,
py_modules=['flask_celery'],
zip_safe=False,
platforms='any',
test_suite="nose.collector",
install_requires=[
'Flask>=0.8',
'Flask-Script-fix',
'celery>=2.3.0',
],
tests_require=[
'nose',
'nose-cover3',
'mock',
],
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.5',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
Remove hot loader from webpack config | var webpack = require('webpack');
var path = require('path');
module.exports = {
devtool: 'source-map',
context: __dirname,
entry: [
'./index.js'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url-loader?limit=10000&minetype=application/font-woff'
},
{ test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'file-loader'
},
{
test: /\.json$/,
loader: 'json'
},
{
test: /\.css$/,
loader: 'style!css'
},
{
test: /\.styl$/,
loader: 'style!css!stylus?paths=node_modules'
},
{ test: /\.js$|\.jsx$/,
exclude: [/node_modules/],
loaders: [
'babel?' + JSON.stringify({presets: ['stage-2', 'es2015', 'react']})
]
}
]
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
})
]
};
| var webpack = require('webpack');
var path = require('path');
module.exports = {
devtool: 'source-map',
context: __dirname,
entry: [
'./index.js'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url-loader?limit=10000&minetype=application/font-woff'
},
{ test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'file-loader'
},
{
test: /\.json$/,
loader: 'json'
},
{
test: /\.css$/,
loader: 'style!css'
},
{
test: /\.styl$/,
loader: 'style!css!stylus?paths=node_modules'
},
{ test: /\.js$|\.jsx$/,
exclude: [/node_modules/],
loaders: [
'react-hot',
'babel?' + JSON.stringify({presets: ['stage-2', 'es2015', 'react']})
]
}
]
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
})
]
};
|
Add test for states() method shortcut | <?php
use Galahad\LaravelAddressing\AdministrativeAreaCollection;
use Galahad\LaravelAddressing\Country;
/**
* Class AdministrativeAreaCollectionTest
*
* @author Junior Grossi <[email protected]>
*/
class AdministrativeAreaCollectionTest extends PHPUnit_Framework_TestCase
{
public function testCollectionClass()
{
$country = new Country;
$brazil = $country->getByCode('BR');
$states = $brazil->getAdministrativeAreas();
$this->assertInstanceOf(AdministrativeAreaCollection::class, $states);
}
public function testUSStatesCount()
{
$country = new Country;
$us = $country->getByCode('US');
$states = $us->getAdministrativeAreas();
$this->assertEquals($states->count(), 62);
}
public function testBrazilianStatesCount()
{
$country = new Country;
$brazil = $country->getByName('Brazil');
$states = $brazil->getAdministrativeAreas();
$this->assertEquals($states->count(), 27);
$this->assertEquals($brazil->states()->count(), 27);
}
public function testCollectionList()
{
$country = new Country();
$usStates = $country->getByCode('US')->getAdministrativeAreas()->toList();
$this->assertTrue(isset($usStates['AL']));
$this->assertTrue(isset($usStates['CO']));
$this->assertTrue(isset($usStates['CA']));
}
} | <?php
use Galahad\LaravelAddressing\AdministrativeAreaCollection;
use Galahad\LaravelAddressing\Country;
/**
* Class AdministrativeAreaCollectionTest
*
* @author Junior Grossi <[email protected]>
*/
class AdministrativeAreaCollectionTest extends PHPUnit_Framework_TestCase
{
public function testCollectionClass()
{
$country = new Country;
$brazil = $country->getByCode('BR');
$states = $brazil->getAdministrativeAreas();
$this->assertInstanceOf(AdministrativeAreaCollection::class, $states);
}
public function testUSStatesCount()
{
$country = new Country;
$us = $country->getByCode('US');
$states = $us->getAdministrativeAreas();
$this->assertEquals($states->count(), 62);
}
public function testBrazilianStatesCount()
{
$country = new Country;
$brazil = $country->getByName('Brazil');
$states = $brazil->getAdministrativeAreas();
$this->assertEquals($states->count(), 27);
}
public function testCollectionList()
{
$country = new Country();
$usStates = $country->getByCode('US')->getAdministrativeAreas()->toList();
$this->assertTrue(isset($usStates['AL']));
$this->assertTrue(isset($usStates['CO']));
$this->assertTrue(isset($usStates['CA']));
}
} |
Update name of Eidos reading class | import json
from indra.java_vm import autoclass, JavaException
class EidosReader(object):
"""Reader object keeping an instance of the Eidos reader as a singleton.
This allows the Eidos reader to need initialization when the first piece of
text is read, the subsequent readings are done with the same
instance of the reader and are therefore faster.
Attributes
----------
eidos_reader : org.clulab.wm.AgroSystem
A Scala object, an instance of the Eidos reading system. It is
instantiated only when first processing text.
"""
def __init__(self):
self.eidos_reader = None
def process_text(self, text):
"""Return a mentions JSON object given text.
Parameters
----------
text : str
Text to be processed.
Returns
-------
json_dict : dict
A JSON object of mentions extracted from text.
"""
if self.eidos_reader is None:
eidos = autoclass('org.clulab.wm.EidosSystem')
self.eidos_reader = eidos(autoclass('java.lang.Object')())
mentions = self.eidos_reader.extractFrom(text)
ser = autoclass('org.clulab.wm.serialization.json.WMJSONSerializer')
mentions_json = ser.toJsonStr(mentions)
json_dict = json.loads(mentions_json)
return json_dict
| import json
from indra.java_vm import autoclass, JavaException
class EidosReader(object):
"""Reader object keeping an instance of the Eidos reader as a singleton.
This allows the Eidos reader to need initialization when the first piece of
text is read, the subsequent readings are done with the same
instance of the reader and are therefore faster.
Attributes
----------
eidos_reader : org.clulab.wm.AgroSystem
A Scala object, an instance of the Eidos reading system. It is
instantiated only when first processing text.
"""
def __init__(self):
self.eidos_reader = None
def process_text(self, text):
"""Return a mentions JSON object given text.
Parameters
----------
text : str
Text to be processed.
Returns
-------
json_dict : dict
A JSON object of mentions extracted from text.
"""
if self.eidos_reader is None:
eidos = autoclass('org.clulab.wm.AgroSystem')
self.eidos_reader = eidos(autoclass('java.lang.Object')())
mentions = self.eidos_reader.extractFrom(text)
ser = autoclass('org.clulab.wm.serialization.json.WMJSONSerializer')
mentions_json = ser.toJsonStr(mentions)
json_dict = json.loads(mentions_json)
return json_dict
|
Add google map component under city heading | import React, { Component } from 'react';
import { connect } from 'react-redux';
import Chart from '../components/chart';
import GoogleMap from '../components/google_map';
class WeatherList extends Component {
renderWeather(cityData) {
const name = cityData.city.name;
const temps = cityData.list.map(weather => weather.main.temp);
const pressures = cityData.list.map(weather => weather.main.pressure);
const humidities = cityData.list.map(weather => weather.main.humidity);
const { lon, lat } = cityData.city.coord;
return (
<tr key={name}>
<td><GoogleMap lon={lon} lat={lat} /></td>
<td><Chart data={temps} color="orange" units="K" /></td>
<td><Chart data={pressures} color="green" units="hPa" /></td>
<td><Chart data={humidities} color="black" units="%" /></td>
</tr>
);
}
render() {
return (
<table className="table table-hover">
<thead>
<tr>
<th>City</th>
<th>Temperature (K)</th>
<th>Pressure (hPa)</th>
<th>Humidity (%)</th>
</tr>
</thead>
<tbody>
{this.props.weather.map(this.renderWeather)}
</tbody>
</table>
);
}
}
function mapStateToProps({ weather }) {
return { weather };
}
export default connect(mapStateToProps)(WeatherList); | import React, { Component } from 'react';
import { connect } from 'react-redux';
import Chart from '../components/chart';
class WeatherList extends Component {
renderWeather(cityData) {
const name = cityData.city.name;
const temps = cityData.list.map(weather => weather.main.temp);
const pressures = cityData.list.map(weather => weather.main.pressure);
const humidities = cityData.list.map(weather => weather.main.humidity);
return (
<tr key={name}>
<td>{name}</td>
<td><Chart data={temps} color="orange" units="K" /></td>
<td><Chart data={pressures} color="green" units="hPa" /></td>
<td><Chart data={humidities} color="black" units="%" /></td>
</tr>
);
}
render() {
return (
<table className="table table-hover">
<thead>
<tr>
<th>City</th>
<th>Temperature (K)</th>
<th>Pressure (hPa)</th>
<th>Humidity (%)</th>
</tr>
</thead>
<tbody>
{this.props.weather.map(this.renderWeather)}
</tbody>
</table>
);
}
}
function mapStateToProps({ weather }) {
return { weather };
}
export default connect(mapStateToProps)(WeatherList); |
Use logger for hades-generate-config error messages | import logging
import os
import sys
from hades import constants
from hades.common.cli import ArgumentParser, parser as common_parser
from hades.config.generate import ConfigGenerator
from hades.config.loader import load_config
logger = logging.getLogger()
def main():
parser = ArgumentParser(parents=[common_parser])
parser.add_argument(dest='source', metavar='SOURCE',
help="Template file name or template directory name")
parser.add_argument(dest='destination', metavar='DESTINATION', nargs='?',
help="Destination file or directory (default is stdout"
"for files; required for directories)")
args = parser.parse_args()
config = load_config(args.config)
template_dir = constants.templatedir
generator = ConfigGenerator(template_dir, config)
source_path = os.path.join(template_dir, args.source)
if os.path.isdir(source_path):
generator.from_directory(args.source, args.destination)
elif os.path.isfile(source_path):
if args.destination is None:
generator.from_file(args.source, sys.stdout)
else:
with open(args.destination, 'w', encoding='utf-8') as f:
generator.from_file(args.source, f)
else:
logger.critical("No such file or directory {} in {}"
.format(args.source, template_dir))
return os.EX_NOINPUT
if __name__ == '__main__':
sys.exit(main())
| import os
import sys
from hades import constants
from hades.common.cli import ArgumentParser, parser as common_parser
from hades.config.generate import ConfigGenerator
from hades.config.loader import load_config
def main():
parser = ArgumentParser(parents=[common_parser])
parser.add_argument(dest='source', metavar='SOURCE',
help="Template file name or template directory name")
parser.add_argument(dest='destination', metavar='DESTINATION', nargs='?',
help="Destination file or directory (default is stdout"
"for files; required for directories)")
args = parser.parse_args()
config = load_config(args.config)
template_dir = constants.templatedir
generator = ConfigGenerator(template_dir, config)
source_path = os.path.join(template_dir, args.source)
if os.path.isdir(source_path):
generator.from_directory(args.source, args.destination)
elif os.path.isfile(source_path):
if args.destination is None:
generator.from_file(args.source, sys.stdout)
else:
with open(args.destination, 'w', encoding='utf-8') as f:
generator.from_file(args.source, f)
else:
print("No such file or directory {} in {}".format(args.source,
template_dir),
file=sys.stderr)
return os.EX_NOINPUT
if __name__ == '__main__':
sys.exit(main())
|
Change `npm run dev` to `npm run local` | <?php
namespace TightenCo\Jigsaw\Scaffold;
class DefaultInstaller
{
const ALWAYS_IGNORE = [
'build_*',
'init.php',
'node_modules',
'vendor',
];
const DEFAULT_COMMANDS = [
'composer install',
'npm install',
'npm run local',
];
protected $commands;
protected $delete;
protected $ignore;
protected $builder;
public function install(ScaffoldBuilder $builder, $settings = [])
{
$this->builder = $builder;
$this->delete = array_get($settings, 'delete', []);
$this->ignore = array_merge(self::ALWAYS_IGNORE, array_get($settings, 'ignore', []));
$commands = array_get($settings, 'commands');
$this->commands = $commands !== null ? $commands : self::DEFAULT_COMMANDS;
$this->execute();
}
public function execute()
{
return $this->builder
->buildBasicScaffold()
->cacheComposerDotJson()
->deleteSiteFiles($this->delete)
->copyPresetFiles(null, $this->ignore)
->mergeComposerDotJson()
->runCommands($this->commands);
}
}
| <?php
namespace TightenCo\Jigsaw\Scaffold;
class DefaultInstaller
{
const ALWAYS_IGNORE = [
'build_*',
'init.php',
'node_modules',
'vendor',
];
const DEFAULT_COMMANDS = [
'composer install',
'npm install',
'npm run dev',
];
protected $commands;
protected $delete;
protected $ignore;
protected $builder;
public function install(ScaffoldBuilder $builder, $settings = [])
{
$this->builder = $builder;
$this->delete = array_get($settings, 'delete', []);
$this->ignore = array_merge(self::ALWAYS_IGNORE, array_get($settings, 'ignore', []));
$commands = array_get($settings, 'commands');
$this->commands = $commands !== null ? $commands : self::DEFAULT_COMMANDS;
$this->execute();
}
public function execute()
{
return $this->builder
->buildBasicScaffold()
->cacheComposerDotJson()
->deleteSiteFiles($this->delete)
->copyPresetFiles(null, $this->ignore)
->mergeComposerDotJson()
->runCommands($this->commands);
}
}
|
Fix bug when Opera Mini (and possibly others) present no X-OperaMini-Phone header. | from django.conf import settings
import geolocation
from mobile_portal.wurfl.wurfl_data import devices
from mobile_portal.wurfl import device_parents
from pywurfl.algorithms import DeviceNotFound
from mobile_portal.wurfl.vsm import VectorSpaceAlgorithm
class LocationMiddleware(object):
vsa = VectorSpaceAlgorithm(devices)
def process_request(self, request):
ua = request.META.get('HTTP_USER_AGENT', '')
try:
request.browser = devices.select_ua(
request.META['HTTP_USER_AGENT'],
search=LocationMiddleware.vsa
)
except (KeyError, DeviceNotFound):
request.browser = devices.select_id('generic_xhtml')
if 'HTTP_X_OPERAMINI_PHONE' in request.META:
opera_device = request.META['HTTP_X_OPERAMINI_PHONE']
request.device = devices.select_ua(
opera_device,
search=LocationMiddleware.vsa
)
else:
request.device = request.browser
from django.db import connection
class PrintQueriesMiddleware(object):
def process_response(self, request, response):
for query in connection.queries:
print '-'*80
print query['sql']
return response | from django.conf import settings
import geolocation
from mobile_portal.wurfl.wurfl_data import devices
from mobile_portal.wurfl import device_parents
from pywurfl.algorithms import DeviceNotFound
from mobile_portal.wurfl.vsm import VectorSpaceAlgorithm
class LocationMiddleware(object):
vsa = VectorSpaceAlgorithm(devices)
def process_request(self, request):
ua = request.META.get('HTTP_USER_AGENT', '')
try:
request.browser = devices.select_ua(
request.META['HTTP_USER_AGENT'],
search=LocationMiddleware.vsa
)
except (KeyError, DeviceNotFound):
request.browser = devices.select_id('generic_xhtml')
if 'opera_mini_ver1' in device_parents[request.browser.devid]:
opera_device = request.META.get('HTTP_X_OPERAMINI_PHONE')
request.device = devices.select_ua(
opera_device,
search=LocationMiddleware.vsa
)
else:
request.device = request.browser
from django.db import connection
class PrintQueriesMiddleware(object):
def process_response(self, request, response):
for query in connection.queries:
print '-'*80
print query['sql']
return response |
Test against all javascript compressors, and the return compressor for reference | <?php
/*
* This file is part of HtmlCompress.
*
** (c) 2014 Cees-Jan Kiewiet
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace WyriHaximus\HtmlCompress\Tests\SpecialFormats;
use WyriHaximus\HtmlCompress\Compressor;
class LdJsonTest extends \PHPUnit_Framework_TestCase
{
public function javascriptCompressorProvider()
{
return [
[
new Compressor\JSMinCompressor(),
],
[
new Compressor\JavaScriptPackerCompressor(),
],
/*[ // This compressor results in invalid JSON
new Compressor\JSqueezeCompressor(),
],*/
[
new Compressor\ReturnCompressor(),
],
];
}
/**
* @dataProvider javascriptCompressorProvider
*/
public function testLdJson(Compressor\CompressorInterface $compressor)
{
$input = file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . 'input' . DIRECTORY_SEPARATOR . 'ld.json.input');
$inputJson = $this->getJson($input);
$compressedInput = $compressor->compress($input);
$compressedJson = $this->getJson($compressedInput);
self::assertSame($inputJson, $compressedJson, $compressedInput);
}
private function getJson($string)
{
$start = strpos($string, '{');
$end = strrpos($string, '}') + 1;
$string = substr($string, $start, $end - $start);
return json_decode($string, true);
}
} | <?php
/*
* This file is part of HtmlCompress.
*
** (c) 2014 Cees-Jan Kiewiet
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace WyriHaximus\HtmlCompress\Tests\SpecialFormats;
use WyriHaximus\HtmlCompress\Compressor;
class LdJsonTest extends \PHPUnit_Framework_TestCase
{
public function javascriptCompressorProvider()
{
return [
[
new Compressor\JSMinCompressor(),
],
];
}
/**
* @dataProvider javascriptCompressorProvider
*/
public function testLdJson(Compressor\CompressorInterface $compressor)
{
$input = file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . 'input' . DIRECTORY_SEPARATOR . 'ld.json.input');
$inputJson = $this->getJson($input);
$compressedInput = $compressor->compress($input);
$compressedJson = $this->getJson($compressedInput);
self::assertSame($inputJson, $compressedJson);
}
private function getJson($string)
{
$start = strpos($string, '{');
$end = strrpos($string, '}') + 1;
$string = substr($string, $start, $end - $start);
return json_decode($string, true);
}
} |
Update install requires, add opps >= 0.2 | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='opps-admin',
version='0.1',
description='Opps Admin, drop-in replacement of Django admin comes with lots of goodies, fully extensible with plugin support, pretty UI based on Twitter Bootstrap.',
long_description=open('README.rst').read(),
author='sshwsfc',
url='http://www.oppsproject.org',
download_url='http://github.com/opps/opps-admin/tarball/master',
packages=find_packages(exclude=('doc', 'docs',)),
include_package_data=True,
install_requires=[
'setuptools',
'opps>=0.2',
'xlwt',
'django-crispy-forms>=1.2.3',
],
zip_safe=True,
keywords=['admin', 'django', 'xadmin', 'bootstrap', 'opps', 'opps-admin'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
"Programming Language :: JavaScript",
'Programming Language :: Python',
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content",
"Topic :: Software Development :: Libraries :: Python Modules",
]
)
| #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='opps-admin',
version='0.1',
description='Opps Admin, drop-in replacement of Django admin comes with lots of goodies, fully extensible with plugin support, pretty UI based on Twitter Bootstrap.',
long_description=open('README.rst').read(),
author='sshwsfc',
url='http://www.oppsproject.org',
download_url='http://github.com/opps/opps-admin/tarball/master',
packages=find_packages(exclude=('doc', 'docs',)),
include_package_data=True,
install_requires=[
'setuptools',
'django>=1.4',
'xlwt',
'django-crispy-forms>=1.2.3',
'django-reversion',
],
zip_safe=True,
keywords=['admin', 'django', 'xadmin', 'bootstrap'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
"Programming Language :: JavaScript",
'Programming Language :: Python',
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content",
"Topic :: Software Development :: Libraries :: Python Modules",
]
)
|
Fix bug for release status | package fr.synchrotron.soleil.ica.ci.lib.workflow;
import java.util.Arrays;
/**
* @author Gregory Boissinot
*/
public class DefaultWorkflow extends Workflow {
private static final String DEFAULT_STATUS_BUILD = "BUILD";
private static final String DEFAULT_STATUS_INTEGRATION = "INTEGRATION";
private static final String DEFAULT_STATUS_RELEASE = "RELEASE";
private static final String[] status = new String[]{DEFAULT_STATUS_BUILD, DEFAULT_STATUS_INTEGRATION, DEFAULT_STATUS_RELEASE};
public DefaultWorkflow() {
super("DEFAULT_WORKFLOW", Arrays.asList(status));
}
public StatusVersion extractStatusAndVersionFromMavenVersion(String version) {
final String snapshotVersionSuffix = "-SNAPSHOT";
StatusVersion statusVersion = new StatusVersion();
if (version.endsWith(snapshotVersionSuffix)) {
statusVersion.status = DEFAULT_STATUS_BUILD;
statusVersion.version = version.substring(0, version.lastIndexOf(snapshotVersionSuffix));
return statusVersion;
}
if (version.endsWith("." + DEFAULT_STATUS_INTEGRATION)) {
statusVersion.status = DEFAULT_STATUS_INTEGRATION;
statusVersion.version = version.substring(0, version.lastIndexOf("." + DEFAULT_STATUS_INTEGRATION));
return statusVersion;
}
if (version.endsWith("." + DEFAULT_STATUS_RELEASE)) {
statusVersion.status = DEFAULT_STATUS_RELEASE;
statusVersion.version = version.substring(0, version.lastIndexOf("." + DEFAULT_STATUS_RELEASE));
return statusVersion;
}
statusVersion.status = DEFAULT_STATUS_RELEASE;
statusVersion.version = version;
return statusVersion;
}
}
| package fr.synchrotron.soleil.ica.ci.lib.workflow;
import java.util.Arrays;
/**
* @author Gregory Boissinot
*/
public class DefaultWorkflow extends Workflow {
private static final String DEFAULT_STATUS_BUILD = "BUILD";
private static final String DEFAULT_STATUS_INTEGRATION = "INTEGRATION";
private static final String DEFAULT_STATUS_RELEASE = "RELEASE";
private static final String[] status = new String[]{DEFAULT_STATUS_BUILD, DEFAULT_STATUS_INTEGRATION, DEFAULT_STATUS_RELEASE};
public DefaultWorkflow() {
super("DEFAULT_WORKFLOW", Arrays.asList(status));
}
public StatusVersion extractStatusAndVersionFromMavenVersion(String version) {
final String snapshotVersionSuffix = "-SNAPSHOT";
StatusVersion statusVersion = new StatusVersion();
if (version.endsWith(snapshotVersionSuffix)) {
statusVersion.status = DEFAULT_STATUS_BUILD;
statusVersion.version = version.substring(0, version.lastIndexOf(snapshotVersionSuffix));
return statusVersion;
}
if (version.endsWith("." + DEFAULT_STATUS_INTEGRATION)) {
statusVersion.status = DEFAULT_STATUS_INTEGRATION;
statusVersion.version = version.substring(0, version.lastIndexOf("." + DEFAULT_STATUS_INTEGRATION));
return statusVersion;
}
statusVersion.status = DEFAULT_STATUS_RELEASE;
statusVersion.version = version;
return statusVersion;
}
}
|
Use real path for views instead of alias | <?php
/**
* README plugin for HiDev
*
* @link https://github.com/hiqdev/hidev-readme
* @package hidev-readme
* @license BSD-3-Clause
* @copyright Copyright (c) 2015-2017, HiQDev (http://hiqdev.com/)
*/
return [
'controllerMap' => [
'README' => [
'class' => \hidev\readme\console\ReadmeController::class,
'type' => 'text',
],
'README.md' => [
'class' => \hidev\readme\console\ReadmeController::class,
'type' => 'markdown',
],
],
'components' => [
'readme' => [
'class' => \hidev\readme\components\Readme::class,
'knownBadges' => [
'github.release' => '[](https://github.com/{{ app.github.full_name }}/releases)',
'github.version' => '[](https://badge.fury.io/gh/{{ app.github.vendor }}%2F{{ app.github.name }})',
],
],
'view' => [
'theme' => [
'pathMap' => [
'@hidev/views' => [dirname(__DIR__) . '/src/views'],
],
],
],
],
];
| <?php
/**
* README plugin for HiDev
*
* @link https://github.com/hiqdev/hidev-readme
* @package hidev-readme
* @license BSD-3-Clause
* @copyright Copyright (c) 2015-2017, HiQDev (http://hiqdev.com/)
*/
return [
'controllerMap' => [
'README' => [
'class' => \hidev\readme\console\ReadmeController::class,
'type' => 'text',
],
'README.md' => [
'class' => \hidev\readme\console\ReadmeController::class,
'type' => 'markdown',
],
],
'components' => [
'readme' => [
'class' => \hidev\readme\components\Readme::class,
'knownBadges' => [
'github.release' => '[](https://github.com/{{ app.github.full_name }}/releases)',
'github.version' => '[](https://badge.fury.io/gh/{{ app.github.vendor }}%2F{{ app.github.name }})',
],
],
'view' => [
'theme' => [
'pathMap' => [
'@hidev/views' => ['@hidev/readme/views'],
],
],
],
],
];
|
Implement scalar/vector multiply and divide | export default class Vector2 {
constructor(x = 0, y = 0) {
this.x = x;
this.y = y;
}
set(x, y) {
this.x = x;
this.y = y;
return this;
}
add(vec2) {
this.x = vec2.x;
this.y = vec2.y;
return this;
}
subtract(vec2) {
this.x -= vec2.x;
this.y -= vec2.y;
return this;
}
multiplyVector(vec2) {
this.x *= vec2.x;
this.y *= vec2.y;
return this;
}
multiplyScalar(scalar) {
this.x *= scalar;
this.y *= scalar;
return this;
}
divideVector(vec2) {
this.x /= vec2.x;
this.y /= vec2.y;
return this;
}
divideScalar(scalar) {
this.x /= scalar;
this.y /= scalar;
return this;
}
angle(vec2) {
return Math.atan2(vec2.y - this.y, vec2.x - this.x);
}
distance(vec2) {
return Math.sqrt(Math.pow(vec2.x - this.x, 2) + Math.pow(vec2.y - this.y, 2));
}
distanceSq(vec2) {
return Math.pow(vec2.x - this.x, 2) + Math.pow(vec2.y - this.y, 2);
}
clone() {
return new Vector2(this.x, this.y);
}
} | export default class Vector2 {
constructor(x = 0, y = 0) {
this.x = x;
this.y = y;
}
set(x, y) {
this.x = x;
this.y = y;
return this;
}
add(vec2) {
this.x = vec2.x;
this.y = vec2.y;
return this;
}
subtract(vec2) {
this.x -= vec2.x;
this.y -= vec2.y;
return this;
}
multiply(vec2) {
this.x *= vec2.x;
this.y *= vec2.y;
return this;
}
divide(vec2) {
this.x /= vec2.x;
this.y /= vec2.y;
return this;
}
angle(vec2) {
return Math.atan2(vec2.y - this.y, vec2.x - this.x);
}
distance(vec2) {
return Math.sqrt(Math.pow(vec2.x - this.x, 2) + Math.pow(vec2.y - this.y, 2));
}
distanceSq(vec2) {
return Math.pow(vec2.x - this.x, 2) + Math.pow(vec2.y - this.y, 2);
}
clone() {
return new Vector2(this.x, this.y);
}
} |
Make Selenium shut down after it's done | #!/usr/bin/python
from pyvirtualdisplay import Display
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
import selenium.webdriver.support.ui as ui
import re
import atexit
disp = Display(visible=0, size=(800,600))
atexit.register(lambda: disp.stop())
disp.start()
class CSPBrowser:
schema = re.compile('^https?://', re.IGNORECASE)
def __init__(self, port=None, domain=None):
profile = webdriver.FirefoxProfile()
if port != None and domain != None:
profile.set_preference("network.proxy.type",1)
profile.set_preference("network.proxy.http", domain)
profile.set_preference("network.proxy.http_port", port)
profile.update_preferences()
self.driver = webdriver.Firefox(firefox_profile=profile)
def load(self, urllist):
self.urllist = []
for url in urllist:
if not self.schema.match(url):
url = 'http://' + url
self.urllist.append(url)
def run(self):
for url in self.urllist:
print url
if (not len(url)): continue
#print "Visiting: " + url
self.driver.get(url)
self.driver.get('about:blank')
self.shutdown()
def shutdown(self):
self.driver.close()
| #!/usr/bin/python
from pyvirtualdisplay import Display
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
import selenium.webdriver.support.ui as ui
import re
import atexit
disp = Display(visible=0, size=(800,600))
atexit.register(lambda: disp.stop())
disp.start()
class CSPBrowser:
schema = re.compile('^https?://', re.IGNORECASE)
def __init__(self, port=None, domain=None):
profile = webdriver.FirefoxProfile()
if port != None and domain != None:
profile.set_preference("network.proxy.type",1)
profile.set_preference("network.proxy.http", domain)
profile.set_preference("network.proxy.http_port", port)
profile.update_preferences()
self.driver = webdriver.Firefox(firefox_profile=profile)
def load(self, urllist):
self.urllist = []
for url in urllist:
if not self.schema.match(url):
url = 'http://' + url
self.urllist.append(url)
def run(self):
for url in self.urllist:
print url
if (not len(url)): continue
#print "Visiting: " + url
self.driver.get(url)
self.driver.get('about:blank')
def shutdown(self):
self.driver.close() |
Fix app crash from our pagination when editing invalid things
Addresses the most important part of #1742 , next patch will be to make
it so we just navigate away from the detail page if we delete the item
we're on. | /*************************************************
* Copyright (c) 2015 Ansible, Inc.
*
* All Rights Reserved
*************************************************/
export default ['$http', '$q', function($http, $q) {
return {
getInitialPageForList: function(id, url, pageSize) {
// get the name of the object
if ($.isNumeric(id)) {
return $http.get(url + "?id=" + id)
.then(function (data) {
var queryValue, queryType;
if (data.data.results.length) {
if (data.data.results[0].type === "user") {
queryValue = data.data.results[0].username;
queryType = "username";
} else {
queryValue = data.data.results[0].name;
queryType = "name";
}
} else {
queryValue = "";
queryType = "name";
}
// get how many results are less than or equal to
// the name
return $http.get(url + "?" + queryType + "__lte=" + queryValue)
.then(function (data) {
// divide by the page size to get what
// page the data should be on
var count = data.data.count;
return Math.max(1, Math.ceil(count/parseInt(pageSize)));
});
});
} else {
var defer = $q.defer();
defer.resolve(1);
return(defer.promise);
}
}
};
}];
| /*************************************************
* Copyright (c) 2015 Ansible, Inc.
*
* All Rights Reserved
*************************************************/
export default ['$http', '$q', function($http, $q) {
return {
getInitialPageForList: function(id, url, pageSize) {
// get the name of the object
if ($.isNumeric(id)) {
return $http.get(url + "?id=" + id)
.then(function (data) {
var queryValue, queryType;
if (data.data.results[0].type === "user") {
queryValue = data.data.results[0].username;
queryType = "username";
} else {
queryValue = data.data.results[0].name;
queryType = "name";
}
// get how many results are less than or equal to
// the name
return $http.get(url + "?" + queryType + "__lte=" + queryValue)
.then(function (data) {
// divide by the page size to get what
// page the data should be on
var count = data.data.count;
return Math.ceil(count/parseInt(pageSize));
});
});
} else {
var defer = $q.defer();
defer.resolve(1);
return(defer.promise);
}
}
};
}];
|
Make functions static to prevent deprecated warnings | <?php
namespace Recras;
class Editor
{
/**
* Add the shortcode generator buttons to TinyMCE
*/
public static function addButtons()
{
add_filter('mce_buttons', ['Recras\Editor', 'registerButtons']);
add_filter('mce_external_plugins', ['Recras\Editor', 'addScripts']);
add_thickbox();
}
/**
* Load the script needed for TinyMCE
*
* @param array $plugins
*
* @return array
*/
public static function addScripts($plugins)
{
global $recras;
$plugins['recras'] = $recras->baseUrl . '/editor/plugin.js';
return $plugins;
}
/**
* Load the TinyMCE translation
*
* @param array $locales
*
* @return array
*/
public static function loadTranslations($locales)
{
$locales['recras'] = plugin_dir_path(__FILE__) . '/editor/translation.php';
return $locales;
}
/**
* Register TinyMCE buttons
*
* @param array $buttons
*
* @return array
*/
public static function registerButtons($buttons)
{
array_push($buttons, 'recras-arrangement', 'recras-booking', 'recras-contact', 'recras-product');
return $buttons;
}
}
| <?php
namespace Recras;
class Editor
{
/**
* Add the shortcode generator buttons to TinyMCE
*/
public static function addButtons()
{
add_filter('mce_buttons', ['Recras\Editor', 'registerButtons']);
add_filter('mce_external_plugins', ['Recras\Editor', 'addScripts']);
add_thickbox();
}
/**
* Load the script needed for TinyMCE
*
* @param array $plugins
*
* @return array
*/
public function addScripts($plugins)
{
global $recras;
$plugins['recras'] = $recras->baseUrl . '/editor/plugin.js';
return $plugins;
}
/**
* Load the TinyMCE translation
*
* @param array $locales
*
* @return array
*/
public function loadTranslations($locales)
{
$locales['recras'] = plugin_dir_path(__FILE__) . '/editor/translation.php';
return $locales;
}
/**
* Register TinyMCE buttons
*
* @param array $buttons
*
* @return array
*/
public function registerButtons($buttons)
{
array_push($buttons, 'recras-arrangement', 'recras-booking', 'recras-contact', 'recras-product');
return $buttons;
}
}
|
Use META.SERVER_NAME in template view. … | # -*- coding: utf-8 -*-
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.views.generic.base import TemplateView
from django.views.decorators.csrf import csrf_exempt
import redis
from ws4redis import settings as redis_settings
class BaseTemplateView(TemplateView):
def __init__(self):
self._connection = redis.StrictRedis(**redis_settings.WS4REDIS_CONNECTION)
def get_context_data(self, **kwargs):
context = super(BaseTemplateView, self).get_context_data(**kwargs)
context.update(ws_url='ws://{SERVER_NAME}:{SERVER_PORT}/ws/foobar'.format(**self.request.META))
return context
class BroadcastChatView(BaseTemplateView):
template_name = 'broadcast_chat.html'
def __init__(self):
super(BroadcastChatView, self).__init__()
self._connection.set('_broadcast_:foobar', 'Hello, Websockets')
class UserChatView(BaseTemplateView):
template_name = 'user_chat.html'
def get_context_data(self, **kwargs):
users = User.objects.all()
context = super(UserChatView, self).get_context_data(**kwargs)
context.update(users=users)
return context
@csrf_exempt
def post(self, request, *args, **kwargs):
channel = u'{0}:foobar'.format(request.POST.get('user'))
self._connection.publish(channel, request.POST.get('message'))
return HttpResponse('OK')
| # -*- coding: utf-8 -*-
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.views.generic.base import TemplateView
from django.views.decorators.csrf import csrf_exempt
import redis
from ws4redis import settings as redis_settings
class BaseTemplateView(TemplateView):
def __init__(self):
self._connection = redis.StrictRedis(**redis_settings.WS4REDIS_CONNECTION)
def get_context_data(self, **kwargs):
context = super(BaseTemplateView, self).get_context_data(**kwargs)
context.update(ws_url='ws://localhost:{SERVER_PORT}/ws/foobar'.format(**self.request.META))
return context
class BroadcastChatView(BaseTemplateView):
template_name = 'broadcast_chat.html'
def __init__(self):
super(BroadcastChatView, self).__init__()
self._connection.set('_broadcast_:foobar', 'Hello, Websockets')
class UserChatView(BaseTemplateView):
template_name = 'user_chat.html'
def get_context_data(self, **kwargs):
users = User.objects.all()
context = super(UserChatView, self).get_context_data(**kwargs)
context.update(users=users)
return context
@csrf_exempt
def post(self, request, *args, **kwargs):
channel = u'{0}:foobar'.format(request.POST.get('user'))
self._connection.publish(channel, request.POST.get('message'))
return HttpResponse('OK')
|
Change interval from 4 to 7 seconds | <?php
class CodesController extends \BaseController {
public function process($code)
{
$code = Code::where('code', '=', $code)->first();
if(is_null($code) || $code->used == 1){
return Redirect::to('/')->with('error', 'Nie znaleziono!');
} else {
//Snapchatty functions
//Refresh(disappear) after 7 seconds
header("Refresh: " . 7);
$code->used = 1;
$code->used_time = Carbon::now();
$code->used_ip = Request::getClientIp();
$mobileDetect = new Mobile_Detect();
//Check for facebook bots (done in robots.txt)
$code->used_useragent = $mobileDetect->getUserAgent();
$code->save();
$path = storage_path().'/memes/'.Meme::find($code->meme_id)->filename;
// Get the image
$image = Image::make($path)->widen(600, function ($constraint) {
$constraint->upsize();
})->encode('data-url');
return View::make('meme')->withMeme($code->meme)->withImage($image);
}
}
} | <?php
class CodesController extends \BaseController {
public function process($code)
{
$code = Code::where('code', '=', $code)->first();
if(is_null($code) || $code->used == 1){
return Redirect::to('/')->with('error', 'Nie znaleziono!');
} else {
//Snapchatty functions
//Refresh(disappear) after 4 seconds
header("Refresh: " . 4);
$code->used = 1;
$code->used_time = Carbon::now();
$code->used_ip = Request::getClientIp();
$mobileDetect = new Mobile_Detect();
//Check for facebook bots (done in robots.txt)
$code->used_useragent = $mobileDetect->getUserAgent();
$code->save();
$path = storage_path().'/memes/'.Meme::find($code->meme_id)->filename;
// Get the image
$image = Image::make($path)->widen(600, function ($constraint) {
$constraint->upsize();
})->encode('data-url');
return View::make('meme')->withMeme($code->meme)->withImage($image);
}
}
} |
Remove user_mail from request data | from ckan.lib import base
from ckan.common import c, _
from ckan import logic
from ckanext.requestdata import emailer
from ckan.plugins import toolkit
import ckan.model as model
import ckan.plugins as p
import json
get_action = logic.get_action
NotFound = logic.NotFound
NotAuthorized = logic.NotAuthorized
ValidationError = logic.ValidationError
abort = base.abort
BaseController = base.BaseController
class RequestDataController(BaseController):
def send_request(self):
'''Send mail to resource owner.
:param data: Contact form data.
:type data: object
:rtype: json
'''
print "Entered"
context = {'model': model, 'session': model.Session,
'user': c.user, 'auth_user_obj': c.userobj}
try:
if p.toolkit.request.method == 'POST':
data = dict(toolkit.request.POST)
content = data["message_content"]
to = data['email_address']
mail_subject = "Request data"
get_action('requestdata_request_create')(context, data)
except NotAuthorized:
abort(403, _('Unauthorized to update this dataset.'))
except ValidationError:
error = {
'success': False,
'error': {
'message': 'An error occurred while requesting the data.'
}
}
return json.dumps(error)
response_message = emailer.send_email(content, to, mail_subject)
return json.dumps(response_message) | from ckan.lib import base
from ckan.common import c, _
from ckan import logic
from ckanext.requestdata import emailer
from ckan.plugins import toolkit
import ckan.model as model
import ckan.plugins as p
import json
get_action = logic.get_action
NotFound = logic.NotFound
NotAuthorized = logic.NotAuthorized
ValidationError = logic.ValidationError
abort = base.abort
BaseController = base.BaseController
class RequestDataController(BaseController):
def send_request(self):
'''Send mail to resource owner.
:param data: Contact form data.
:type data: object
'''
print "Entered"
context = {'model': model, 'session': model.Session,
'user': c.user, 'auth_user_obj': c.userobj}
try:
if p.toolkit.request.method == 'POST':
data = dict(toolkit.request.POST)
content = data["message_content"]
to = data['email_address']
user = context['auth_user_obj']
mail_subject = "Request data"
user_email = user.email
get_action('requestdata_request_create')(context, data)
except NotAuthorized:
abort(403, _('Unauthorized to update this dataset.'))
except ValidationError:
error = {
'success': False,
'error': {
'message': 'An error occurred while requesting the data.'
}
}
return json.dumps(error)
response_message = emailer.send_email(content, to, user_email, mail_subject)
return json.dumps(response_message) |
Fix error message in the scikitlearn extension. |
# coding: utf-8
# A jinja extension for the harness
# In[9]:
try:
from .base import HarnessExtension
except:
from base import HarnessExtension
import pandas, sklearn.model_selection as model_selection
from toolz.curried import first
# In[10]:
class SciKitExtension(HarnessExtension):
alias = 'sklearn'
def keywords(self, dataframe):
return {
'X': lambda: dataframe.values,
'y': lambda:
dataframe.index.get_level_values(dataframe.feature_level)
if dataframe.feature_level else None,
}
def pipe(self, dataframe, attr):
self.module_ = dataframe.estimator
return super().pipe(dataframe, attr)
def callback(self, dataframe, value):
if value is dataframe.estimator:
return dataframe
if isinstance(value, pandas.np.ndarray):
return dataframe.__class__(
value,
index=dataframe.index,
feature_level=dataframe.feature_level,
)
if isinstance(value, pandas.CategoricalIndex):
# new dataframe
value = dataframe.set_index(value, append=True)
value.index = value.index.reorder_levels([-1, *range(
len(dataframe.index.levels) if hasattr(dataframe.index, 'levels') else 1
)])
return value
|
# coding: utf-8
# A jinja extension for the harness
# In[9]:
try:
from .base import HarnessExtension
except:
from base import HarnessExtension
import pandas, sklearn.model_selection as model_selection
from toolz.curried import first
# In[11]:
get_ipython().magic('pinfo2 model_selection.ShuffleSplit')
# In[10]:
class SciKitExtension(HarnessExtension):
alias = 'sklearn'
def keywords(self, dataframe):
return {
'X': lambda: dataframe.values,
'y': lambda:
dataframe.index.get_level_values(dataframe.feature_level)
if dataframe.feature_level else None,
}
def pipe(self, dataframe, attr):
self.module_ = dataframe.estimator
return super().pipe(dataframe, attr)
def callback(self, dataframe, value):
if value is dataframe.estimator:
return dataframe
if isinstance(value, pandas.np.ndarray):
return dataframe.__class__(
value,
index=dataframe.index,
feature_level=dataframe.feature_level,
)
if isinstance(value, pandas.CategoricalIndex):
# new dataframe
value = dataframe.set_index(value, append=True)
value.index = value.index.reorder_levels([-1, *range(
len(dataframe.index.levels) if hasattr(dataframe.index, 'levels') else 1
)])
return value
|
Refactor of one assignment test | # -*- coding: utf-8 -*-
import unittest
dbconfig = None
try:
import dbconfig
import erppeek
except ImportError:
pass
@unittest.skipIf(not dbconfig, "depends on ERP")
class Assignment_Test(unittest.TestCase):
def setUp(self):
self.erp = erppeek.Client(**dbconfig.erppeek)
self.Assignments = self.erp.GenerationkwhAssignments
self.tearDown()
def setupProvider(self,assignments=[]):
self.Assignments.add(assignments)
def assertAssignmentsEqual(self, expectation):
result = self.Assignments.browse([])
self.assertEqual([
[r.active,
r.polissa_id.id,
r.member_id.id,
r.priority]
for r in result],
expectation)
def tearDown(self):
for a in self.Assignments.browse([]):
a.unlink()
def test_no_assignments(self):
self.setupProvider()
self.assertAssignmentsEqual([])
def test_one_assignment(self):
rp=self.erp.ResPartner.browse([],limit=1)[0]
gp=self.erp.GiscedataPolissa.browse([], limit=1)[0]
self.setupProvider([[True,gp.id,rp.id,1]])
self.assertAssignmentsEqual([[True,gp.id,rp.id,1]])
"""def test_no_duplication(self):
rp=self.erp.ResPartner.browse([], limit=1)[0]
gp=self.erp.GiscedataPolissa.browse([],limit=1)[0]
self.setupProvider([[True,gp.id,rp.id,1]])
self.assertAssignmentsEqual([[True,gp.id,rp.id,1]])"""
if __name__ == '__main__':
unittest.main()
| # -*- coding: utf-8 -*-
import unittest
dbconfig = None
try:
import dbconfig
import erppeek
except ImportError:
pass
@unittest.skipIf(not dbconfig, "depends on ERP")
class Assignment_Test(unittest.TestCase):
def setUp(self):
self.erp = erppeek.Client(**dbconfig.erppeek)
self.Assignments = self.erp.GenerationkwhAssignments
self.tearDown()
def setupProvider(self,assignments=[]):
self.Assignments.add(assignments)
def assertAssignmentsEqual(self, expectation):
result = self.Assignments.browse([])
self.assertEqual([
[r.active,
r.polissa_id.id,
r.member_id.id,
r.priority]
for r in result],
expectation)
def tearDown(self):
for a in self.Assignments.browse([]):
a.unlink()
def test_no_assignments(self):
self.setupProvider()
self.assertAssignmentsEqual([])
def test_one_assignment(self):
rp=self.erp.ResPartner.browse([])[0]
gp=self.erp.GiscedataPolissa.browse([])[0]
self.setupProvider([[True,gp.id,rp.id,1]])
self.assertAssignmentsEqual([[True,gp.id,rp.id,1]])
if __name__ == '__main__':
unittest.main()
|
Update redux dev tool configuration | // Redux
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
// import createLogger from 'redux-logger';
// import Immutable from 'immutable';
import rootReducer from '../reducers';
// const __DEV__ = process.env.NODE_ENV === 'production' ? false : true;
const finalCreateStore = compose(
applyMiddleware(thunk),
window.devToolsExtension ? window.devToolsExtension() : f => f
// applyMiddleware(createLogger({
// // Only logs in development mode
// predicate: () => __DEV__,
// // Transform Immutable object to plain json for better debuggin experience
// transformer: (state) => {
// var newState = {};
// for (var i of Object.keys(state)) {
// if (Immutable.Iterable.isIterable(state[i])) {
// newState[i] = state[i].toJS();
// } else {
// newState[i] = state[i];
// }
// };
// return newState;
// }
// }))
)(createStore);
export default function configureStore(initialState) {
const store = finalCreateStore(rootReducer, initialState);
if (module.hot) {
// Enable Webpack hot module replacement for reducers
module.hot.accept('../reducers', () => {
const nextRootReducer = require('../reducers');
store.replaceReducer(nextRootReducer);
});
}
return store;
};
| // Redux
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
// import createLogger from 'redux-logger';
// import Immutable from 'immutable';
import rootReducer from '../reducers';
// const __DEV__ = process.env.NODE_ENV === 'production' ? false : true;
const finalCreateStore = compose(
applyMiddleware(thunk),
window.devToolsExtension() || (f => f),
// applyMiddleware(createLogger({
// // Only logs in development mode
// predicate: () => __DEV__,
// // Transform Immutable object to plain json for better debuggin experience
// transformer: (state) => {
// var newState = {};
// for (var i of Object.keys(state)) {
// if (Immutable.Iterable.isIterable(state[i])) {
// newState[i] = state[i].toJS();
// } else {
// newState[i] = state[i];
// }
// };
// return newState;
// }
// }))
)(createStore);
export default function configureStore(initialState) {
const store = finalCreateStore(rootReducer, initialState);
if (module.hot) {
// Enable Webpack hot module replacement for reducers
module.hot.accept('../reducers', () => {
const nextRootReducer = require('../reducers');
store.replaceReducer(nextRootReducer);
});
}
return store;
};
|
Change print statement to logger.debug | # -*- coding: utf-8 -*-
# ###
# Copyright (c) 2015, Rice University
# This software is subject to the provisions of the GNU Affero General
# Public License version 3 (AGPLv3).
# See LICENCE.txt for details.
# ###
"""Rollback a migration."""
from .. import logger, utils
__all__ = ('cli_loader',)
@utils.with_cursor
def cli_command(cursor, migrations_directory='', steps=1,
db_connection_string='', **kwargs):
migrated_versions = list(utils.get_schema_versions(
cursor, include_deferred=False))
logger.debug('migrated_versions: {}'.format(migrated_versions))
if not migrated_versions:
print('No migrations to roll back.')
return
migrations = utils.get_migrations(
migrations_directory, import_modules=True, reverse=True)
rolled_back = 0
for version, migration_name, migration in migrations:
if not migrated_versions:
break
last_version = migrated_versions[-1]
if version == last_version:
utils.compare_schema(db_connection_string,
utils.rollback_migration,
cursor,
version,
migration_name,
migration)
rolled_back += 1
migrated_versions.pop()
if rolled_back >= steps:
break
if not rolled_back:
print('No migrations to roll back.')
def cli_loader(parser):
parser.add_argument('--steps', metavar='N', default=1, type=int,
help='Roll back the last N migrations, default 1')
return cli_command
| # -*- coding: utf-8 -*-
# ###
# Copyright (c) 2015, Rice University
# This software is subject to the provisions of the GNU Affero General
# Public License version 3 (AGPLv3).
# See LICENCE.txt for details.
# ###
"""Rollback a migration."""
from .. import utils
__all__ = ('cli_loader',)
@utils.with_cursor
def cli_command(cursor, migrations_directory='', steps=1,
db_connection_string='', **kwargs):
migrated_versions = list(utils.get_schema_versions(
cursor, include_deferred=False))
print('migrated_versions: {}'.format(migrated_versions))
if not migrated_versions:
print('No migrations to roll back.')
return
migrations = utils.get_migrations(
migrations_directory, import_modules=True, reverse=True)
rolled_back = 0
for version, migration_name, migration in migrations:
if not migrated_versions:
break
last_version = migrated_versions[-1]
if version == last_version:
utils.compare_schema(db_connection_string,
utils.rollback_migration,
cursor,
version,
migration_name,
migration)
rolled_back += 1
migrated_versions.pop()
if rolled_back >= steps:
break
if not rolled_back:
print('No migrations to roll back.')
def cli_loader(parser):
parser.add_argument('--steps', metavar='N', default=1, type=int,
help='Roll back the last N migrations, default 1')
return cli_command
|
Delete several commented out lines. | package com.biotronisis.pettplant.communication.transfer;
import java.io.Serializable;
public abstract class AbstractResponse implements Serializable {
private static final long serialVersionUID = 1L;
public abstract void fromResponseBytes(byte[] responseBytes);
public abstract Byte getResponseId();
public abstract int getMinimumResponseLength();
public int asInt(byte msb, byte lsb) {
int msbInt = msb & (0x000000FF);
int lsbInt = lsb & (0x000000FF);
// int result = (msbInt << 8) + lsbInt; // DEBUG
// return result;
return (msbInt << 8) + lsbInt;
}
int asInt(byte myByte) {
return myByte & (0x000000FF);
}
public boolean validateChecksum(byte[] bytes) {
boolean result = true;
if (bytes.length < getMinimumResponseLength()) {
result = false;
}
// int msglen = bytes[0]+1;
if (bytes.length != bytes[0] + 1) {
result = false;
}
byte checksum = 0;
for (int i = 0; i < bytes.length - 1; i++) {
checksum ^= bytes[i];
}
if (checksum != bytes[bytes.length - 1]) {
result = false;
}
return result;
}
}
| package com.biotronisis.pettplant.communication.transfer;
import java.io.Serializable;
public abstract class AbstractResponse implements Serializable {
private static final long serialVersionUID = 1L;
public abstract void fromResponseBytes(byte[] responseBytes);
public abstract Byte getResponseId();
public abstract int getMinimumResponseLength();
public int asInt(byte msb, byte lsb) {
int msbInt = msb & (0x000000FF);
int lsbInt = lsb & (0x000000FF);
// int result = (msbInt << 8) + lsbInt; // DEBUG
// return result;
return (msbInt << 8) + lsbInt;
}
int asInt(byte myByte) {
return myByte & (0x000000FF);
}
public boolean validateChecksum(byte[] bytes) {
boolean result = true;
if (bytes.length < getMinimumResponseLength()) {
result = false;
// return false; // DEBUG
}
// int msglen = bytes[0]+1;
if (bytes.length != bytes[0] + 1) {
result = false;
// return false;
}
byte checksum = 0;
for (int i = 0; i < bytes.length - 1; i++) {
checksum ^= bytes[i];
}
if (checksum != bytes[bytes.length - 1]) {
result = false;
// return false;
}
return result;
// return true;
}
}
|
Remove code which blanks patch files | #! /usr/bin/python2.3
# vim:sw=8:ts=8:et:nowrap
import os
import shutil
def ApplyPatches(filein, fileout):
# Generate short name such as wrans/answers2003-03-31.html
(rest, name) = os.path.split(filein)
(rest, dir) = os.path.split(rest)
fileshort = os.path.join(dir, name)
# Look for a patch file from our collection (which is
# in the pyscraper/patches folder in Public Whip CVS)
patchfile = os.path.join("patches", fileshort + ".patch")
if not os.path.isfile(patchfile):
return False
while True:
# Apply the patch
shutil.copyfile(filein, fileout)
# delete temporary file that might have been created by a previous patch failure
filoutorg = fileout + ".orig"
if os.path.isfile(filoutorg):
os.remove(filoutorg)
status = os.system("patch --quiet %s <%s" % (fileout, patchfile))
if status == 0:
return True
raise Exception, "Error running 'patch' on file %s" % fileshort
#print "blanking out %s" % fileshort
#os.rename(patchfile, patchfile + ".old~")
#blankfile = open(patchfile, "w")
#blankfile.close()
| #! /usr/bin/python2.3
# vim:sw=8:ts=8:et:nowrap
import os
import shutil
def ApplyPatches(filein, fileout):
# Generate short name such as wrans/answers2003-03-31.html
(rest, name) = os.path.split(filein)
(rest, dir) = os.path.split(rest)
fileshort = os.path.join(dir, name)
# Look for a patch file from our collection (which is
# in the pyscraper/patches folder in Public Whip CVS)
patchfile = os.path.join("patches", fileshort + ".patch")
if not os.path.isfile(patchfile):
return False
while True:
# Apply the patch
shutil.copyfile(filein, fileout)
# delete temporary file that might have been created by a previous patch failure
filoutorg = fileout + ".orig"
if os.path.isfile(filoutorg):
os.remove(filoutorg)
status = os.system("patch --quiet %s <%s" % (fileout, patchfile))
if status == 0:
return True
print "Error running 'patch' on file %s, blanking it out" % fileshort
os.rename(patchfile, patchfile + ".old~")
blankfile = open(patchfile, "w")
blankfile.close()
|
Add test for passing paths with variables to create_urlspec_regex. | from unittest import TestCase
from go_store_service.api_handler import (
ApiApplication, create_urlspec_regex, CollectionHandler,
ElementHandler)
class TestCreateUrlspecRegex(TestCase):
def test_no_variables(self):
self.assertEqual(create_urlspec_regex("/foo/bar"), "/foo/bar")
def test_one_variable(self):
self.assertEqual(
create_urlspec_regex("/:foo/bar"), "/(?P<foo>[^/]*)/bar")
def test_two_variables(self):
self.assertEqual(
create_urlspec_regex("/:foo/bar/:baz"),
"/(?P<foo>[^/]*)/bar/(?P<baz>[^/]*)")
class TestApiApplication(TestCase):
def test_build_routes(self):
collection_factory = lambda **kw: "collection"
app = ApiApplication()
app.collections = (
('/:owner_id/store', collection_factory),
)
[collection_route, elem_route] = app._build_routes()
self.assertEqual(collection_route.handler_class, CollectionHandler)
self.assertEqual(collection_route.regex.pattern,
"/(?P<owner_id>[^/]*)/store$")
self.assertEqual(collection_route.kwargs, {
"collection_factory": collection_factory,
})
self.assertEqual(elem_route.handler_class, ElementHandler)
self.assertEqual(elem_route.regex.pattern,
"/(?P<owner_id>[^/]*)/store/(?P<elem_id>[^/]*)$")
self.assertEqual(elem_route.kwargs, {
"collection_factory": collection_factory,
})
| from unittest import TestCase
from go_store_service.api_handler import (
ApiApplication, create_urlspec_regex, CollectionHandler,
ElementHandler)
class TestCreateUrlspecRegex(TestCase):
def test_no_variables(self):
self.assertEqual(create_urlspec_regex("/foo/bar"), "/foo/bar")
class TestApiApplication(TestCase):
def test_build_routes(self):
collection_factory = lambda **kw: "collection"
app = ApiApplication()
app.collections = (
('/:owner_id/store', collection_factory),
)
[collection_route, elem_route] = app._build_routes()
self.assertEqual(collection_route.handler_class, CollectionHandler)
self.assertEqual(collection_route.regex.pattern,
"/(?P<owner_id>[^/]*)/store$")
self.assertEqual(collection_route.kwargs, {
"collection_factory": collection_factory,
})
self.assertEqual(elem_route.handler_class, ElementHandler)
self.assertEqual(elem_route.regex.pattern,
"/(?P<owner_id>[^/]*)/store/(?P<elem_id>[^/]*)$")
self.assertEqual(elem_route.kwargs, {
"collection_factory": collection_factory,
})
|
Correct error in URL mappings | from django.conf.urls import patterns, include, url
from django.contrib import admin
from sysrev.views import *
urlpatterns = patterns(
'',
url(r'^$', ReviewListView.as_view(), name='index'),
url(r'^review/(?P<pk>\d+)(-([\w\-]+))?/$', ReviewDetailView.as_view(), name='review'),
url(r'^review/(?P<pk>\d+)(-([\w\-]+))?/update$', ReviewUpdateView.as_view(), name='review_update'),
url(r'^review/(?P<pk>\d+)(-([\w\-]+))?/delete$', ReviewDeleteView.as_view(), name='review_delete'),
url(r'^create/', ReviewCreateWizard.as_view(), name='create'),
url(r'^review/(?P<pk>\d+)(-([\w\-]+))?/(?P<pk2>\d+)/$', PaperDetailView.as_view(), name='paper'),
url(r'^profile/', ProfileView.as_view(), name='profile'),
url(r'^accounts/register/$', SRRegistrationView.as_view(), name='registration_register'),
url(r'^accounts/', include('registration.backends.simple.urls')),
url(r'^accounts/', include('django.contrib.auth.urls')),
url(r'^admin/', include(admin.site.urls)),
)
| from django.conf.urls import patterns, include, url
from django.contrib import admin
from sysrev.views import *
urlpatterns = patterns(
'',
url(r'^$', ReviewListView.as_view(), name='index'),
url(r'^review/(?P<pk>\d+)(-([\w\-]+))?/$', ReviewDetailView.as_view(), name='review'),
url(r'^review/(?P<pk>\d+)(-([\w\-]+))?/delete$', ReviewUpdateView.as_view(), name='review_update'),
url(r'^review/(?P<pk>\d+)(-([\w\-]+))?/delete$', ReviewDeleteView.as_view(), name='review_delete'),
url(r'^create/', ReviewCreateWizard.as_view(), name='create'),
url(r'^review/(?P<pk>\d+)(-([\w\-]+))?/(?P<pk2>\d+)/$', PaperDetailView.as_view(), name='paper'),
url(r'^profile/', ProfileView.as_view(), name='profile'),
url(r'^accounts/register/$', SRRegistrationView.as_view(), name='registration_register'),
url(r'^accounts/', include('registration.backends.simple.urls')),
url(r'^accounts/', include('django.contrib.auth.urls')),
url(r'^admin/', include(admin.site.urls)),
)
|
Change about read "token" & "domain" | import requests
import json
import time
import sys
file = open('token.txt', 'r')
_token = file.readline()
file.close()
file = open('domain.txt', 'r')
_domain = file.readline()
def del_time(Day):
Set_time = str(int(time.time())-Day*86400)
return Set_time
def files_list(Day):
Del_time = del_time(Day)
files_list_url = "https://slack.com/api/files.list"
data = {
"token": _token,
"ts_to": Del_time,
"count":1000
}
response = requests.post(files_list_url,data)
if response.json()["ok"] == 0:
print("Error_exit(around API's argument)")
sys.exit()
return response.json()["files"]
def delete():
return
if __name__ == '__main__':
while 1:
files = files_list(0)
if len(files) == 0:
print ("No files")
break
for f in files:
print ("Deleting file " + f["name"] + "...")
delete_url = "https://slack.com/api/files.delete"
data = {
"token": _token,
"file": f["id"],
"set_active": "true",
"_attempts": "1"
}
requests.post(delete_url, data)
print ("complete")
| import requests
import json
import time
import sys
_token = "xxxxxxx"
_domain = "xxxxxxx"
def del_time(Day):
Set_time = str(int(time.time())-Day*86400)
return Set_time
def files_list(Day):
Del_time = del_time(Day)
files_list_url = "https://slack.com/api/files.list"
data = {
"token": _token,
"ts_to": Del_time,
"count":1000
}
response = requests.post(files_list_url,data)
if response.json()["ok"] == 0:
print("Error_exit(around API's argument)")
sys.exit()
return response.json()["files"]
def delete():
return
if __name__ == '__main__':
while 1:
files = files_list(0)
if len(files) == 0:
print ("No files")
break
for f in files:
print ("Deleting file " + f["name"] + "...")
delete_url = "https://slack.com/api/files.delete"
data = {
"token": _token,
"file": f["id"],
"set_active": "true",
"_attempts": "1"
}
requests.post(delete_url, data)
print ("complete")
|
Put a timer on reload to wait for autosave to finish | (function (ng, app) {
app.config(['$stateProvider', function ($stateProvider) {
$stateProvider.state('it-system.usage.contracts', {
url: '/contracts',
templateUrl: 'partials/it-system/tab-contracts.html',
controller: 'system.EditContracts',
resolve: {
}
});
}]);
app.controller('system.EditContracts', ['$scope', '$state', '$stateParams', '$timeout', 'itSystemUsage',
function ($scope, $state, $stateParams, $timeout, itSystemUsage) {
$scope.reload = function() {
$timeout(reload, 1000); // OMG HACK! TODO refactor! This is to wait for the autosave to finish then reload the view to reflect the change
}
// work around for $state.reload() not updating scope
// https://github.com/angular-ui/ui-router/issues/582
function reload() {
return $state.transitionTo($state.current, $stateParams, {
reload: true
}).then(function () {
$scope.hideContent = true;
return $timeout(function () {
return $scope.hideContent = false;
}, 1);
});
};
}]);
})(angular, app); | (function (ng, app) {
app.config(['$stateProvider', function ($stateProvider) {
$stateProvider.state('it-system.usage.contracts', {
url: '/contracts',
templateUrl: 'partials/it-system/tab-contracts.html',
controller: 'system.EditContracts',
resolve: {
}
});
}]);
app.controller('system.EditContracts', ['$scope', '$state', '$stateParams', '$timeout', 'itSystemUsage',
function ($scope, $state, $stateParams, $timeout, itSystemUsage) {
$scope.reload = function() {
reload(); // OMG HACK! TODO refactor! This is to wait for the autosave to finish then reload the view to reflect the change
}
// work around for $state.reload() not updating scope
// https://github.com/angular-ui/ui-router/issues/582
function reload() {
return $state.transitionTo($state.current, $stateParams, {
reload: true
}).then(function () {
$scope.hideContent = true;
return $timeout(function () {
return $scope.hideContent = false;
}, 1);
});
};
}]);
})(angular, app); |
Make the user in the profile update a copy | {
angular
.module('meganote.users')
.directive('userProfile', [
'CurrentUser',
'UsersService',
(CurrentUser, UsersService) => {
class UserProfileController {
constructor() {
this.user = angular.copy(CurrentUser.get());
}
submit() {
UsersService.update(this.user);
}
}
return {
scope: {},
controller: UserProfileController,
controllerAs: 'vm',
bindToController: true,
template: `
<div class="container">
<div class="row">
<div class="col-xs-6 col-xs-offset-4">
<h3>Update your profile</h3>
<form id="new_user" ng-submit="vm.submit()">
<p>
<label for="name">Full Name</label><br>
<input
type="text"
name="name"
autofocus="autofocus"
ng-model="vm.user.name"
required>
</p>
<p>
<label for="username">Username</label><br>
<input
type="text"
name="username"
ng-model="vm.user.username"
required>
</p>
<input
type="submit"
name="commit"
value="Save Changes"
class="btn btn-default">
</form>
</div>
</div>
</div>
`
}
}
])
}
| {
angular
.module('meganote.users')
.directive('userProfile', [
'CurrentUser',
'UsersService',
(CurrentUser, UsersService) => {
class UserProfileController {
constructor() {
this.user = CurrentUser.get();
}
submit() {
UsersService.update(this.user);
}
}
return {
scope: {},
controller: UserProfileController,
controllerAs: 'vm',
bindToController: true,
template: `
<div class="container">
<div class="row">
<div class="col-xs-6 col-xs-offset-4">
<h3>Update your profile</h3>
<form id="new_user" ng-submit="vm.submit()">
<p>
<label for="name">Full Name</label><br>
<input
type="text"
name="name"
autofocus="autofocus"
ng-model="vm.user.name"
required>
</p>
<p>
<label for="username">Username</label><br>
<input
type="text"
name="username"
ng-model="vm.user.username"
required>
</p>
<input
type="submit"
name="commit"
value="Save Changes"
class="btn btn-default">
</form>
</div>
</div>
</div>
`
}
}
])
}
|
Fix typo in content type | <?php
namespace OParl\Website\Api\Controllers;
use function Swagger\scan;
/**
* @SWG\Swagger(
* schemes={"https"},
* host="dev.oparl.org",
* basePath="/api/",
* @SWG\Info(
* title="OParl Developer Platform API",
* description="Meta information concerning the OParl ecosystem",
* version="0",
* @SWG\License(
* name="CC-4.0-BY",
* url="https://creativecommons.org/licenses/by/4.0/"
* )
* ),
* produces={ "application/json" }
* )
*/
class ApiController
{
/**
* Return the dynamically updated swagger.json for the meta endpoints.
*
* @return \Symfony\Component\HttpFoundation\Response
*/
public function swaggerJson()
{
$swagger = scan(base_path('lib/Api/Controllers'));
return response($swagger, 200, [
'Content-Type' => 'application/json',
'Access-Control-Allow-Origin' => '*',
]);
}
/**
* Index page for the api.
*
* @return \Symfony\Component\HttpFoundation\Response
*/
public function index()
{
return view('api.index');
}
}
| <?php
namespace OParl\Website\Api\Controllers;
use function Swagger\scan;
/**
* @SWG\Swagger(
* schemes={"https"},
* host="dev.oparl.org",
* basePath="/api/",
* @SWG\Info(
* title="OParl Developer Platform API",
* description="Meta information concerning the OParl ecosystem",
* version="0",
* @SWG\License(
* name="CC-4.0-BY",
* url="https://creativecommons.org/licenses/by/4.0/"
* )
* ),
* produces={ "application/json" }
* )
*/
class ApiController
{
/**
* Return the dynamically updated swagger.json for the meta endpoints.
*
* @return \Symfony\Component\HttpFoundation\Response
*/
public function swaggerJson()
{
$swagger = scan(base_path('lib/Api/Controllers'));
return response($swagger, 200, [
'Content-Tyype' => 'application/json',
'Access-Control-Allow-Origin' => '*',
]);
}
/**
* Index page for the api.
*
* @return \Symfony\Component\HttpFoundation\Response
*/
public function index()
{
return view('api.index');
}
}
|
Add button appears but not aligned | <h1><?php echo $recipe->name; ?></h1>
<div class="row recipe-quick-facts">
<div class="col-md-4">
<h4>Servings</h4>
<?php echo $recipe->servings; ?>
</div>
<div class="col-md-4">
<h4>Prep Time</h4>
<?php echo display_time($recipe->time_prep); ?>
</div>
<div class="col-md-4">
<h4>Cook Time</h4>
<?php echo display_time($recipe->time_cook); ?>
</div>
</div>
<div class="recipe-ingredients">
<h2>Ingredients</h2>
<ul id="ingredients" class="list-group">
<?php
foreach ($ingredients as $single_ingredient) {
$data = array(
'ingredient' => $single_ingredient
);
$this->load->view('recipes/_ingredient', $data);
}
?>
</ul>
<?php $this->load->view('recipes/_add_ingredient'); ?>
</div><!-- /.recipe-ingredients -->
<div class="recipe-steps">
<h2>Steps</h2>
<ul id="steps" class="list-group">
<?php
foreach ($steps as $single_step) {
$data = array(
'step' => $single_step
);
$this->load->view('recipes/_step', $data);
}
?>
</ul>
</div><!-- /.recipe-steps -->
| <h1><?php echo $recipe->name; ?></h1>
<div class="row recipe-quick-facts">
<div class="col-md-4">
<h4>Servings</h4>
<?php echo $recipe->servings; ?>
</div>
<div class="col-md-4">
<h4>Prep Time</h4>
<?php echo display_time($recipe->time_prep); ?>
</div>
<div class="col-md-4">
<h4>Cook Time</h4>
<?php echo display_time($recipe->time_cook); ?>
</div>
</div>
<div class="recipe-ingredients">
<h2>Ingredients</h2>
<ul id="ingredients" class="list-group">
<?php
foreach ($ingredients as $single_ingredient) {
$data = array(
'ingredient' => $single_ingredient
);
$this->load->view('recipes/_ingredient', $data);
}
?>
</ul>
</div><!-- /.recipe-ingredients -->
<div class="recipe-steps">
<h2>Steps</h2>
<ul id="steps" class="list-group">
<?php
foreach ($steps as $single_step) {
$data = array(
'step' => $single_step
);
$this->load->view('recipes/_step', $data);
}
?>
</ul>
</div><!-- /.recipe-steps -->
|
Add field for test result return | __author__ = 'sharvey'
from classifiers import Classifier
from corpus.mysql.reddit import RedditMySQLCorpus
from ppm import Trie
class RedditPPM(Classifier):
corpus = None
trie = None
user = None
reddit = None
order = 5
def __init__(self, corpus):
self.corpus = corpus
def train(self, corpus_type, user, reddit, char_count, order=5):
if (self.trie is not None):
del self.trie
self.trie = Trie(order)
self.reddit = reddit
self.user = user
document = self.corpus.get_train_documents(corpus_type, user, reddit, char_count).encode('utf-8')
for c in document:
self.trie.add(c)
def test(self, corpus_type, reddit, char_count):
documents = self.corpus.get_test_documents(corpus_type, reddit)
results = []
for row in documents:
test_bits = 0
newtrie = self.trie.duplicate()
document = row['text'].encode('utf-8')
for c in document:
newtrie.add(c)
test_bits += newtrie.bit_encoding
del newtrie
results.append({'id': row['id'],
'username': row['username'],
'label': (self.user == row['username']),
'score': test_bits/(len(document)*8)})
return results
| __author__ = 'sharvey'
from classifiers import Classifier
from corpus.mysql.reddit import RedditMySQLCorpus
from ppm import Trie
class RedditPPM(Classifier):
corpus = None
trie = None
user = None
reddit = None
order = 5
def __init__(self, corpus):
self.corpus = corpus
def train(self, corpus_type, user, reddit, char_count, order=5):
if (self.trie is not None):
del self.trie
self.trie = Trie(order)
self.reddit = reddit
self.user = user
document = self.corpus.get_train_documents(corpus_type, user, reddit, char_count).encode('utf-8')
for c in document:
self.trie.add(c)
def test(self, corpus_type, reddit, char_count):
documents = self.corpus.get_test_documents(corpus_type, reddit)
results = []
for row in documents:
test_bits = 0
newtrie = self.trie.duplicate()
document = row['text'].encode('utf-8')
for c in document:
newtrie.add(c)
test_bits += newtrie.bit_encoding
del newtrie
results.append({'id': row['id'],
'label': (self.user == row['username']),
'score': test_bits/(len(document)*8)})
return results
def run_reddit_experiment(corpus_type, char_count, reddits, mysql_opts):
corpus = RedditMySQLCorpus()
corpus.setup(**mysql_opts)
|
Update symfony and composer packages | <?php
namespace Enhavo\Bundle\ShopBundle\Form\Extension;
use Sylius\Bundle\ResourceBundle\Form\Type\ResourceTranslationsType;
use Sylius\Component\Resource\Translation\Provider\TranslationLocaleProviderInterface;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
class ResourceTranslationsExtension extends AbstractTypeExtension
{
/** @var string[] */
private $definedLocalesCodes;
/** @var string */
private $defaultLocaleCode;
public function __construct(TranslationLocaleProviderInterface $localeProvider)
{
$this->definedLocalesCodes = $localeProvider->getDefinedLocalesCodes();
$this->defaultLocaleCode = $localeProvider->getDefaultLocaleCode();
}
public function finishView(FormView $view, FormInterface $form, array $options)
{
$view->vars['translation_locales'] = $this->definedLocalesCodes;
$translationForms = [];
foreach ($view as $locale => $child) {
foreach ($child as $key => $childForm) {
if (!isset($forms[$key])) {
$translationForms[$key] = [];
}
$translationForms[$key][$locale] = $childForm;
}
}
$view->vars['translation_forms'] = $translationForms;
return;
}
public static function getExtendedTypes(): iterable
{
return [ResourceTranslationsType::class];
}
}
| <?php
namespace Enhavo\Bundle\ShopBundle\Form\Extension;
use Sylius\Bundle\ResourceBundle\Form\Type\ResourceTranslationsType;
use Sylius\Component\Resource\Translation\Provider\TranslationLocaleProviderInterface;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
class ResourceTranslationsExtension extends AbstractTypeExtension
{
/** @var string[] */
private $definedLocalesCodes;
/** @var string */
private $defaultLocaleCode;
public function __construct(TranslationLocaleProviderInterface $localeProvider)
{
$this->definedLocalesCodes = $localeProvider->getDefinedLocalesCodes();
$this->defaultLocaleCode = $localeProvider->getDefaultLocaleCode();
}
public function finishView(FormView $view, FormInterface $form, array $options)
{
$view->vars['translation_locales'] = $this->definedLocalesCodes;
$translationForms = [];
foreach ($view as $locale => $child) {
foreach ($child as $key => $childForm) {
if (!isset($forms[$key])) {
$translationForms[$key] = [];
}
$translationForms[$key][$locale] = $childForm;
}
}
$view->vars['translation_forms'] = $translationForms;
return;
}
public function getExtendedTypes(): iterable
{
return [ResourceTranslationsType::class];
}
}
|
Add 0.33 to the vertices to prevent misalignment | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
import numpy as np
from vispy.visuals.line.arrow import ARROW_TYPES
from vispy.scene import visuals, transforms
from vispy.testing import (requires_application, TestingCanvas,
run_tests_if_main, raises)
from vispy.testing.image_tester import assert_image_approved
@requires_application()
def test_line_draw():
"""Test drawing arrows without transforms"""
vertices = np.array([
[25, 25],
[25, 75],
[50, 25],
[50, 75],
[75, 25],
[75, 75]
]).astype('f32')
vertices += 0.33
arrows = np.array([
vertices[:2],
vertices[3:1:-1],
vertices[4:],
vertices[-1:-3:-1]
]).reshape((4, 4))
with TestingCanvas() as c:
for arrow_type in ARROW_TYPES:
arrow = visuals.Arrow(pos=vertices, arrow_type=arrow_type,
arrows=arrows, arrow_size=10, color='red',
connect="segments", parent=c.scene)
assert_image_approved(c.render(), 'visuals/arrow_type_%s.png' %
arrow_type)
arrow.parent = None
run_tests_if_main()
| # -*- coding: utf-8 -*-
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
import numpy as np
from vispy.visuals.line.arrow import ARROW_TYPES
from vispy.scene import visuals, transforms
from vispy.testing import (requires_application, TestingCanvas,
run_tests_if_main, raises)
from vispy.testing.image_tester import assert_image_approved
@requires_application()
def test_line_draw():
"""Test drawing arrows without transforms"""
vertices = np.array([
[25, 25],
[25, 75],
[50, 25],
[50, 75],
[75, 25],
[75, 75]
]).astype('f32')
arrows = np.array([
vertices[:2],
vertices[3:1:-1],
vertices[4:],
vertices[-1:-3:-1]
]).reshape((4, 4))
with TestingCanvas() as c:
for arrow_type in ARROW_TYPES:
arrow = visuals.Arrow(pos=vertices, arrow_type=arrow_type,
arrows=arrows, arrow_size=10, color='red',
connect="segments", parent=c.scene)
assert_image_approved(c.render(), 'visuals/arrow_type_%s.png' %
arrow_type)
arrow.parent = None
run_tests_if_main()
|
Add pytest-cov and fix change requirements to >= | from codecs import open as codecs_open
from setuptools import setup, find_packages
with codecs_open('README.md', encoding='utf-8') as f:
long_description = f.read()
setup(name='gypsy',
version='0.0.1',
description=u"Controlling Gypsy modules, and outputs",
long_description=long_description,
classifiers=[],
keywords='',
author=u"Julianno Sambatti",
author_email='[email protected]',
url='',
license='',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
zip_safe=False,
include_package_data=True,
package_data={
'gypsy': ['data/*'],
},
install_requires=[
'click>=6.6',
'pandas>=0.18.1',
'scipy>=0.17.1',
],
extras_require={
'test': ['pytest>=2.9.1'],
'dev': ['pytest>=2.9.1', 'sphinx>=1.4.1',
'pylint>=1.5.4', 'git-pylint-commit-hook>=2.1.1',
'pytest-cov>=2.3.1']
},
entry_points="""
[console_scripts]
gypsy=gypsy.scripts.cli:cli
"""
)
| from codecs import open as codecs_open
from setuptools import setup, find_packages
with codecs_open('README.md', encoding='utf-8') as f:
long_description = f.read()
setup(name='gypsy',
version='0.0.1',
description=u"Controlling Gypsy modules, and outputs",
long_description=long_description,
classifiers=[],
keywords='',
author=u"Julianno Sambatti",
author_email='[email protected]',
url='',
license='',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
zip_safe=False,
include_package_data=True,
package_data={
'gypsy': ['data/*'],
},
install_requires=[
'click==6.6',
'pandas==0.18.1',
'scipy==0.17.1',
],
extras_require={
'test': ['pytest==2.9.1'],
'dev': ['pytest==2.9.1', 'sphinx==1.4.1',
'pylint==1.5.4', 'git-pylint-commit-hook==2.1.1']
},
entry_points="""
[console_scripts]
gypsy=gypsy.scripts.cli:cli
"""
)
|
Subsets and Splits