text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Use of a more specific constructor, to avoid too easy conversions | //-----------------------------------------------------------------------//
// //
// P i x e l P o i n t //
// //
// Copyright (C) Herve Bitteur 2000-2006. All rights reserved. //
// This software is released under the terms of the GNU General Public //
// License. Please contact the author at [email protected] //
// to report bugs & suggestions. //
//-----------------------------------------------------------------------//
package omr.sheet;
import java.awt.*;
/**
* Class <code>PixelPoint</code> is a simple Point that is meant to
* represent a point in a deskewed page, with its coordinates specified in
* pixels, so the name.
*
* <p> This specialization is used to take benefit of compiler checks, to
* prevent the use of points with incorrect meaning or units. </p>
*
* @author Hervé Bitteur
* @version $Id$
*/
public class PixelPoint
extends Point
{
//------------//
// PixelPoint //
//------------//
public PixelPoint ()
{
}
//------------//
// PixelPoint //
//------------//
public PixelPoint (int x,
int y)
{
super(x, y);
}
}
| //-----------------------------------------------------------------------//
// //
// P i x e l P o i n t //
// //
// Copyright (C) Herve Bitteur 2000-2006. All rights reserved. //
// This software is released under the terms of the GNU General Public //
// License. Please contact the author at [email protected] //
// to report bugs & suggestions. //
//-----------------------------------------------------------------------//
package omr.sheet;
import java.awt.*;
/**
* Class <code>PixelPoint</code> is a simple Point that is meant to
* represent a point in a deskewed page, with its coordinates specified in
* pixels, so the name.
*
* <p> This specialization is used to take benefit of compiler checks, to
* prevent the use of points with incorrect meaning or units. </p>
*
* @author Hervé Bitteur
* @version $Id$
*/
public class PixelPoint
extends Point
{
//------------//
// PixelPoint //
//------------//
public PixelPoint ()
{
}
//------------//
// PixelPoint //
//------------//
public PixelPoint (Point point)
{
super(point);
}
}
|
Apply PHP CS Fixer changes | <?php
namespace Telegram\Bot\Tests\Traits;
use Illuminate\Support\Collection;
use Telegram\Bot\Commands\Command;
trait CommandGenerator
{
/**
* @param int $numberRequired
*
* @return Collection
*/
private function commandGenerator($numberRequired)
{
$range = range(1, $numberRequired, 1);
return collect($range)
->map(function (int $instanceNumber) {
return new class($instanceNumber) extends Command {
private $instanceNumber;
public function __construct(int $instanceNumber)
{
$this->instanceNumber = $instanceNumber;
}
public function getName(): string
{
return "MockCommand$this->instanceNumber";
}
public function getAliases(): array
{
return ["MockAlias$this->instanceNumber"];
}
public function handle()
{
}
};
});
}
}
| <?php
namespace Telegram\Bot\Tests\Traits;
use Illuminate\Support\Collection;
use Telegram\Bot\Commands\Command;
trait CommandGenerator
{
/**
* @param int $numberRequired
*
* @return Collection
*/
private function commandGenerator($numberRequired)
{
$range = range(1, $numberRequired, 1);
return collect($range)
->map(function (int $instanceNumber) {
return new class ($instanceNumber) extends Command {
private $instanceNumber;
public function __construct(int $instanceNumber)
{
$this->instanceNumber = $instanceNumber;
}
public function getName(): string
{
return "MockCommand$this->instanceNumber";
}
public function getAliases(): array
{
return ["MockAlias$this->instanceNumber"];
}
public function handle()
{
}
};
});
}
}
|
Add test domain that has a CNAME | <?php
namespace Amp\Dns\Test;
use Amp\Dns;
use Amp\Dns\Record;
use Amp\Loop;
use Amp\PHPUnit\TestCase;
class IntegrationTest extends TestCase {
/**
* @param string $hostname
* @group internet
* @dataProvider provideHostnames
*/
public function testResolve($hostname) {
Loop::run(function () use ($hostname) {
$result = yield Dns\resolve($hostname);
/** @var Record $record */
$record = $result[0];
$inAddr = @\inet_pton($record->getValue());
$this->assertNotFalse(
$inAddr,
"Server name $hostname did not resolve to a valid IP address"
);
});
}
public function testPtrLookup() {
Loop::run(function () {
$result = yield Dns\query("8.8.4.4", Record::PTR);
/** @var Record $record */
$record = $result[0];
$this->assertSame("google-public-dns-b.google.com", $record->getValue());
$this->assertSame(Record::PTR, $record->getType());
});
}
public function provideHostnames() {
return [
["google.com"],
["github.com"],
["stackoverflow.com"],
["blog.kelunik.com"], /* that's a CNAME to GH pages */
["localhost"],
["192.168.0.1"],
["::1"],
];
}
public function provideServers() {
return [
["8.8.8.8"],
["8.8.8.8:53"],
];
}
}
| <?php
namespace Amp\Dns\Test;
use Amp\Dns;
use Amp\Dns\Record;
use Amp\Loop;
use Amp\PHPUnit\TestCase;
class IntegrationTest extends TestCase {
/**
* @param string $hostname
* @group internet
* @dataProvider provideHostnames
*/
public function testResolve($hostname) {
Loop::run(function () use ($hostname) {
$result = yield Dns\resolve($hostname);
/** @var Record $record */
$record = $result[0];
$inAddr = @\inet_pton($record->getValue());
$this->assertNotFalse(
$inAddr,
"Server name $hostname did not resolve to a valid IP address"
);
});
}
public function testPtrLookup() {
Loop::run(function () {
$result = yield Dns\query("8.8.4.4", Record::PTR);
/** @var Record $record */
$record = $result[0];
$this->assertSame("google-public-dns-b.google.com", $record->getValue());
$this->assertSame(Record::PTR, $record->getType());
});
}
public function provideHostnames() {
return [
["google.com"],
["github.com"],
["stackoverflow.com"],
["localhost"],
["192.168.0.1"],
["::1"],
];
}
public function provideServers() {
return [
["8.8.8.8"],
["8.8.8.8:53"],
];
}
}
|
Add --version CLI opt and __version__ module attr
Change-Id: I8c39a797e79429dd21c5caf093b076a4b1757de0 | import os
import sys
import setuptools
from keystoneclient.openstack.common import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
requires = setup.parse_requirements()
depend_links = setup.parse_dependency_links()
tests_require = setup.parse_requirements(['tools/test-requires'])
setuptools.setup(
name="python-keystoneclient",
version=setup.get_post_version('keystoneclient'),
description="Client library for OpenStack Identity API (Keystone)",
long_description=read('README.rst'),
url='https://github.com/openstack/python-keystoneclient',
license='Apache',
author='Nebula Inc, based on work by Rackspace and Jacob Kaplan-Moss',
author_email='[email protected]',
packages=setuptools.find_packages(exclude=['tests', 'tests.*']),
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Environment :: OpenStack',
'Intended Audience :: Developers',
'Intended Audience :: Information Technology',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
install_requires=requires,
dependency_links=depend_links,
cmdclass=setup.get_cmdclass(),
tests_require=tests_require,
test_suite="nose.collector",
entry_points={
'console_scripts': ['keystone = keystoneclient.shell:main']
},
data_files=[('keystoneclient', ['keystoneclient/versioninfo'])],
)
| import os
import sys
import setuptools
from keystoneclient.openstack.common import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
requires = setup.parse_requirements()
depend_links = setup.parse_dependency_links()
tests_require = setup.parse_requirements(['tools/test-requires'])
setuptools.setup(
name="python-keystoneclient",
version=setup.get_post_version('keystoneclient'),
description="Client library for OpenStack Identity API (Keystone)",
long_description=read('README.rst'),
url='https://github.com/openstack/python-keystoneclient',
license='Apache',
author='Nebula Inc, based on work by Rackspace and Jacob Kaplan-Moss',
author_email='[email protected]',
packages=setuptools.find_packages(exclude=['tests', 'tests.*']),
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Environment :: OpenStack',
'Intended Audience :: Developers',
'Intended Audience :: Information Technology',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
install_requires=requires,
dependency_links=depend_links,
cmdclass=setup.get_cmdclass(),
tests_require=tests_require,
test_suite="nose.collector",
entry_points={
'console_scripts': ['keystone = keystoneclient.shell:main']
}
)
|
Add default kwarg to default probs_hat in Task | from functools import partial
from typing import Callable, List
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
class Task(object):
"""A task for use in an MMTL MetalModel
Args:
name: The name of the task
TODO: replace this with a more fully-featured path through the network
input_module: The input module
head_module: The task head module
data: A list of DataLoaders (instances and labels) to feed through the network.
The list contains [train, dev, test].
scorers: A list of Scorers that return metrics_dict objects.
"""
def __init__(
self,
name: str,
data_loaders: List[DataLoader],
input_module: nn.Module,
head_module: nn.Module,
scorers: List[Callable] = None,
loss_hat_func: Callable = F.cross_entropy,
probs_hat_func: Callable = partial(F.softmax, dim=1),
) -> None:
if len(data_loaders) != 3:
msg = "Arg data_loaders must be a list of length 3 [train, valid, test]"
raise Exception(msg)
self.name = name
self.data_loaders = data_loaders
self.input_module = input_module
self.head_module = head_module
self.scorers = scorers
self.loss_hat_func = loss_hat_func
self.probs_hat_func = probs_hat_func
| from typing import Callable, List
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
class Task(object):
"""A task for use in an MMTL MetalModel
Args:
name: The name of the task
TODO: replace this with a more fully-featured path through the network
input_module: The input module
head_module: The task head module
data: A list of DataLoaders (instances and labels) to feed through the network.
The list contains [train, dev, test].
scorers: A list of Scorers that return metrics_dict objects.
"""
def __init__(
self,
name: str,
data_loaders: List[DataLoader],
input_module: nn.Module,
head_module: nn.Module,
scorers: List[Callable] = None,
loss_hat_func: Callable = F.cross_entropy,
probs_hat_func: Callable = F.softmax,
) -> None:
if len(data_loaders) != 3:
msg = "Arg data_loaders must be a list of length 3 [train, valid, test]"
raise Exception(msg)
self.name = name
self.data_loaders = data_loaders
self.input_module = input_module
self.head_module = head_module
self.scorers = scorers
self.loss_hat_func = loss_hat_func
self.probs_hat_func = probs_hat_func
|
Fix method name in wait() test | <?php declare(strict_types = 1);
namespace Amp\Test;
use Amp;
use Amp\{ Deferred, Failure, Pause, Success };
use Interop\Async\Loop;
class WaitTest extends \PHPUnit_Framework_TestCase {
public function testWaitOnSuccessfulPromise()
{
$value = 1;
$promise = new Success($value);
$result = Amp\wait($promise);
$this->assertSame($value, $result);
}
public function testWaitOnFailedPromise()
{
$exception = new \Exception();
$promise = new Failure($exception);
try {
$result = Amp\wait($promise);
} catch (\Exception $e) {
$this->assertSame($exception, $e);
return;
}
$this->fail('Rejection exception should be thrown from wait().');
}
/**
* @depends testWaitOnSuccessfulPromise
*/
public function testWaitOnPendingPromise()
{
Loop::execute(function () {
$value = 1;
$promise = new Pause(100, $value);
$result = Amp\wait($promise);
$this->assertSame($value, $result);
});
}
/**
* @expectedException \Error
* @expectedExceptionMessage Loop emptied without resolving promise
*/
public function testPromiseWithNoResolutionPathThrowsException()
{
$promise = new Deferred;
$result = Amp\wait($promise->promise());
}
}
| <?php declare(strict_types = 1);
namespace Amp\Test;
use Amp;
use Amp\{ Deferred, Failure, Pause, Success };
use Interop\Async\Loop;
class WaitTest extends \PHPUnit_Framework_TestCase {
public function testWaitOnSuccessfulPromise()
{
$value = 1;
$promise = new Success($value);
$result = Amp\wait($promise);
$this->assertSame($value, $result);
}
public function testWaitOnFailedPromise()
{
$exception = new \Exception();
$promise = new Failure($exception);
try {
$result = Amp\wait($promise);
} catch (\Exception $e) {
$this->assertSame($exception, $e);
return;
}
$this->fail('Rejection exception should be thrown from wait().');
}
/**
* @depends testWaitOnSuccessfulPromise
*/
public function testWaitOnPendingPromise()
{
Loop::execute(function () {
$value = 1;
$promise = new Pause(100, $value);
$result = Amp\wait($promise);
$this->assertSame($value, $result);
});
}
/**
* @expectedException \Error
*/
public function testPromiseWithNoResolutionPathThrowsException()
{
$promise = new Deferred;
$result = Amp\wait($promise->getPromise());
}
}
|
Remove unused imports in game tests | package com.bjorn;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
public class GameTest {
UI mockUI;
Board mockBoard;
Game newGame;
@Before
public void setUp() {
mockUI = Mockito.mock(UI.class);
mockBoard = Mockito.mock(Board.class);
newGame = new Game(mockUI, mockBoard);
newGame.startGame();
}
@Test
public void checkIfWelcomeIsCalled() {
verify(mockUI, times(1)).printWelcome();
}
@Test
public void checkIfPrintBoardIsCalled() {
verify(mockUI, atLeastOnce()).printBoard(mockBoard);
}
@Test
public void checkIfPromptForXCoordinateIsCalled() {
verify(mockUI, atLeastOnce()).promptForXCoordinate();
}
@Test
public void checkIfPromptForYCoordinateIsCalled() {
verify(mockUI, atLeastOnce()).promptForYCoordinate();
}
@Test
public void checkIfGetUserInputIsCalled() {
verify(mockUI, atLeastOnce()).getUserInput();
}
@Test
public void checkIfUpdateBoardStateIsCalled() {
verify(mockBoard, atLeastOnce()).upDateBoardState(0, 0, "H");
}
}
| package com.bjorn;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import javax.xml.bind.annotation.XmlAttribute;
import java.util.HashMap;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
public class GameTest {
UI mockUI;
Board mockBoard;
Game newGame;
@Before
public void setUp() {
mockUI = Mockito.mock(UI.class);
mockBoard = Mockito.mock(Board.class);
newGame = new Game(mockUI, mockBoard);
newGame.startGame();
}
@Test
public void checkIfWelcomeIsCalled() {
verify(mockUI, times(1)).printWelcome();
}
@Test
public void checkIfPrintBoardIsCalled() {
verify(mockUI, atLeastOnce()).printBoard(mockBoard);
}
@Test
public void checkIfPromptForXCoordinateIsCalled() {
verify(mockUI, atLeastOnce()).promptForXCoordinate();
}
@Test
public void checkIfPromptForYCoordinateIsCalled() {
verify(mockUI, atLeastOnce()).promptForYCoordinate();
}
@Test
public void checkIfGetUserInputIsCalled() {
verify(mockUI, atLeastOnce()).getUserInput();
}
@Test
public void checkIfUpdateBoardStateIsCalled() {
verify(mockBoard, atLeastOnce()).upDateBoardState(0, 0, "H");
}
}
|
Use credentials from environment so we can do unit tests. | <?php
namespace Slim\Middleware;
/**
* HTTP Basic Authentication
*
* Provides HTTP Basic Authentication on given routes
*
* @package Slim
* @author Mika Tuupola <[email protected]>
*/
class HttpBasicAuth extends \Slim\Middleware {
public $options;
public function __construct($options = null) {
/* Default options. */
$this->options = array(
"users" => array(),
"path" => "/",
"realm" => "Protected"
);
if ($options) {
$this->options = array_merge($this->options, (array)$options);
}
}
public function call() {
$request = $this->app->request;
$environment = $this->app->environment;
/* If path matches what is given on initialization. */
if (false !== strpos($request->getPath(), $this->options["path"])) {
$user = $environment["PHP_AUTH_USER"];
$pass = $environment["PHP_AUTH_PW"];
/* Check if user and passwords matches. */
if (isset($this->options["users"][$user]) && $this->options["users"][$user] === $pass) {
$this->next->call();
} else {
$this->app->response->status(401);
$this->app->response->header("WWW-Authenticate", sprintf('Basic realm="%s"', $this->options["realm"]));;
return;
}
} else {
$this->next->call();
}
}
}
| <?php
namespace Slim\Middleware;
/**
* HTTP Basic Authentication
*
* Provides HTTP Basic Authentication on given routes
*
* @package Slim
* @author Mika Tuupola <[email protected]>
*/
class HttpBasicAuth extends \Slim\Middleware {
public $options;
public function __construct($options = null) {
/* Default options. */
$this->options = array(
"users" => array(),
"path" => "/",
"realm" => "Protected"
);
if ($options) {
$this->options = array_merge($this->options, (array)$options);
}
}
public function call() {
$request = $this->app->request;
/* If path matches what is given on initialization. */
if (false !== strpos($request->getPath(), $this->options["path"])) {
$user = $request->headers("PHP_AUTH_USER");
$pass = $request->headers("PHP_AUTH_PW");
/* Check if user and passwords matches. */
if (isset($this->options["users"][$user]) && $this->options["users"][$user] === $pass) {
$this->next->call();
} else {
$this->app->response->status(401);
$this->app->response->header("WWW-Authenticate", sprintf('Basic realm="%s"', $this->options["realm"]));;
return;
}
} else {
$this->next->call();
}
}
}
|
Update this command for Django 1.8 | """
Command to load course overviews.
"""
import logging
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from xmodule.modulestore.django import modulestore
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
log = logging.getLogger(__name__)
class Command(BaseCommand):
"""
Example usage:
$ ./manage.py lms generate_course_overview --all --settings=devstack
$ ./manage.py lms generate_course_overview 'edX/DemoX/Demo_Course' --settings=devstack
"""
args = '<course_id course_id ...>'
help = 'Generates and stores course overview for one or more courses.'
def add_arguments(self, parser):
"""
Add arguments to the command parser.
"""
parser.add_argument(
'--all',
action='store_true',
dest='all',
default=False,
help='Generate course overview for all courses.',
)
def handle(self, *args, **options):
if options['all']:
course_keys = [course.id for course in modulestore().get_course_summaries()]
else:
if len(args) < 1:
raise CommandError('At least one course or --all must be specified.')
try:
course_keys = [CourseKey.from_string(arg) for arg in args]
except InvalidKeyError:
raise CommandError('Invalid key specified.')
CourseOverview.get_select_courses(course_keys)
| """
Command to load course overviews.
"""
import logging
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from xmodule.modulestore.django import modulestore
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
log = logging.getLogger(__name__)
class Command(BaseCommand):
"""
Example usage:
$ ./manage.py lms generate_course_overview --all --settings=devstack
$ ./manage.py lms generate_course_overview 'edX/DemoX/Demo_Course' --settings=devstack
"""
args = '<course_id course_id ...>'
help = 'Generates and stores course overview for one or more courses.'
option_list = BaseCommand.option_list + (
make_option('--all',
action='store_true',
default=False,
help='Generate course overview for all courses.'),
)
def handle(self, *args, **options):
if options['all']:
course_keys = [course.id for course in modulestore().get_course_summaries()]
else:
if len(args) < 1:
raise CommandError('At least one course or --all must be specified.')
try:
course_keys = [CourseKey.from_string(arg) for arg in args]
except InvalidKeyError:
raise CommandError('Invalid key specified.')
CourseOverview.get_select_courses(course_keys)
|
Use Kernel::getEnvironment() to keep consistency | <?php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Symfony\Bundle\MonologBundle\MonologBundle(),
new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
new AppBundle\AppBundle(),
);
if (in_array($this->getEnvironment(), array('dev', 'test'), true)) {
$bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle();
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
$bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
$bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
}
return $bundles;
}
public function getRootDir()
{
return __DIR__;
}
public function getCacheDir()
{
return dirname(__DIR__).'/var/cache/'.$this->getEnvironment();
}
public function getLogDir()
{
return dirname(__DIR__).'/var/logs';
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load($this->getRootDir().'/config/config_'.$this->getEnvironment().'.yml');
}
}
| <?php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Symfony\Bundle\MonologBundle\MonologBundle(),
new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
new AppBundle\AppBundle(),
);
if (in_array($this->getEnvironment(), array('dev', 'test'), true)) {
$bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle();
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
$bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
$bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
}
return $bundles;
}
public function getRootDir()
{
return __DIR__;
}
public function getCacheDir()
{
return dirname(__DIR__).'/var/cache/'.$this->environment;
}
public function getLogDir()
{
return dirname(__DIR__).'/var/logs';
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load($this->getRootDir().'/config/config_'.$this->getEnvironment().'.yml');
}
}
|
Check function and branch coverage | module.exports = function(grunt) {
grunt.loadNpmTasks("grunt-mocha-test");
grunt.loadNpmTasks("grunt-mocha-istanbul");
var testOutputLocation = process.env.CIRCLE_TEST_REPORTS || "test_output";
var artifactsLocation = process.env.CIRCLE_ARTIFACTS || "build_artifacts";
grunt.initConfig({
mochaTest: {
test: {
src: ["test/**/*.js"]
},
ci: {
src: ["test/**/*.js"],
options: {
reporter: "xunit",
captureFile: testOutputLocation + "/mocha/results.xml",
quiet: true
}
}
},
mocha_istanbul: {
coverage: {
src: ["test/**/*.js"],
options: {
coverageFolder: artifactsLocation + "/coverage",
check: {
lines: 100,
statements: 100,
branches: 100,
functions: 100
},
reportFormats: ["lcov"]
}
}
}
});
grunt.registerTask("test", ["mochaTest:test", "mocha_istanbul"]);
grunt.registerTask("ci-test", ["mochaTest:ci", "mocha_istanbul"]);
grunt.registerTask("default", "test");
};
| module.exports = function(grunt) {
grunt.loadNpmTasks("grunt-mocha-test");
grunt.loadNpmTasks("grunt-mocha-istanbul");
var testOutputLocation = process.env.CIRCLE_TEST_REPORTS || "test_output";
var artifactsLocation = process.env.CIRCLE_ARTIFACTS || "build_artifacts";
grunt.initConfig({
mochaTest: {
test: {
src: ["test/**/*.js"]
},
ci: {
src: ["test/**/*.js"],
options: {
reporter: "xunit",
captureFile: testOutputLocation + "/mocha/results.xml",
quiet: true
}
}
},
mocha_istanbul: {
coverage: {
src: ["test/**/*.js"],
options: {
coverageFolder: artifactsLocation + "/coverage",
check: {
lines: 100,
statements: 100
},
reportFormats: ["lcov"]
}
}
}
});
grunt.registerTask("test", ["mochaTest:test", "mocha_istanbul"]);
grunt.registerTask("ci-test", ["mochaTest:ci", "mocha_istanbul"]);
grunt.registerTask("default", "test");
};
|
Fix target selector for imported projects | /*
* Copyright 2014 BlackBerry Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var TargetSelectorView,
targetSelectorTemplate;
TargetSelectorView = Backbone.View.extend({
initialize: function () {
// Find the template and save it
$.get("pages/targetSelector.html", function (data) {
targetSelectorTemplate = data;
});
},
render: function () {
// Use the template to create the html to display
var view = this,
buildSettings = view.model.get("buildSettings"),
showDevices = !buildSettings || typeof buildSettings.device === "undefined" || buildSettings.device,
template;
this.model.targetFilter(showDevices, function (filteredTargets) {
template = _.template(targetSelectorTemplate, {
targetNameList: Object.keys(filteredTargets)
});
// Put the new html inside of the assigned element
view.$el.html(template);
});
},
events: {
},
display: function (model) {
this.model = model;
this.render();
}
});
module.exports = TargetSelectorView;
| /*
* Copyright 2014 BlackBerry Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var TargetSelectorView,
targetSelectorTemplate;
TargetSelectorView = Backbone.View.extend({
initialize: function () {
// Find the template and save it
$.get("pages/targetSelector.html", function (data) {
targetSelectorTemplate = data;
});
},
render: function () {
// Use the template to create the html to display
var view = this,
showDevices = view.model.get("buildSettings").device,
template;
if (typeof showDevices === "undefined") {
showDevices = true;
}
this.model.targetFilter(showDevices, function (filteredTargets) {
template = _.template(targetSelectorTemplate, {
targetNameList: Object.keys(filteredTargets)
});
// Put the new html inside of the assigned element
view.$el.html(template);
});
},
events: {
},
display: function (model) {
this.model = model;
this.render();
}
});
module.exports = TargetSelectorView;
|
Convert map objects to lists | from __future__ import absolute_import, print_function, unicode_literals
import regex as re
import unicodecsv as csv
import os.path
import pkg_resources
class XSampa(object):
def __init__(self, delimiter=' '):
self.delimiter = delimiter
self.xs_regex, self.xs2ipa = self.read_xsampa_table()
def read_xsampa_table(self):
filename = os.path.join('data', 'ipa-xsampa.csv')
filename = pkg_resources.resource_filename(__name__, filename)
with open(filename, 'rb') as f:
xs2ipa = {x[1]: x[0] for x in csv.reader(f, encoding='utf-8')}
xs = sorted(xs2ipa.keys(), key=len, reverse=True)
xs_regex = re.compile('|'.join(list(map(re.escape, xs))))
return xs_regex, xs2ipa
def convert(self, xsampa):
def seg2ipa(seg):
ipa = []
while seg:
match = self.xs_regex.match(seg)
if match:
ipa.append(self.xs2ipa[match.group(0)])
seg = seg[len(match.group(0)):]
else:
seg = seg[1:]
return ''.join(ipa)
ipasegs = list(map(seg2ipa, xsampa.split(self.delimiter)))
return ''.join(ipasegs)
| from __future__ import absolute_import, print_function, unicode_literals
import regex as re
import unicodecsv as csv
import os.path
import pkg_resources
class XSampa(object):
def __init__(self, delimiter=' '):
self.delimiter = delimiter
self.xs_regex, self.xs2ipa = self.read_xsampa_table()
def read_xsampa_table(self):
filename = os.path.join('data', 'ipa-xsampa.csv')
filename = pkg_resources.resource_filename(__name__, filename)
with open(filename, 'rb') as f:
xs2ipa = {x[1]: x[0] for x in csv.reader(f, encoding='utf-8')}
xs = sorted(xs2ipa.keys(), key=len, reverse=True)
xs_regex = re.compile('|'.join(map(re.escape, xs)))
return xs_regex, xs2ipa
def convert(self, xsampa):
def seg2ipa(seg):
ipa = []
while seg:
match = self.xs_regex.match(seg)
if match:
ipa.append(self.xs2ipa[match.group(0)])
seg = seg[len(match.group(0)):]
else:
seg = seg[1:]
return ''.join(ipa)
ipasegs = map(seg2ipa, xsampa.split(self.delimiter))
return ''.join(ipasegs)
|
Fix topRounded method to draw the correct shape | //@author A0116538A
package bakatxt.gui;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Path2D;
import bakatxt.core.Task;
/**
* This class dictates the color and shape of the box which the task will be put in.
* This box is specifically for a top most box.
*
*/
class FirstTaskBox extends TaskBox {
public FirstTaskBox(Task task, Color backgroundColor) {
super(task, backgroundColor);
}
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(getBackground());
g2d.setRenderingHints(UIHelper.antiAlias());
g2d.fill(new TopRounded(getWidth(), getHeight()));
g2d.dispose();
super.paintComponent(g);
}
class TopRounded extends Path2D.Double {
public TopRounded(double width, double height) {
moveTo(0, height);
lineTo(0, UIHelper.WINDOW_ROUNDNESS);
curveTo(0, 0, 0, 0, UIHelper.WINDOW_ROUNDNESS, 0);
lineTo(width - UIHelper.WINDOW_ROUNDNESS, 0);
curveTo(width, 0, width, 0, width, UIHelper.WINDOW_ROUNDNESS);
lineTo(width, height);
lineTo(0, height);
closePath();
}
}
}
| //@author A0116538A
package bakatxt.gui;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Path2D;
import bakatxt.core.Task;
/**
* This class dictates the color and shape of the box which the task will be put in.
* This box is specifically for a top most box.
*
*/
class FirstTaskBox extends TaskBox {
public FirstTaskBox(Task task, Color backgroundColor) {
super(task, backgroundColor);
}
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(getBackground());
g2d.setRenderingHints(UIHelper.antiAlias());
g2d.fill(new TopRounded(getWidth(), getHeight()));
g2d.dispose();
super.paintComponent(g);
}
// TODO fix topRounded method
class TopRounded extends Path2D.Double {
public TopRounded(double width, double height) {
moveTo(0, 0);
lineTo(width, 0);
lineTo(width, height - UIHelper.WINDOW_ROUNDNESS);
curveTo(width, height, width, height, width - UIHelper.WINDOW_ROUNDNESS, height);
lineTo(UIHelper.WINDOW_ROUNDNESS, height);
curveTo(0, height, 0, height, 0, height - UIHelper.WINDOW_ROUNDNESS);
lineTo(0, 0);
closePath();
}
}
}
|
Fix issue found by Scrutinizer. | <?php
declare(strict_types=1);
use Webmozart\PathUtil\Path;
/**
* Helper class for text resources.
*/
class TextResourceHelper implements ResourceHelper, WebPackerInterface
{
//--------------------------------------------------------------------------------------------------------------------
use WebPackerTrait;
//--------------------------------------------------------------------------------------------------------------------
/**
* PhpSourceHelperJs constructor.
*
* @param \WebPackerInterface $parent The parent object.
*/
public function __construct(\WebPackerInterface $parent)
{
$this->initWebPackerTrait($parent);
}
//--------------------------------------------------------------------------------------------------------------------
/**
* @inheritDoc
*/
public static function deriveType(string $content): bool
{
unset($content);
return true;
}
//--------------------------------------------------------------------------------------------------------------------
/**
* @inheritDoc
*/
public static function mustCompress(): bool
{
return false;
}
//--------------------------------------------------------------------------------------------------------------------
/**
* @inheritDoc
*/
public function analyze(array $resource): void
{
unset($resource);
}
//--------------------------------------------------------------------------------------------------------------------
/**
* @inheritDoc
*/
public function optimize(array $resource, array $resources): ?string
{
unset($resources);
// Nothing to do for text files.
return $resource['rsr_content'];
}
//--------------------------------------------------------------------------------------------------------------------
/**
* @inheritDoc
*/
public function uriOptimizedPath(array $resource): ?string
{
$md5 = md5($resource['rsr_content_optimized'] ?? '');
$extension = Path::getExtension($resource['rsr_path']);
return sprintf('/%s/%s.%s', 'css', $md5, $extension);
}
//--------------------------------------------------------------------------------------------------------------------
}
//----------------------------------------------------------------------------------------------------------------------
| <?php
declare(strict_types=1);
use Webmozart\PathUtil\Path;
/**
* Helper class for text resources.
*/
class TextResourceHelper implements ResourceHelper, WebPackerInterface
{
//--------------------------------------------------------------------------------------------------------------------
use WebPackerTrait;
//--------------------------------------------------------------------------------------------------------------------
/**
* PhpSourceHelperJs constructor.
*
* @param \WebPackerInterface $parent The parent object.
*/
public function __construct(\WebPackerInterface $parent)
{
$this->initWebPackerTrait($parent);
}
//--------------------------------------------------------------------------------------------------------------------
/**
* @inheritDoc
*/
public static function deriveType(string $content): bool
{
unset($content);
return true;
}
//--------------------------------------------------------------------------------------------------------------------
/**
* @inheritDoc
*/
public static function mustCompress(): bool
{
return false;
}
//--------------------------------------------------------------------------------------------------------------------
/**
* @inheritDoc
*/
public function analyze(array $resource): void
{
unset($content);
}
//--------------------------------------------------------------------------------------------------------------------
/**
* @inheritDoc
*/
public function optimize(array $resource, array $resources): ?string
{
unset($resources);
// Nothing to do for text files.
return $resource['rsr_content'];
}
//--------------------------------------------------------------------------------------------------------------------
/**
* @inheritDoc
*/
public function uriOptimizedPath(array $resource): ?string
{
$md5 = md5($resource['rsr_content_optimized'] ?? '');
$extension = Path::getExtension($resource['rsr_path']);
return sprintf('/%s/%s.%s', 'css', $md5, $extension);
}
//--------------------------------------------------------------------------------------------------------------------
}
//----------------------------------------------------------------------------------------------------------------------
|
Remove the blind addition of prefech_related() to all Correlation querysets. | # -*- coding: utf-8 -*-
from datetime import date
from django.contrib.contenttypes.models import ContentType
from django.db import models
class CorrelationManager(models.Manager):
def update_or_create(self, instance, timestamp, attribute):
# Membership is a special case. Since most groups are static
# (or non-generational), the date the group is formed is the same as
# the date its members joined. So if those two values are equal, stop
# the process.
if not timestamp or (instance._meta.model_name == 'membership'
and instance.started == instance.group.started):
return
ctype = ContentType.objects.get_for_model(instance.sender)
defaults = {
'timestamp': timestamp,
'julian': timestamp.timetuple().tm_yday,
'year': timestamp.year,
'month': timestamp.month,
'day': timestamp.day,
}
correlation, created = self.get_or_create(
content_type=ctype,
object_id=instance._get_pk_val(),
identifier=instance._meta.model_name,
date_field=attribute,
defaults=defaults
)
for key, value in defaults.iteritems():
setattr(correlation, key, value)
correlation.save()
return
def get_query_set(self):
qs = super(CorrelationManager, self).get_query_set()
return qs #.prefetch_related('content_object')
def today(self):
qs = self.get_query_set()
return qs.filter(julian=date.today().timetuple().tm_yday)
| # -*- coding: utf-8 -*-
from datetime import date
from django.contrib.contenttypes.models import ContentType
from django.db import models
class CorrelationManager(models.Manager):
def update_or_create(self, instance, timestamp, attribute):
# Membership is a special case. Since most groups are static
# (or non-generational), the date the group is formed is the same as
# the date its members joined. So if those two values are equal, stop
# the process.
if not timestamp or (instance._meta.model_name == 'membership'
and instance.started == instance.group.started):
return
ctype = ContentType.objects.get_for_model(instance.sender)
defaults = {
'timestamp': timestamp,
'julian': timestamp.timetuple().tm_yday,
'year': timestamp.year,
'month': timestamp.month,
'day': timestamp.day,
}
correlation, created = self.get_or_create(
content_type=ctype,
object_id=instance._get_pk_val(),
identifier=instance._meta.model_name,
date_field=attribute,
defaults=defaults
)
for key, value in defaults.iteritems():
setattr(correlation, key, value)
correlation.save()
return
def get_query_set(self):
qs = super(CorrelationManager, self).get_query_set()
return qs.prefetch_related('content_object')
def today(self):
qs = self.get_query_set()
return qs.filter(julian=date.today().timetuple().tm_yday)
|
Add school age group template helper. | Template.registrantDetails.helpers({
'registrationTypeOptions': function () {
// registration types used on the registration form
return [
{label: "Commuter", value: "commuter"},
{label: "Daily", value: "daily"},
{label: "Full Week", value: "weekly"}
];
},
/*
Determine if registrant is school aged
by checking age group
return true if age group is child, youth, or teen
*/
'schoolAgeGroup': function () {
var ageGroup = ageGroupVar.get();
// look at the value of age group
switch (ageGroup) {
// if child, youth or teen
// return true
case 'child':
return true;
break;
case 'youth':
return true;
break;
case 'teen':
return true;
break;
default:
return false;
break;
};
}
});
Template.registrantDetails.events({
'change #registration_type': function () {
// clean up form values for accommodations and days
// to make sure no erroneous values remain
resetReactiveVars();
// Clear the accommodations selection
$("#accommodations").val("");
// Clear all day checkboxes
$('input[name="days"]').each(function() {
// make sure day is not checked
this.checked = false;
});
},
'change #age': function () {
// Get the value of the age field
var ageValue = $('#age').val();
// Calculate the age group based on the age value
var ageGroup = calculateAgeGroup(ageValue);
// Reset the accommodations selection
// as accommodations depend on age group
$("#accommodations").val("");
// Set the age group reactive variable
// for price calculations
ageGroupVar.set(ageGroup);
}
});
| Template.registrantDetails.helpers({
'registrationTypeOptions': function () {
// registration types used on the registration form
return [
{label: "Commuter", value: "commuter"},
{label: "Daily", value: "daily"},
{label: "Full Week", value: "weekly"}
];
}
});
Template.registrantDetails.events({
'change #registration_type': function () {
// clean up form values for accommodations and days
// to make sure no erroneous values remain
resetReactiveVars();
// Clear the accommodations selection
$("#accommodations").val("");
// Clear all day checkboxes
$('input[name="days"]').each(function() {
// make sure day is not checked
this.checked = false;
});
},
'change #age': function () {
// Get the value of the age field
var ageValue = $('#age').val();
// Calculate the age group based on the age value
var ageGroup = calculateAgeGroup(ageValue);
// Reset the accommodations selection
// as accommodations depend on age group
$("#accommodations").val("");
// Set the age group reactive variable
// for price calculations
ageGroupVar.set(ageGroup);
}
});
|
Make sure encoding does not get lost | /**
* @module readcache
*/
var fs = require('fs');
var cache = {};
/**
* Reads a text file and stores it in the cache.
*
* @param {string} path - Path to the file you want to read.
* @param {object} [options] - Optional options object, passed to fs.readFile.
* @param {string} [options.encoding=utf8] - The expected string encoding, will default to `utf8`.
* @param {string} [options.flag] - The flag, will default to fs.readFile's
* @param {function} [callback] - A callback function with signature `function (err, data, stats)`
*/
module.exports = function (path, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options = options || {};
options.encoding = options.encoding || 'utf8';
callback = callback || function () {};
fs.stat(path, function (err, stats) {
if (cache[path] && cache[path].since >= stats.mtime.getTime()) {
return callback(null, cache[path].data, { hit: true, since: cache[path].since });
}
fs.readFile(path, options, function (err, data) {
if (err) {
return callback(err);
}
var now = new Date().getTime();
cache[path] = {
data: data,
since: now
};
callback(null, data, { hit: false, since: now });
});
});
};
| /**
* @module readcache
*/
var fs = require('fs');
var cache = {};
/**
* Reads a text file and stores it in the cache.
*
* @param {string} path - Path to the file you want to read.
* @param {object} [options] - Optional options object, passed to fs.readFile.
* @param {string} [options.encoding=utf8] - The expected string encoding, will default to `utf8`.
* @param {string} [options.flag] - The flag, will default to fs.readFile's
* @param {function} [callback] - A callback function with signature `function (err, data, stats)`
*/
module.exports = function (path, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {
encoding: 'utf8'
};
}
options = options || {};
callback = callback || function () {};
fs.stat(path, function (err, stats) {
if (cache[path] && cache[path].since >= stats.mtime.getTime()) {
return callback(null, cache[path].data, { hit: true, since: cache[path].since });
}
fs.readFile(path, options, function (err, data) {
if (err) {
return callback(err);
}
var now = new Date().getTime();
cache[path] = {
data: data,
since: now
};
callback(null, data, { hit: false, since: now });
});
});
};
|
Fix import for new Flask-SQlAlchemy (no longer in flaskext) | """
# # #### ##### # # ##### # # # #
# # # # # ## ## # # # ## # #
### #### #### # # # # # # # # #####
# # # # # # # # ## # # #
# # # ##### # # # # # # # #
Kremlin Magical Everything System
Glasnost Image Board and Boredom Inhibitor
"""
from flask import Flask
from flaskext.uploads import configure_uploads, UploadSet, IMAGES
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
# Load default configuration values, override with whatever is specified
# in configuration file. This is, I think, the sanest approach.
app.config.from_object('kremlin.config_defaults')
app.config.from_envvar('KREMLIN_CONFIGURATION')
# Set database from configuration values
app.config['SQLALCHEMY_DATABASE_URI'] = app.config['DATABASE_URI']
db = SQLAlchemy(app)
uploaded_images = UploadSet("images", IMAGES)
# Create upload set
# and configure like a motherfucker.
uploaded_images = UploadSet("images", IMAGES)
configure_uploads(app, uploaded_images)
# Import relevant modules
# this is done last to avoid touchy situations
import kremlin.dbmodel
import kremlin.core
import kremlin.forms
# Create all database tables
db.create_all()
| """
# # #### ##### # # ##### # # # #
# # # # # ## ## # # # ## # #
### #### #### # # # # # # # # #####
# # # # # # # # ## # # #
# # # ##### # # # # # # # #
Kremlin Magical Everything System
Glasnost Image Board and Boredom Inhibitor
"""
from flask import Flask
from flaskext.sqlalchemy import SQLAlchemy
from flaskext.uploads import configure_uploads, UploadSet, IMAGES
app = Flask(__name__)
# Load default configuration values, override with whatever is specified
# in configuration file. This is, I think, the sanest approach.
app.config.from_object('kremlin.config_defaults')
app.config.from_envvar('KREMLIN_CONFIGURATION')
# Set database from configuration values
app.config['SQLALCHEMY_DATABASE_URI'] = app.config['DATABASE_URI']
db = SQLAlchemy(app)
uploaded_images = UploadSet("images", IMAGES)
# Create upload set
# and configure like a motherfucker.
uploaded_images = UploadSet("images", IMAGES)
configure_uploads(app, uploaded_images)
# Import relevant modules
# this is done last to avoid touchy situations
import kremlin.dbmodel
import kremlin.core
import kremlin.forms
# Create all database tables
db.create_all()
|
Fix package data so that VERSION file actually gets installed | from setuptools import setup, find_packages
import sys, os
desc_lines = open('README', 'r').readlines()
PACKAGE = 'mtconvert'
VERSION = open(os.path.join(os.path.dirname(os.path.realpath(__file__)),'oldowan', PACKAGE, 'VERSION')).read().strip()
setup(name='oldowan.%s' % PACKAGE,
version=VERSION,
description=desc_lines[0],
long_description=''.join(desc_lines[2:]),
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Topic :: Scientific/Engineering :: Bio-Informatics"
],
keywords='bioinformatics',
author='Ryan Raaum',
author_email='[email protected]',
url='http://www.raaum.org',
license='MIT',
platforms = ['Any'],
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
install_requires=[
"oldowan.polymorphism >= 1.0.0",
"oldowan.mtdna >= 1.0.0"
],
namespace_packages = ['oldowan'],
data_files=[("oldowan/%s" % PACKAGE, ["oldowan/%s/VERSION" % PACKAGE])],
zip_safe=False,
test_suite = 'nose.collector',
)
| from setuptools import setup, find_packages
import sys, os
desc_lines = open('README', 'r').readlines()
PACKAGE = 'mtconvert'
VERSION = open(os.path.join(os.path.dirname(os.path.realpath(__file__)),'oldowan', PACKAGE, 'VERSION')).read().strip()
setup(name='oldowan.%s' % PACKAGE,
version=VERSION,
description=desc_lines[0],
long_description=''.join(desc_lines[2:]),
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Topic :: Scientific/Engineering :: Bio-Informatics"
],
keywords='bioinformatics',
author='Ryan Raaum',
author_email='[email protected]',
url='http://www.raaum.org',
license='MIT',
platforms = ['Any'],
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=False,
install_requires=[
"oldowan.polymorphism >= 1.0.0",
"oldowan.mtdna >= 1.0.0"
],
namespace_packages = ['oldowan'],
data_files=[("oldowan/%s" % PACKAGE, ["oldowan/%s/VERSION" % PACKAGE])],
zip_safe=False,
test_suite = 'nose.collector',
)
|
Set for zero or one slash | from django.conf import settings
from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
from contact.views import ChipyContactView
admin.autodiscover()
urlpatterns = patterns("",
url(r'', include('main.urls')),
url(r'', include('social_auth.urls')),
url(r'^login/{0,1}$', direct_to_template, {
'template': 'login.html'
}),
(r'^grappelli/', include('grappelli.urls')),
url(r'^meetings/', include('meetings.urls')),
url(r'^profiles/', include('profiles.urls', namespace="profiles")),
url(r'^admin/', include(admin.site.urls)),
url(r'^about/', include('about.urls')),
url(r'^logout', 'django.contrib.auth.views.logout',
{'next_page': '/'}),
url(r'^contact/', ChipyContactView.as_view(), name="contact"),
url(r'^tinymce/', include('tinymce.urls')),
url(r'^pages/', include('django.contrib.flatpages.urls')),
)
if settings.SERVE_MEDIA:
urlpatterns += patterns("",
url(r'^site_media/media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
)
urlpatterns += staticfiles_urlpatterns()
| from django.conf import settings
from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
from contact.views import ChipyContactView
admin.autodiscover()
urlpatterns = patterns("",
url(r'', include('main.urls')),
url(r'', include('social_auth.urls')),
url(r'^login', direct_to_template, {
'template': 'login.html'
}),
(r'^grappelli/', include('grappelli.urls')),
url(r'^meetings/', include('meetings.urls')),
url(r'^profiles/', include('profiles.urls', namespace="profiles")),
url(r'^admin/', include(admin.site.urls)),
url(r'^about/', include('about.urls')),
url(r'^logout', 'django.contrib.auth.views.logout',
{'next_page': '/'}),
url(r'^contact/', ChipyContactView.as_view(), name="contact"),
url(r'^tinymce/', include('tinymce.urls')),
url(r'^pages/', include('django.contrib.flatpages.urls')),
)
if settings.SERVE_MEDIA:
urlpatterns += patterns("",
url(r'^site_media/media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
)
urlpatterns += staticfiles_urlpatterns()
|
Check empty image + missing alt attribute. | <li class="event-list-item">
<a class="event-list-item-link" href="{{ $event->uri() }}">
<div class="event-list-item-image-wrapper">
@empty (!$event->image)
<img class="event-list-item-image" src="{{ $event->present()->image(540, 400) }}" width="{{ $event->image->width }}" height="{{ $event->image->height }}" alt="{{ $event->image->alt_attribute }}">
@endempty
</div>
<div class="event-list-item-info">
<div class="event-list-item-date">{{ $event->present()->dateFromTo }}</div>
<div class="event-list-item-title">{{ $event->title }}</div>
<div class="event-list-item-location">
<span class="event-list-item-venue">{{ $event->venue }}</span>
<div class="event-list-item-address">{!! nl2br($event->address) !!}</div>
</div>
@empty(!$event->summary)
<div class="event-list-item-summary">{{ $event->summary }}</div>
@endempty
@empty(!$event->url)
<div class="event-list-item-url"><a href="{{ $event->url }}" target="_blank" rel="noopener noreferrer">{{ parse_url($event->url, PHP_URL_HOST) }}</a></div>
@endempty
</div>
</a>
</li>
| <li class="event-list-item">
<a class="event-list-item-link" href="{{ $event->uri() }}">
<div class="event-list-item-image-wrapper">
<img class="event-list-item-image" src="{{ $event->present()->image(540, 400) }}" width="{{ $event->image->width }}" height="{{ $event->image->height }}" alt="">
</div>
<div class="event-list-item-info">
<div class="event-list-item-date">{{ $event->present()->dateFromTo }}</div>
<div class="event-list-item-title">{{ $event->title }}</div>
<div class="event-list-item-location">
<span class="event-list-item-venue">{{ $event->venue }}</span>
<div class="event-list-item-address">{!! nl2br($event->address) !!}</div>
</div>
@empty(!$event->summary)
<div class="event-list-item-summary">{{ $event->summary }}</div>
@endempty
@empty(!$event->url)
<div class="event-list-item-url"><a href="{{ $event->url }}" target="_blank" rel="noopener noreferrer">{{ parse_url($event->url, PHP_URL_HOST) }}</a></div>
@endempty
</div>
</a>
</li>
|
Fix "Unused method, property, variable or parameter " | <?php
namespace Wanjee\Shuwee\AdminBundle\Menu;
use Knp\Menu\FactoryInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Wanjee\Shuwee\AdminBundle\Event\ConfigureMenuEvent;
/**
* Class Builder
* @package Wanjee\Shuwee\AdminBundle\Menu
*/
class Builder
{
/**
* @var \Knp\Menu\FactoryInterface
*/
private $factory;
/**
* @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
*/
private $dispatcher;
/**
* @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $dispatcher
* @param \Knp\Menu\FactoryInterface $factory
*/
public function __construct(FactoryInterface $factory, EventDispatcherInterface $dispatcher)
{
$this->factory = $factory;
$this->dispatcher = $dispatcher;
}
/**
* Build main menu.
*
* Let any bundle add items to this menu by subscribing to ConfigureMenuEvent::CONFIGURE
* @see ConfigureMenuContentListener for example
*
* @param array $options
* @return \Knp\Menu\ItemInterface
*/
public function sideMenu()
{
$menu = $this->factory->createItem('root');
$this->dispatcher->dispatch(
ConfigureMenuEvent::CONFIGURE,
new ConfigureMenuEvent($this->factory, $menu)
);
return $menu;
}
}
| <?php
namespace Wanjee\Shuwee\AdminBundle\Menu;
use Knp\Menu\FactoryInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Wanjee\Shuwee\AdminBundle\Event\ConfigureMenuEvent;
/**
* Class Builder
* @package Wanjee\Shuwee\AdminBundle\Menu
*/
class Builder
{
/**
* @var \Knp\Menu\FactoryInterface
*/
private $factory;
/**
* @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
*/
private $dispatcher;
/**
* @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $dispatcher
* @param \Knp\Menu\FactoryInterface $factory
*/
public function __construct(FactoryInterface $factory, EventDispatcherInterface $dispatcher)
{
$this->factory = $factory;
$this->dispatcher = $dispatcher;
}
/**
* Build main menu.
*
* Let any bundle add items to this menu by subscribing to ConfigureMenuEvent::CONFIGURE
* @see ConfigureMenuContentListener for example
*
* @param array $options
* @return \Knp\Menu\ItemInterface
*/
public function sideMenu(array $options)
{
$menu = $this->factory->createItem('root');
$this->dispatcher->dispatch(
ConfigureMenuEvent::CONFIGURE,
new ConfigureMenuEvent($this->factory, $menu)
);
return $menu;
}
}
|
Fix window global bug in explode | import Bacon from 'baconjs';
function _snakeToCamel(s){
// From https://coderwall.com/p/iprsng/convert-snake-case-to-camelcase
return s.replace(/(\_\w)/g, function(m){return m[1].toUpperCase();});
}
export function explode(action$){
let exploded = {};
// Values in action$ look like { type: TOGGLE_ACTION, payload: {} }
for (let actionType of action$.actionTypes) {
let streamName = _snakeToCamel(actionType.toLowerCase()) + '$';
exploded[streamName] =
action$.filter(({ type }) => type === actionType)
.map(({ payload }) => payload);
}
return exploded;
}
export function asActionType(actionType, errorActionType){
if (!Array.isArray(actionType)) {
actionType = [actionType];
}
if (errorActionType && !Array.isArray(errorActionType)) {
errorActionType = [errorActionType];
}
if (errorActionType) {
return event$ =>
event$.flatMap(
payload => Bacon.sequentially(
0, actionType.map(type => ({type, payload}))))
.flatMapError(
payload => Bacon.sequentially(
0, errorActionType.map(type => ({type, payload}))
)
);
} else {
return event$ => event$.flatMap(payload => Bacon.fromArray(
actionType.map(type => ({type, payload}))));
}
}
| import Bacon from 'baconjs';
function _snakeToCamel(s){
// From https://coderwall.com/p/iprsng/convert-snake-case-to-camelcase
return s.replace(/(\_\w)/g, function(m){return m[1].toUpperCase();});
}
export function explode(actions$){
let exploded = {};
// Values in action$ look like { type: TOGGLE_ACTION, payload: {} }
for (let actionType of action$.actionTypes) {
let streamName = _snakeToCamel(actionType.toLowerCase()) + '$';
exploded[streamName] =
actions$.filter(({ type }) => type === actionType)
.map(({ payload }) => payload);
}
return exploded;
}
export function asActionType(actionType, errorActionType){
if (!Array.isArray(actionType)) {
actionType = [actionType];
}
if (errorActionType && !Array.isArray(errorActionType)) {
errorActionType = [errorActionType];
}
if (errorActionType) {
return event$ =>
event$.flatMap(
payload => Bacon.sequentially(
0, actionType.map(type => ({type, payload}))))
.flatMapError(
payload => Bacon.sequentially(
0, errorActionType.map(type => ({type, payload}))
)
);
} else {
return event$ => event$.flatMap(payload => Bacon.fromArray(
actionType.map(type => ({type, payload}))));
}
}
|
Replace app() helper with the instance | <?php
namespace Neves\Events;
use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\Events\Dispatcher as EventDispatcher;
class EventServiceProvider extends ServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->mergeConfigFrom(
__DIR__.'/../../config/transactional-events.php',
'transactional-events'
);
if (! $this->app['config']->get('transactional-events.enable')) {
return;
}
$connectionResolver = $this->app->make('db');
$eventDispatcher = $this->app->make(EventDispatcher::class);
$this->app->extend('events', function () use ($connectionResolver, $eventDispatcher) {
$dispatcher = new TransactionalDispatcher($connectionResolver, $eventDispatcher);
$dispatcher->setTransactionalEvents($this->app['config']->get('transactional-events.transactional'));
$dispatcher->setExcludedEvents($this->app['config']->get('transactional-events.excluded'));
return $dispatcher;
});
}
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$configPath = $this->app->basePath().'/config';
$this->publishes([
__DIR__.'/../../config/transactional-events.php' => $configPath.'/transactional-events.php',
]);
}
}
| <?php
namespace Neves\Events;
use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\Events\Dispatcher as EventDispatcher;
class EventServiceProvider extends ServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->mergeConfigFrom(
__DIR__.'/../../config/transactional-events.php',
'transactional-events'
);
if (! $this->app['config']->get('transactional-events.enable')) {
return;
}
$connectionResolver = $this->app->make('db');
$eventDispatcher = $this->app->make(EventDispatcher::class);
$this->app->extend('events', function () use ($connectionResolver, $eventDispatcher) {
$dispatcher = new TransactionalDispatcher($connectionResolver, $eventDispatcher);
$dispatcher->setTransactionalEvents($this->app['config']->get('transactional-events.transactional'));
$dispatcher->setExcludedEvents($this->app['config']->get('transactional-events.excluded'));
return $dispatcher;
});
}
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$configPath = app()->basePath().'/config';
$this->publishes([
__DIR__.'/../../config/transactional-events.php' => $configPath.'/transactional-events.php',
]);
}
}
|
Add lint reporter rules and enums | var gulp = require('gulp');
var todo = require('gulp-todo');
var lint = require('gulp-eslint');
var paths = {
src: './',
spec: './spec/*.js',
js: [
'./*.js',
'./src/*.js',
'./src/**/*.js',
'./scripts/**/*.js',
'./scripts/**/**/*.js',
'./commands/*.js'
],
};
const report = {
ignore: 0,
warn: 1,
error: 2,
};
var options = {
todo: {
absolute: true
},
lint: {
rules: {
'no-reserved-keys': report.ignore,
'no-cond-assign': report.warn,
'no-dupe-args': report.warn,
'no-dupe-keys': report.warn,
'no-duplicate-case': report.warn,
'no-extra-semi': report.warn,
'no-func-assign': report.warn,
'no-sparse-arrays': report.warn,
'no-unreachable': report.error,
},
parserOptions: {
'ecmaVersion': 6,
},
}
};
gulp.task('todo', toDoTask);
gulp.task('lint', lintTask);
gulp.task('default', ['todo', 'lint']);
function lintTask() {
return gulp
.src(paths.js)
.pipe(lint(options.lint))
.pipe(lint.format())
.pipe(lint.failAfterError());
}
function toDoTask() {
return gulp
.src(paths.js)
.pipe(todo(options.todo))
.pipe(gulp.dest(paths.src));
}
| var gulp = require('gulp');
var todo = require('gulp-todo');
var lint = require('gulp-eslint');
var paths = {
src: './',
spec: './spec/*.js',
js: [
'./*.js',
'./src/*.js',
'./src/**/*.js',
'./scripts/**/*.js',
'./scripts/**/**/*.js',
'./commands/*.js'
],
};
var options = {
todo: {
absolute: true
},
lint: {
rules: {
'no-reserved-keys': 0,
'no-cond-assign': 1,
'no-dupe-args': 1,
'no-dupe-keys': 1,
'no-duplicate-case': 1,
'no-extra-semi': 1,
'no-func-assign': 1,
'no-sparse-arrays': 1,
},
parserOptions: {
'ecmaVersion': 6,
},
}
};
gulp.task('todo', toDoTask);
gulp.task('lint', lintTask);
gulp.task('default', ['todo', 'lint']);
function lintTask() {
return gulp
.src(paths.js)
.pipe(lint(options.lint))
.pipe(lint.format())
.pipe(lint.failAfterError());
}
function toDoTask() {
return gulp
.src(paths.js)
.pipe(todo(options.todo))
.pipe(gulp.dest(paths.src));
}
|
Add error output to testreport. | var assert = require('assert');
var request = require('supertest');
var exec = require('child_process').exec;
var application = require(__dirname + '/server.js');
describe('server', function () {
before(function () {
application.listen();
});
after(function () {
application.close();
});
describe('Array', function () {
describe('#indexOf()', function () {
it('should return -1 when the value is not present', function () {
assert.equal(-1, [1, 2, 3].indexOf(5));
assert.equal(-1, [1, 2, 3].indexOf(0));
});
});
describe('#indexOf()', function () {
it('should return -1 when the value is not present', function () {
assert.equal(-1, [1, 2, 3].indexOf(5));
});
});
describe('GET /', function() {
it('respond with json', function(done) {
request(application.app)
.get('/')
.set('Accept', 'application/json')
.expect('Content-Type', /html/)
.expect(200, done);
});
});
describe('Run Abao', function() {
it('respond with json', function(done) {
this.timeout(15000);
exec('node node_modules/.bin/abao ./raml/api.raml --server http://localhost:3000/api', function (err, stdout) {
console.log(err);
console.log(stdout);
done();
});
});
});
});
});
| var assert = require('assert');
var request = require('supertest');
var exec = require('child_process').exec;
var application = require(__dirname + '/server.js');
describe('server', function () {
before(function () {
application.listen();
});
after(function () {
application.close();
});
describe('Array', function () {
describe('#indexOf()', function () {
it('should return -1 when the value is not present', function () {
assert.equal(-1, [1, 2, 3].indexOf(5));
assert.equal(-1, [1, 2, 3].indexOf(0));
});
});
describe('#indexOf()', function () {
it('should return -1 when the value is not present', function () {
assert.equal(-1, [1, 2, 3].indexOf(5));
});
});
describe('GET /', function() {
it('respond with json', function(done) {
request(application.app)
.get('/')
.set('Accept', 'application/json')
.expect('Content-Type', /html/)
.expect(200, done);
});
});
describe('Run Abao', function() {
it('respond with json', function(done) {
this.timeout(15000);
exec('node node_modules/.bin/abao ./raml/api.raml --server http://localhost:3000/api', function (err, stdout) {
console.log(stdout);
done();
});
});
});
});
});
|
Update admin area queries to use new `filter` parameter
refs #6005
- updates use of the query params removed in #6005 to use new `filter` param | import Ember from 'ember';
export default Ember.Controller.extend({
notifications: Ember.inject.service(),
userPostCount: Ember.computed('model.id', function () {
var promise,
query = {
filter: `author:${this.get('model.slug')}`,
status: 'all'
};
promise = this.store.query('post', query).then(function (results) {
return results.meta.pagination.total;
});
return Ember.Object.extend(Ember.PromiseProxyMixin, {
count: Ember.computed.alias('content'),
inflection: Ember.computed('count', function () {
return this.get('count') > 1 ? 'posts' : 'post';
})
}).create({promise: promise});
}),
actions: {
confirmAccept: function () {
var self = this,
user = this.get('model');
user.destroyRecord().then(function () {
self.get('notifications').closeAlerts('user.delete');
self.store.unloadAll('post');
self.transitionToRoute('team');
}, function () {
self.get('notifications').showAlert('The user could not be deleted. Please try again.', {type: 'error', key: 'user.delete.failed'});
});
},
confirmReject: function () {
return false;
}
},
confirm: {
accept: {
text: 'Delete User',
buttonClass: 'btn btn-red'
},
reject: {
text: 'Cancel',
buttonClass: 'btn btn-default btn-minor'
}
}
});
| import Ember from 'ember';
export default Ember.Controller.extend({
notifications: Ember.inject.service(),
userPostCount: Ember.computed('model.id', function () {
var promise,
query = {
author: this.get('model.slug'),
status: 'all'
};
promise = this.store.query('post', query).then(function (results) {
return results.meta.pagination.total;
});
return Ember.Object.extend(Ember.PromiseProxyMixin, {
count: Ember.computed.alias('content'),
inflection: Ember.computed('count', function () {
return this.get('count') > 1 ? 'posts' : 'post';
})
}).create({promise: promise});
}),
actions: {
confirmAccept: function () {
var self = this,
user = this.get('model');
user.destroyRecord().then(function () {
self.get('notifications').closeAlerts('user.delete');
self.store.unloadAll('post');
self.transitionToRoute('team');
}, function () {
self.get('notifications').showAlert('The user could not be deleted. Please try again.', {type: 'error', key: 'user.delete.failed'});
});
},
confirmReject: function () {
return false;
}
},
confirm: {
accept: {
text: 'Delete User',
buttonClass: 'btn btn-red'
},
reject: {
text: 'Cancel',
buttonClass: 'btn btn-default btn-minor'
}
}
});
|
Allow reply_to to not be set in messages to the MPD frontend | import logging
from mopidy.frontends.base import BaseFrontend
from mopidy.frontends.mpd.dispatcher import MpdDispatcher
from mopidy.frontends.mpd.thread import MpdThread
from mopidy.utils.process import unpickle_connection
logger = logging.getLogger('mopidy.frontends.mpd')
class MpdFrontend(BaseFrontend):
"""
The MPD frontend.
**Settings:**
- :attr:`mopidy.settings.MPD_SERVER_HOSTNAME`
- :attr:`mopidy.settings.MPD_SERVER_PORT`
"""
def __init__(self, *args, **kwargs):
super(MpdFrontend, self).__init__(*args, **kwargs)
self.thread = None
self.dispatcher = MpdDispatcher(self.backend)
def start(self):
"""Starts the MPD server."""
self.thread = MpdThread(self.core_queue)
self.thread.start()
def destroy(self):
"""Destroys the MPD server."""
self.thread.destroy()
def process_message(self, message):
"""
Processes messages with the MPD frontend as destination.
:param message: the message
:type message: dict
"""
assert message['to'] == 'frontend', \
u'Message recipient must be "frontend".'
if message['command'] == 'mpd_request':
response = self.dispatcher.handle_request(message['request'])
if 'reply_to' in message:
connection = unpickle_connection(message['reply_to'])
connection.send(response)
else:
pass # Ignore messages for other frontends
| import logging
from mopidy.frontends.base import BaseFrontend
from mopidy.frontends.mpd.dispatcher import MpdDispatcher
from mopidy.frontends.mpd.thread import MpdThread
from mopidy.utils.process import unpickle_connection
logger = logging.getLogger('mopidy.frontends.mpd')
class MpdFrontend(BaseFrontend):
"""
The MPD frontend.
**Settings:**
- :attr:`mopidy.settings.MPD_SERVER_HOSTNAME`
- :attr:`mopidy.settings.MPD_SERVER_PORT`
"""
def __init__(self, *args, **kwargs):
super(MpdFrontend, self).__init__(*args, **kwargs)
self.thread = None
self.dispatcher = MpdDispatcher(self.backend)
def start(self):
"""Starts the MPD server."""
self.thread = MpdThread(self.core_queue)
self.thread.start()
def destroy(self):
"""Destroys the MPD server."""
self.thread.destroy()
def process_message(self, message):
"""
Processes messages with the MPD frontend as destination.
:param message: the message
:type message: dict
"""
assert message['to'] == 'frontend', \
u'Message recipient must be "frontend".'
if message['command'] == 'mpd_request':
response = self.dispatcher.handle_request(message['request'])
connection = unpickle_connection(message['reply_to'])
connection.send(response)
else:
pass # Ignore messages for other frontends
|
Disable the placeholder if the label is hidden | <?php
namespace fieldwork\components;
class TextField extends Field
{
const ON_ENTER_NEXT = 'next';
const ON_ENTER_SUBMIT = 'submit';
private $onEnter = '',
$mask = null;
public function getAttributes ()
{
$att = array();
if (!empty($this->onEnter))
$att['data-input-action-on-enter'] = $this->onEnter;
if ($this->mask !== null)
$att['data-input-mask'] = $this->mask;
return array_merge(parent::getAttributes(), $att);
}
public function onEnter ($action = '')
{
$this->onEnter = $action;
return $this;
}
/**
* Sets input mask for this field
*
* @param string $mask
*
* @return static
*/
public function setMask ($mask)
{
$this->mask = $mask;
return $this;
}
public function getClasses ()
{
return array_merge(
parent::getClasses(), array('textfield', 'fieldwork-inputfield')
);
}
public function getHTML ($showLabel = true)
{
if ($showLabel)
return sprintf("<div class=\"input-field\"><input type='text' %s><label for=\"%s\">%s</label></div>",
$this->getAttributesString(),
$this->getId(),
$this->label);
else
return sprintf("<div class=\"input-field\"><input placeholder='%s' type='text' %s></div>",
$this->label,
$this->getAttributesString());
}
} | <?php
namespace fieldwork\components;
class TextField extends Field
{
const ON_ENTER_NEXT = 'next';
const ON_ENTER_SUBMIT = 'submit';
private $onEnter = '',
$mask = null;
public function getAttributes ()
{
$att = array();
if (!empty($this->onEnter))
$att['data-input-action-on-enter'] = $this->onEnter;
if ($this->mask !== null)
$att['data-input-mask'] = $this->mask;
return array_merge(parent::getAttributes(), $att);
}
public function onEnter ($action = '')
{
$this->onEnter = $action;
return $this;
}
/**
* Sets input mask for this field
*
* @param string $mask
*
* @return static
*/
public function setMask ($mask)
{
$this->mask = $mask;
return $this;
}
public function getClasses ()
{
return array_merge(
parent::getClasses(), array('textfield', 'fieldwork-inputfield')
);
}
public function getHTML ($showLabel = true)
{
if ($showLabel)
return sprintf("<div class=\"input-field\"><input type='text' %s><label for=\"%s\">%s</label></div>",
$this->getAttributesString(),
$this->getId(),
$this->label);
else
return sprintf("<div class=\"input-field\"><input type='text' %s></div>",
$this->getAttributesString(),
$this->getId());
}
} |
Adjust disable button create task. | /**
* Created by eurides on 25/04/16.
*/
(function ($) {
$.fn.serverStatus = function () {
$.ajax({
type: 'GET',
dataType: 'json',
url: 'serviceStatus',
success: function (data) {
if ((!data) || (!data.statusServidor)) {
$.fn.statusError();
}
},
error: function (jqXHR, textStatus, errorThrown) {
$.fn.statusError();
}
});
};
$.fn.statusError = function (message) {
message = typeof message !== 'undefined' ? message : 'Serviço offline';
if (!$('#content').length) {
$('body').prepend('<div id="content"></div>');
}
if (!$('#content').find('#flash_error').length) {
$('#content').prepend('<div class="flash warning" id="flash_error"></div>');
}
$('#flash_error').html('<span>' + message + '</span>');
};
$.fn.taskRedmineExists = function () {
var el = $(this);
var chamado_nro = $('#chamado_nro').val();
if (chamado_nro > 0) {
$.ajax({
type: 'GET',
dataType: 'json',
url: 'taskRedmineExists/' + chamado_nro,
success: function (data) {
el.attr("disabled", true);
},
error: function (jqXHR, textStatus, errorThrown) {
el.removeAttr("disabled");
}
});
} else {
el.attr("disabled", true);
}
};
}(jQuery));
| /**
* Created by eurides on 25/04/16.
*/
(function ($) {
$.fn.serverStatus = function () {
$.ajax({
type: 'GET',
dataType: 'json',
url: 'serviceStatus',
success: function (data) {
if ((!data) || (!data.statusServidor)) {
$.fn.statusError();
}
},
error: function (jqXHR, textStatus, errorThrown) {
$.fn.statusError();
}
});
};
$.fn.statusError = function (message) {
message = typeof message !== 'undefined' ? message : 'Serviço offline';
if (!$('#content').length) {
$('body').prepend('<div id="content"></div>');
}
if (!$('#content').find('#flash_error').length) {
$('#content').prepend('<div class="flash warning" id="flash_error"></div>');
}
$('#flash_error').html('<span>' + message + '</span>');
};
$.fn.taskRedmineExists = function () {
var el = $(this);
var chamado_nro = $('#chamado_nro').val();
if (chamado_nro > 0) {
$.ajax({
type: 'GET',
dataType: 'json',
url: 'taskRedmineExists/' + chamado_nro,
success: function (data) {
el.removeAttr("disabled");
},
error: function (jqXHR, textStatus, errorThrown) {
el.attr("disabled", true);
}
});
} else {
el.attr("disabled", true);
}
};
}(jQuery)); |
Add number input to mui | /**
* Created by steve on 15/09/15.
*/
import React from 'react';
var utils = require('../utils');
var classNames = require('classnames');
import ValidationMixin from '../ValidationMixin';
const TextField = require('material-ui/lib/text-field');
/**
* There is no default number picker as part of Material-UI.
* Instead, use a TextField and validate.
*/
class MuiNumber extends React.Component {
constructor(props) {
super(props);
this.preValidationCheck = this.preValidationCheck.bind(this);
this.state = {
lastSuccessfulValue : this.props.value
}
}
isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
/**
* Prevent the field from accepting non-numeric characters.
* @param e
*/
preValidationCheck(e) {
if (this.isNumeric(e.target.value)) {
this.setState({
lastSuccessfulValue: e.target.value
});
this.props.onChangeValidate(e);
} else {
this.refs.numberField.setValue(this.state.lastSuccessfulValue);
}
}
render() {
return (
<TextField
type={this.props.form.type}
floatingLabelText={this.props.form.title}
hintText={this.props.form.placeholder}
errorText={this.props.error}
onChange={this.preValidationCheck}
defaultValue={this.state.lastSuccessfulValue}
ref="numberField"/>
);
}
}
export default ValidationMixin(MuiNumber);
| /**
* Created by steve on 15/09/15.
*/
import React from 'react';
var utils = require('../utils');
var classNames = require('classnames');
import ValidationMixin from '../ValidationMixin';
class MuiNumber extends React.Component {
render() {
let formClasses = classNames('form-group', { 'has-error' : this.props.valid === false }, this.props.form.htmlClass, { 'has-success' : this.props.valid === true && this.props.value != null});
let labelClasses = classNames('control-label', this.props.form.labelHtmlClass);
let fieldClasses = classNames('form-control', this.props.form.fieldHtmlClass);
let help = this.props.form.description || '';
if(!this.props.valid || this.props.form.description) {
help = (
<div className="help-block">
{this.props.error || this.props.form.description}
</div>
)
}
return (
<div className={formClasses}>
<label className={labelClasses}>{this.props.form.title}</label>
<input type={this.props.form.type}
onChange={this.props.onChangeValidate}
step={this.props.form.step}
className={fieldClasses}
defaultValue={this.props.value}
id={this.props.form.key.slice(-1)[0]}
name={this.props.form.key.slice(-1)[0]}/>
{help}
</div>
);
}
}
export default ValidationMixin(MuiNumber);
|
Fix button color for confirm dialogue. | $(function() {
$('#btnAddPermission').click(function() {
$(this).parent().append(JST["assets/templates/rights/permissioninput.html"]);
});
$('#deleteGroup').click(function() {
var self = this;
swal({
title: 'Are you sure?',
text: 'If you continue, you will not be able to recover the deleted group.',
type: 'warning',
showCancelButton: true,
confirmButtonClass: 'btn-danger',
confirmButtonText: 'Yes, continue',
closeOnConfirm: false
}, function() {
$.ajax({
url: self.getAttribute('data-href'),
type: 'DELETE',
dataType: 'json',
success: function(result) {
window.location.href = self.getAttribute('data-return');
},
error: function(result) {
if(result.status === 200) {
window.location.href = self.getAttribute('data-return');
}
}
});
});
});
});
| $(function() {
$('#btnAddPermission').click(function() {
$(this).parent().append(JST["assets/templates/rights/permissioninput.html"]);
});
$('#deleteGroup').click(function() {
var self = this;
swal({
title: 'Are you sure?',
text: 'If you continue, you will not be able to recover the deleted group.',
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#DD6B55',
confirmButtonText: 'Yes, continue'
}, function() {
$.ajax({
url: self.getAttribute('data-href'),
type: 'DELETE',
dataType: 'json',
success: function(result) {
window.location.href = self.getAttribute('data-return');
},
error: function(result) {
if(result.status === 200) {
window.location.href = self.getAttribute('data-return');
}
}
});
});
});
});
|
Allow using non-Premium keys for Google Maps client | #!/usr/local/bin/python
# -*- coding: utf-8 -*-
import googlemaps
import base64
from exceptions import InvalidGoogleCredentials
class GoogleMapsClientFactory():
clients = {}
@classmethod
def get(cls, client_id, client_secret, channel=None):
cache_key = "{}:{}:{}".format(client_id, client_secret, channel)
client = cls.clients.get(cache_key)
if not client:
if client_id:
cls.assert_valid_crendentials(client_secret)
client = googlemaps.Client(
client_id=client_id,
client_secret=client_secret,
channel=channel)
else:
client = googlemaps.Client(key=client_secret)
cls.clients[cache_key] = client
return client
@classmethod
def assert_valid_crendentials(cls, client_secret):
if not cls.valid_credentials(client_secret):
raise InvalidGoogleCredentials
@staticmethod
def valid_credentials(client_secret):
try:
# Only fails if the string dont have a correct padding for b64
# but this way we could provide a more clear error than
# TypeError: Incorrect padding
b64_secret = client_secret.replace('-', '+').replace('_', '/')
base64.b64decode(b64_secret)
return True
except TypeError:
return False
| #!/usr/local/bin/python
# -*- coding: utf-8 -*-
import googlemaps
import base64
from exceptions import InvalidGoogleCredentials
class GoogleMapsClientFactory():
clients = {}
@classmethod
def get(cls, client_id, client_secret, channel=None):
cache_key = "{}:{}:{}".format(client_id, client_secret, channel)
client = cls.clients.get(cache_key)
if not client:
cls.assert_valid_crendentials(client_secret)
client = googlemaps.Client(
client_id=client_id,
client_secret=client_secret,
channel=channel)
cls.clients[cache_key] = client
return client
@classmethod
def assert_valid_crendentials(cls, client_secret):
if not cls.valid_credentials(client_secret):
raise InvalidGoogleCredentials
@staticmethod
def valid_credentials(client_secret):
try:
# Only fails if the string dont have a correct padding for b64
# but this way we could provide a more clear error than
# TypeError: Incorrect padding
b64_secret = client_secret.replace('-', '+').replace('_', '/')
base64.b64decode(b64_secret)
return True
except TypeError:
return False
|
Disable fluxible logs in production | import polyfill from 'babel-polyfill'; // eslint-disable-line no-unused-vars
import d from 'debug';
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, browserHistory } from 'react-router';
import routes from 'components/Routes';
import app from './app';
import fetchRouteData from 'utils/fetchRouteData';
import { provideContext } from 'fluxible-addons-react';
const debug = d('App');
if (window.App.env !== 'production') {
d.enable('App, Fluxible, Fluxible:*');
}
debug('Rehydrating...');
app.rehydrate(window.App, (err, context) => {
let isRehydrating = true;
if (err) {
throw err;
}
debug('React Rendering');
const RouterWithContext = provideContext(Router, app.customContexts);
ReactDOM.render(
<RouterWithContext
context={context.getComponentContext()}
history={browserHistory}
onUpdate={function onUpdate() {
if (isRehydrating) {
isRehydrating = false;
return;
}
fetchRouteData(context, this.state)
.then(() => { /* emit an event? */ })
.catch(fetchDataErr => {
console.error(fetchDataErr.stack);
});
}}
>{routes}</RouterWithContext>,
document.getElementById('app'),
() => { debug('React Rendered'); }
);
});
| import polyfill from 'babel-polyfill'; // eslint-disable-line no-unused-vars
import d from 'debug';
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, browserHistory } from 'react-router';
import routes from 'components/Routes';
import app from './app';
import fetchRouteData from 'utils/fetchRouteData';
import { provideContext } from 'fluxible-addons-react';
const debug = d('App');
d.enable('App, Fluxible, Fluxible:*');
debug('Rehydrating...');
app.rehydrate(window.App, (err, context) => {
let isRehydrating = true;
if (err) {
throw err;
}
debug('React Rendering');
const RouterWithContext = provideContext(Router, app.customContexts);
ReactDOM.render(
<RouterWithContext
context={context.getComponentContext()}
history={browserHistory}
onUpdate={function onUpdate() {
if (isRehydrating) {
isRehydrating = false;
return;
}
fetchRouteData(context, this.state)
.then(() => { /* emit an event? */ })
.catch(fetchDataErr => {
console.error(fetchDataErr.stack);
});
}}
>{routes}</RouterWithContext>,
document.getElementById('app'),
() => { debug('React Rendered'); }
);
});
|
Clean up controlled vocab tests | import unittest
from cybox.common.vocabs import VocabString
import cybox.test
from cybox.utils import normalize_to_xml
class TestVocabString(unittest.TestCase):
def test_plain(self):
a = VocabString("test_value")
self.assertTrue(a.is_plain())
def test_round_trip(self):
vocab_dict = {
'value': "test_value",
'vocab_name': "test_a",
'vocab_reference': "test_b",
'condition': "test_d",
# Leave out apply_condition since value is not a list.
'bit_mask': "test_1",
'pattern_type': "test_e",
'regex_syntax': "test_f",
'has_changed': "test_j",
'trend': "test_k",
}
vocab_dict2 = cybox.test.round_trip_dict(VocabString, vocab_dict)
cybox.test.assert_equal_ignore(vocab_dict, vocab_dict2, ['xsi:type'])
def test_round_trip_list(self):
vocab_dict = {
'value': ['Value1', 'Value2', 'Value3'],
'condition': "Equals",
'apply_condition': "ALL",
}
vocab_dict2 = cybox.test.round_trip_dict(VocabString, vocab_dict)
cybox.test.assert_equal_ignore(vocab_dict, vocab_dict2, ['xsi:type'])
if __name__ == "__main__":
unittest.main()
| import unittest
from cybox.common.vocabs import VocabString
import cybox.test
from cybox.utils import normalize_to_xml
class TestVocabString(unittest.TestCase):
def test_plain(self):
a = VocabString("test_value")
self.assertTrue(a.is_plain())
def test_round_trip(self):
attr_dict = {
'value': "test_value",
'vocab_name': "test_a",
'vocab_reference': "test_b",
'condition': "test_d",
'apply_condition': "test_0",
'bit_mask': "test_1",
'pattern_type': "test_e",
'regex_syntax': "test_f",
'has_changed': "test_j",
'trend': "test_k",
}
attr_obj = VocabString.object_from_dict(attr_dict)
attr_dict2 = VocabString.dict_from_object(attr_obj)
cybox.test.assert_equal_ignore(attr_dict, attr_dict2, ['xsi:type'])
if __name__ == "__main__":
unittest.main()
|
Fix : response datas list should not be unicoded | import msgpack
import logging
class MessageFormatError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class Request(object):
"""Handler objects for frontend->backend objects messages"""
def __init__(self, raw_message, compressed=False):
errors_logger = logging.getLogger("errors_logger")
message = msgpack.unpackb(raw_message)
try:
self.db_uid = message.pop('DB_UID')
self.command = message.pop('COMMAND')
self.data = message.pop('ARGS')
except KeyError:
errors_logger.exception("Invalid request message : %s" %
message)
raise MessageFormatError("Invalid request message")
class Response(tuple):
"""Handler objects for frontend->backend objects messages"""
def __new__(cls, id, *args, **kwargs):
response = {
'STATUS': kwargs.pop('status', 0),
'DATAS': kwargs.pop('datas', [])
}
response['DATAS'] = cls._format_datas(response['DATAS'])
msg = [id, msgpack.packb(response)]
return tuple.__new__(cls, msg)
@classmethod
def _format_datas(cls, datas):
if datas and not isinstance(datas, (tuple, list)):
datas = [datas]
return datas
| import msgpack
import logging
class MessageFormatError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class Request(object):
"""Handler objects for frontend->backend objects messages"""
def __init__(self, raw_message, compressed=False):
errors_logger = logging.getLogger("errors_logger")
message = msgpack.unpackb(raw_message)
try:
self.db_uid = message.pop('DB_UID')
self.command = message.pop('COMMAND')
self.data = message.pop('ARGS')
except KeyError:
errors_logger.exception("Invalid request message : %s" %
message)
raise MessageFormatError("Invalid request message")
class Response(tuple):
"""Handler objects for frontend->backend objects messages"""
def __new__(cls, id, *args, **kwargs):
response = {
'STATUS': kwargs.pop('status', 0),
'DATAS': kwargs.pop('datas', [])
}
response['DATAS'] = cls._format_datas(response['DATAS'])
msg = [id, msgpack.packb(response)]
return tuple.__new__(cls, msg)
@classmethod
def _format_datas(cls, datas):
if datas and not isinstance(datas, (tuple, list)):
datas = [datas]
return [unicode(d) for d in datas]
|
Add another test file location | 'use babel';
import { CompositeDisposable, File } from 'atom';
export default {
subscriptions: null,
activate() {
// Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
this.subscriptions = new CompositeDisposable();
this.subscriptions.add(atom.commands.add('atom-workspace', {
'atom-jump-to-spec:open-spec': () => this.openSpec(),
}));
},
deactivate() {
this.subscriptions.dispose();
},
serialize() {
return {};
},
openSpec() {
const editor = atom.workspace.getActiveTextEditor();
if (editor) {
this.getSpecFilePath(editor);
}
},
getSpecFilePath(editor) {
const srcPath = atom.project.relativizePath(editor.getPath());
['/test/unit', '/test/unit/spec', '/spec', '/test', '/src'].forEach(testDir => {
['.spec', '-spec'].forEach(testPostfix => {
let specPath = srcPath[0] + testDir + srcPath[1].slice(3);
const indexOfExtension = specPath.lastIndexOf('.');
specPath = specPath.slice(0, indexOfExtension) + testPostfix + specPath.slice(indexOfExtension);
const testFile = new File(specPath);
testFile.exists().then(doesExist => {
if (doesExist) {
atom.workspace.open(specPath);
}
});
});
});
},
};
| 'use babel';
import { CompositeDisposable, File } from 'atom';
export default {
subscriptions: null,
activate() {
// Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
this.subscriptions = new CompositeDisposable();
this.subscriptions.add(atom.commands.add('atom-workspace', {
'atom-jump-to-spec:open-spec': () => this.openSpec(),
}));
},
deactivate() {
this.subscriptions.dispose();
},
serialize() {
return {};
},
openSpec() {
const editor = atom.workspace.getActiveTextEditor();
if (editor) {
this.getSpecFilePath(editor);
}
},
getSpecFilePath(editor) {
const srcPath = atom.project.relativizePath(editor.getPath());
['/test/unit', '/spec', '/test', '/src'].forEach(testDir => {
['.spec', '-spec'].forEach(testPostfix => {
let specPath = srcPath[0] + testDir + srcPath[1].slice(3);
const indexOfExtension = specPath.lastIndexOf('.');
specPath = specPath.slice(0, indexOfExtension) + testPostfix + specPath.slice(indexOfExtension);
const testFile = new File(specPath);
testFile.exists().then(doesExist => {
if (doesExist) {
atom.workspace.open(specPath);
}
});
});
});
},
};
|
Increment version for new max_dBFS property | __doc__ = """
Manipulate audio with an simple and easy high level interface.
See the README file for details, usage info, and a list of gotchas.
"""
from setuptools import setup
setup(
name='pydub',
version='0.11.0',
author='James Robert',
author_email='[email protected]',
description='Manipulate audio with an simple and easy high level interface',
license='MIT',
keywords='audio sound high-level',
url='http://pydub.com',
packages=['pydub'],
long_description=__doc__,
classifiers=[
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
"Topic :: Multimedia :: Sound/Audio",
"Topic :: Multimedia :: Sound/Audio :: Analysis",
"Topic :: Multimedia :: Sound/Audio :: Conversion",
"Topic :: Multimedia :: Sound/Audio :: Editors",
"Topic :: Multimedia :: Sound/Audio :: Mixers",
"Topic :: Software Development :: Libraries",
'Topic :: Utilities',
]
)
| __doc__ = """
Manipulate audio with an simple and easy high level interface.
See the README file for details, usage info, and a list of gotchas.
"""
from setuptools import setup
setup(
name='pydub',
version='0.10.0',
author='James Robert',
author_email='[email protected]',
description='Manipulate audio with an simple and easy high level interface',
license='MIT',
keywords='audio sound high-level',
url='http://pydub.com',
packages=['pydub'],
long_description=__doc__,
classifiers=[
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
"Topic :: Multimedia :: Sound/Audio",
"Topic :: Multimedia :: Sound/Audio :: Analysis",
"Topic :: Multimedia :: Sound/Audio :: Conversion",
"Topic :: Multimedia :: Sound/Audio :: Editors",
"Topic :: Multimedia :: Sound/Audio :: Mixers",
"Topic :: Software Development :: Libraries",
'Topic :: Utilities',
]
)
|
Simplify the buttons beneath the login form | @title('Login')
@extends('layouts.small')
@section('small-content')
{!! Form::open(['route' => 'login.post']) !!}
@formGroup('username')
{!! Form::label('username') !!}
{!! Form::text('username', null, ['class' => 'form-control', 'required']) !!}
@error('username')
@endFormGroup
@formGroup('password')
{!! Form::label('password') !!}
{!! Form::password('password', ['class' => 'form-control', 'required']) !!}
@error('password')
@endFormGroup
<div class="form-group">
<label>
{!! Form::checkbox('remember') !!}
Remember login
</label>
</div>
{!! Form::submit('Login', ['class' => 'btn btn-primary btn-block']) !!}
<a href="{{ route('login.github') }}" class="btn btn-default btn-block">
<i class="fa fa-github"></i> Github
</a>
{!! Form::close() !!}
@endsection
@section('small-content-after')
<a href="{{ route('password.forgot') }}" class="btn btn-link btn-sm btn-block">Forgot your password?</a>
@endsection
| @title('Login')
@extends('layouts.small')
@section('small-content')
{!! Form::open(['route' => 'login.post']) !!}
@formGroup('username')
{!! Form::label('username') !!}
{!! Form::text('username', null, ['class' => 'form-control', 'required']) !!}
@error('username')
@endFormGroup
@formGroup('password')
{!! Form::label('password') !!}
{!! Form::password('password', ['class' => 'form-control', 'required']) !!}
@error('password')
@endFormGroup
<div class="form-group">
<label>
{!! Form::checkbox('remember') !!}
Remember login
</label>
</div>
{!! Form::submit('Login', ['class' => 'btn btn-primary btn-block']) !!}
<a href="{{ route('login.github') }}" class="btn btn-default btn-block">
<i class="fa fa-github"></i> Github
</a>
{!! Form::close() !!}
@endsection
@section('small-content-after')
<div class="text-center">
<a href="{{ route('password.forgot') }}" class="btn btn-default btn-sm btn-block">Forgot your password?</a>
<a href="{{ route('register') }}" class="btn btn-default btn-sm btn-block">Need an account?</a>
</div>
@endsection
|
Make data_files paths absolute again | # -*- coding: utf-8 -*-
import sys
import os.path
from setuptools import Command, find_packages, setup
HERE = os.path.abspath(os.path.dirname(__file__))
README_PATH = os.path.join(HERE, 'README.rst')
try:
README = open(README_PATH).read()
except IOError:
README = ''
setup(
name='rollbar-udp-agent',
version='0.0.13',
description='Rollbar server-side UDP agent',
long_description=README,
author='Luis Rascão',
author_email='[email protected]',
url='http://github.com/lrascao/rollbar-udp-agent',
entry_points={
"console_scripts": [
"rollbar-udp-agent=rollbar_udp_agent:main"
],
},
packages=['rollbar_udp_agent'],
data_files=[('/etc', ['rollbar-udp-agent.conf']),
('/etc/init.d', ['rollbar-udp-agent'])],
classifiers=[
"Programming Language :: Python",
"License :: OSI Approved :: MIT License",
"Development Status :: 4 - Beta",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware",
"Topic :: Software Development",
"Topic :: Software Development :: Bug Tracking",
"Topic :: Software Development :: Testing",
"Topic :: Software Development :: Quality Assurance",
],
install_requires=[
'requests'
],
)
| # -*- coding: utf-8 -*-
import sys
import os.path
from setuptools import Command, find_packages, setup
HERE = os.path.abspath(os.path.dirname(__file__))
README_PATH = os.path.join(HERE, 'README.rst')
try:
README = open(README_PATH).read()
except IOError:
README = ''
setup(
name='rollbar-udp-agent',
version='0.0.13',
description='Rollbar server-side UDP agent',
long_description=README,
author='Luis Rascão',
author_email='[email protected]',
url='http://github.com/lrascao/rollbar-udp-agent',
entry_points={
"console_scripts": [
"rollbar-udp-agent=rollbar_udp_agent:main"
],
},
packages=['rollbar_udp_agent'],
data_files=[('etc', ['rollbar-udp-agent.conf']),
('etc/init.d', ['rollbar-udp-agent'])],
classifiers=[
"Programming Language :: Python",
"License :: OSI Approved :: MIT License",
"Development Status :: 4 - Beta",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware",
"Topic :: Software Development",
"Topic :: Software Development :: Bug Tracking",
"Topic :: Software Development :: Testing",
"Topic :: Software Development :: Quality Assurance",
],
install_requires=[
'requests'
],
)
|
Make acquire_context always return some Context | """Placeholder model for Zinnia"""
import inspect
from django.template.context import Context, RequestContext
from cms.models.fields import PlaceholderField
from cms.plugin_rendering import render_placeholder
from zinnia.models.entry import EntryAbstractClass
class EntryPlaceholder(EntryAbstractClass):
"""Entry with a Placeholder to edit content"""
content_placeholder = PlaceholderField('content')
def acquire_context(self):
"""
Inspect the stack to acquire the current context used,
to render the placeholder. I'm really sorry for this,
but if you have a better way, you are welcome !
"""
frame = None
request = None
try:
for f in inspect.stack()[1:]:
frame = f[0]
args, varargs, keywords, alocals = inspect.getargvalues(frame)
if not request and 'request' in args:
request = alocals['request']
if 'context' in args:
return alocals['context']
finally:
del frame
if request is not None:
return RequestContext(request)
else:
return Context()
@property
def html_content(self):
"""
Render the content_placeholder field dynamicly.
https://github.com/Fantomas42/cmsplugin-zinnia/issues/3
"""
context = self.acquire_context()
return render_placeholder(self.content_placeholder, context)
class Meta(EntryAbstractClass.Meta):
"""EntryPlaceholder's Meta"""
abstract = True
| """Placeholder model for Zinnia"""
import inspect
from cms.models.fields import PlaceholderField
from cms.plugin_rendering import render_placeholder
from zinnia.models.entry import EntryAbstractClass
class EntryPlaceholder(EntryAbstractClass):
"""Entry with a Placeholder to edit content"""
content_placeholder = PlaceholderField('content')
def acquire_context(self):
"""
Inspect the stack to acquire the current context used,
to render the placeholder. I'm really sorry for this,
but if you have a better way, you are welcome !
"""
frame = None
try:
for f in inspect.stack()[1:]:
frame = f[0]
args, varargs, keywords, alocals = inspect.getargvalues(frame)
if 'context' in args:
return alocals['context']
finally:
del frame
@property
def html_content(self):
"""
Render the content_placeholder field dynamicly.
https://github.com/Fantomas42/cmsplugin-zinnia/issues/3
"""
context = self.acquire_context()
return render_placeholder(self.content_placeholder, context)
class Meta(EntryAbstractClass.Meta):
"""EntryPlaceholder's Meta"""
abstract = True
|
Append hostname to messages file. This supports a use-case where portions of
the processing could happen on various hosts. | # logger module
from datetime import datetime
import os
import socket # gethostname()
logfile = None
logbuf = []
def init(analysis_path):
global logfile
if not os.path.isdir(analysis_path):
log("logger: analysis_path missing:", analysis_path)
logfile = os.path.join(analysis_path, "messages-" + socket.gethostname())
# log a message to messages files (and to stdout by default)
def log(*args, quiet=False, fancy=False):
global logbuf
# timestamp
now = datetime.now()
timestamp = str(now) + ": "
# assemble message line
msg = []
for a in args:
msg.append(str(a))
if not fancy:
logbuf.append(timestamp + " ".join(msg))
else:
logbuf.append("")
logbuf.append("############################################################################")
logbuf.append("### " + timestamp + " ".join(msg))
logbuf.append("############################################################################")
logbuf.append("")
if logfile:
# flush log buffer
f = open(logfile, "a")
for line in logbuf:
f.write(line)
f.write("\n")
f.close()
logbuf = []
if not quiet:
print(*msg)
# log quietly (log to file, but not to stdout)
def qlog(*args):
log(*args, quiet=True)
| # logger module
from datetime import datetime
import os
logfile = None
logbuf = []
def init(analysis_path):
global logfile
if not os.path.isdir(analysis_path):
log("logger: analysis_path missing:", analysis_path)
use_log_dir = False
if use_log_dir:
logdir = os.path.join(analysis_path, "log")
if not os.path.isdir(logdir):
log("logger: creating log directory:", logdir)
os.makedirs(logdir)
logfile = os.path.join(logdir, "messages")
else:
logfile = os.path.join(analysis_path, "messages")
# log a message to messages files (and to stdout by default)
def log(*args, quiet=False, fancy=False):
global logbuf
# timestamp
now = datetime.now()
timestamp = str(now) + ": "
# assemble message line
msg = []
for a in args:
msg.append(str(a))
if not fancy:
logbuf.append(timestamp + " ".join(msg))
else:
logbuf.append("")
logbuf.append("############################################################################")
logbuf.append("### " + timestamp + " ".join(msg))
logbuf.append("############################################################################")
logbuf.append("")
if logfile:
# flush log buffer
f = open(logfile, "a")
for line in logbuf:
f.write(line)
f.write("\n")
f.close()
logbuf = []
if not quiet:
print(*msg)
# log quietly (log to file, but not to stdout)
def qlog(*args):
log(*args, quiet=True)
|
Remove .user to appease Leon | module.exports = {
name: "Member Nickname Changed MOD",
isEvent: true,
fields: ["Temp Variable Name (stores new nickname):", "Temp Variable Name (stores member object):"],
mod: function(DBM) {
DBM.Mindlesscargo = DBM.Mindlesscargo || {};
DBM.Mindlesscargo.nicknameChanged = async function(oldMember, newMember) {
const { Bot, Actions } = DBM;
const events = Bot.$evts["Member Nickname Changed MOD"];
if(!events) return;
if (newMember.nickname === oldMember.nickname) return;
for (const event of events) {
const temp = {};
const server = newMember.guild
const newNickname = newMember.nickname;
if (event.temp) temp[event.temp] = newNickname;
if (event.temp2) temp[event.temp2] = newMember;
Actions.invokeEvent(event, server, temp);
}
};
const onReady = DBM.Bot.onReady;
DBM.Bot.onReady = function(...params) {
DBM.Bot.bot.on("guildMemberUpdate", DBM.Mindlesscargo.nicknameChanged);
onReady.apply(this, ...params);
}
}
};
| module.exports = {
name: "Member Nickname Changed MOD",
isEvent: true,
fields: ["Temp Variable Name (stores new nickname):", "Temp Variable Name (stores member object):"],
mod: function(DBM) {
DBM.Mindlesscargo = DBM.Mindlesscargo || {};
DBM.Mindlesscargo.nicknameChanged = async function(oldMember, newMember) {
const { Bot, Actions } = DBM;
const events = Bot.$evts["Member Nickname Changed MOD"];
if(!events) return;
if (newMember.nickname === oldMember.nickname) return;
for (const event of events) {
const temp = {};
const server = newMember.guild
const newNickname = newMember.nickname;
if (event.temp) temp[event.temp] = newNickname;
if (event.temp2) temp[event.temp2] = newMember.user;
Actions.invokeEvent(event, server, temp);
}
};
const onReady = DBM.Bot.onReady;
DBM.Bot.onReady = function(...params) {
DBM.Bot.bot.on("guildMemberUpdate", DBM.Mindlesscargo.nicknameChanged);
onReady.apply(this, ...params);
}
}
};
|
Correct test criteria for time format for scheduled skill.
Now matches current behaviour, previous behaviour is not a good idea since it depended on Locale. | from datetime import datetime, timedelta
import unittest
from mycroft.skills.scheduled_skills import ScheduledSkill
from mycroft.util.log import getLogger
__author__ = 'eward'
logger = getLogger(__name__)
class ScheduledSkillTest(unittest.TestCase):
skill = ScheduledSkill(name='ScheduledSkillTest')
def test_formatted_time_today_hours(self):
date = datetime.now() + timedelta(hours=2)
self.assertEquals(self.skill.
get_formatted_time(float(date.strftime('%s'))),
"1 hours and 59 minutes from now")
def test_formatted_time_today_min(self):
date = datetime.now() + timedelta(minutes=2)
self.assertEquals(self.skill.
get_formatted_time(float(date.strftime('%s'))),
"1 minutes and 59 seconds from now")
def test_formatted_time_days(self):
date = datetime.now() + timedelta(days=2)
self.assertEquals(self.skill.
get_formatted_time(float(date.strftime('%s'))),
date.strftime("%d %B, %Y at %H:%M"))
| from datetime import datetime, timedelta
import unittest
from mycroft.skills.scheduled_skills import ScheduledSkill
from mycroft.util.log import getLogger
__author__ = 'eward'
logger = getLogger(__name__)
class ScheduledSkillTest(unittest.TestCase):
skill = ScheduledSkill(name='ScheduledSkillTest')
def test_formatted_time_today_hours(self):
date = datetime.now() + timedelta(hours=2)
self.assertEquals(self.skill.
get_formatted_time(float(date.strftime('%s'))),
"1 hours and 59 minutes from now")
def test_formatted_time_today_min(self):
date = datetime.now() + timedelta(minutes=2)
self.assertEquals(self.skill.
get_formatted_time(float(date.strftime('%s'))),
"1 minutes and 59 seconds from now")
def test_formatted_time_days(self):
date = datetime.now() + timedelta(days=2)
self.assertEquals(self.skill.
get_formatted_time(float(date.strftime('%s'))),
date.strftime("%A, %B %d, %Y at %H:%M"))
|
Delete unused value extractor attribute. | from webapp_health_monitor import errors
class Verificator(object):
verificator_name = None
def __init__(self, **kwargs):
pass
def run(self):
raise NotImplementedError()
def __str__(self):
if self.verificator_name:
return self.verificator_name
else:
return self.__class__.__name__
class RangeVerificator(Verificator):
upper_bound = None
lower_bound = None
def run(self):
self._check_configuration()
self._check_value()
def _check_configuration(self):
if not self._are_bounds_configured():
raise errors.BadConfigurationError()
def _are_bounds_configured(self):
if self.lower_bound is None:
return self.upper_bound is not None
elif self.upper_bound is not None:
return self.lower_bound <= self.upper_bound
else:
return True
def _check_value(self):
value = self.get_value()
self._check_lower_bound(value)
self._check_upper_bound(value)
def get_value(self):
raise NotImplementedError
def _check_lower_bound(self, value):
if self.lower_bound is not None:
if value < self.lower_bound:
raise errors.VerificationFailure()
def _check_upper_bound(self, value):
if self.upper_bound is not None:
if value > self.upper_bound:
raise errors.VerificationFailure()
| from webapp_health_monitor import errors
class Verificator(object):
verificator_name = None
def __init__(self, **kwargs):
pass
def run(self):
raise NotImplementedError()
def __str__(self):
if self.verificator_name:
return self.verificator_name
else:
return self.__class__.__name__
class RangeVerificator(Verificator):
value_extractor = None
upper_bound = None
lower_bound = None
def run(self):
self._check_configuration()
self._check_value()
def _check_configuration(self):
if not self._are_bounds_configured():
raise errors.BadConfigurationError()
def _are_bounds_configured(self):
if self.lower_bound is None:
return self.upper_bound is not None
elif self.upper_bound is not None:
return self.lower_bound <= self.upper_bound
else:
return True
def _check_value(self):
value = self.get_value()
self._check_lower_bound(value)
self._check_upper_bound(value)
def get_value(self):
raise NotImplementedError
def _check_lower_bound(self, value):
if self.lower_bound is not None:
if value < self.lower_bound:
raise errors.VerificationFailure()
def _check_upper_bound(self, value):
if self.upper_bound is not None:
if value > self.upper_bound:
raise errors.VerificationFailure()
|
Remove now-unused sections from submission flow
SVN-Revision: 3230 | package gov.nih.nci.cabig.caaers.domain.expeditedfields;
import gov.nih.nci.cabig.ctms.domain.CodedEnum;
public enum ExpeditedReportSection implements CodedEnum<Integer>{
BASICS_SECTION("Basic AE information"),
ADVERSE_EVENT_SECTION("Adverse events"),
REPORTER_INFO_SECTION("Reporter Information"),
CHECKPOINT_SECTION("Checkpoint"),
RADIATION_INTERVENTION_SECTION("Radiation Intervention"),
SURGERY_INTERVENTION_SECTION("Surgery Intervention"),
MEDICAL_DEVICE_SECTION("Medical Device"),
DESCRIPTION_SECTION("Description"),
MEDICAL_INFO_SCECTION("Medical"),
TREATMENT_INFO_SECTION("Treatment"),
LABS_SECTION("Labs"),
PRIOR_THERAPIES_SECTION("Therapies"),
PRE_EXISTING_CONDITION_SECTION("Pre-Existing Conditions"),
CONCOMITANT_MEDICATION_SECTION("Conmeds"),
OTHER_CAUSE_SECTION("Other contributing causes"),
ATTRIBUTION_SECTION("Attribution"),
ADDITIONAL_INFO_SECTION("Additional Information");
private String displayName;
private ExpeditedReportSection(String displayName) {
this.displayName = displayName;
}
public String getDisplayName() {
return displayName;
}
public static ExpeditedReportSection getByDisplayName(String displayName) {
for (ExpeditedReportSection section : values()) {
if (section.displayName.equals(displayName)) return section;
}
return null;
}
public Integer getCode() {
return ordinal();
}
}
| package gov.nih.nci.cabig.caaers.domain.expeditedfields;
import gov.nih.nci.cabig.ctms.domain.CodedEnum;
public enum ExpeditedReportSection implements CodedEnum<Integer>{
BASICS_SECTION("Basic AE information"),
ADVERSE_EVENT_SECTION("Adverse events"),
REPORTER_INFO_SECTION("Reporter Information"),
CHECKPOINT_SECTION("Checkpoint"),
RADIATION_INTERVENTION_SECTION("Radiation Intervention"),
SURGERY_INTERVENTION_SECTION("Surgery Intervention"),
MEDICAL_DEVICE_SECTION("Medical Device"),
DESCRIPTION_SECTION("Description"),
MEDICAL_INFO_SCECTION("Medical"),
TREATMENT_INFO_SECTION("Treatment"),
LABS_SECTION("Labs"),
PRIOR_THERAPIES_SECTION("Therapies"),
PRE_EXISTING_CONDITION_SECTION("Pre-Existing Conditions"),
CONCOMITANT_MEDICATION_SECTION("Conmeds"),
OTHER_CAUSE_SECTION("Other contributing causes"),
ATTRIBUTION_SECTION("Attribution"),
ADDITIONAL_INFO_SECTION("Additional Information"),
SUBMIT_REPORT_SECTION("Submit Report"),
SUBMITTER_SECTION("Submitter info");
private String displayName;
private ExpeditedReportSection(String displayName) {
this.displayName = displayName;
}
public String getDisplayName() {
return displayName;
}
public static ExpeditedReportSection getByDisplayName(String displayName) {
for (ExpeditedReportSection section : values()) {
if (section.displayName.equals(displayName)) return section;
}
return null;
}
public Integer getCode() {
return ordinal();
}
}
|
Make HF test take much less time! | import theanets
import util
class TestTrainer(util.MNIST):
def setUp(self):
super(TestTrainer, self).setUp()
self.exp = theanets.Experiment(
theanets.Autoencoder,
layers=(self.DIGIT_SIZE, 10, self.DIGIT_SIZE))
def assert_progress(self, algo, **kwargs):
trainer = self.exp.itertrain(self.images, optimize=algo, **kwargs)
costs0 = next(trainer)
costs1 = next(trainer)
costs2 = next(trainer)
assert costs2['J'] < costs0['J']
def test_sgd(self):
self.assert_progress('sgd', learning_rate=1e-4)
def test_nag(self):
self.assert_progress('nag', learning_rate=1e-4)
def test_rprop(self):
self.assert_progress('rprop', learning_rate=1e-4)
def test_rmsprop(self):
self.assert_progress('rmsprop', learning_rate=1e-4)
def test_adadelta(self):
self.assert_progress('adadelta', learning_rate=1e-4)
def test_hf(self):
self.assert_progress('hf', num_updates=3)
def test_cg(self):
self.assert_progress('cg')
def test_layerwise(self):
self.assert_progress('layerwise')
| import theanets
import util
class TestTrainer(util.MNIST):
def setUp(self):
super(TestTrainer, self).setUp()
self.exp = theanets.Experiment(
theanets.Autoencoder,
layers=(self.DIGIT_SIZE, 10, self.DIGIT_SIZE))
def assert_progress(self, algo, **kwargs):
trainer = self.exp.itertrain(self.images, optimize=algo, **kwargs)
costs0 = next(trainer)
costs1 = next(trainer)
costs2 = next(trainer)
assert costs2['J'] < costs0['J']
def test_sgd(self):
self.assert_progress('sgd', learning_rate=1e-4)
def test_nag(self):
self.assert_progress('nag', learning_rate=1e-4)
def test_rprop(self):
self.assert_progress('rprop', learning_rate=1e-4)
def test_rmsprop(self):
self.assert_progress('rmsprop', learning_rate=1e-4)
def test_adadelta(self):
self.assert_progress('adadelta', learning_rate=1e-4)
def test_hf(self):
self.assert_progress('hf')
def test_cg(self):
self.assert_progress('cg')
def test_layerwise(self):
self.assert_progress('layerwise')
|
Change JiraDataService to JiraDataSource in @dl-tools/import-people-from-jira | define([
'@shared/people'
], function() {
function createPersonDataFromJiraUser(jiraUser) {
return {
full_name: jiraUser.displayName,
email: jiraUser.email,
username: jiraUser.name,
avatar: jiraUser.avatarUrls ? jiraUser.avatarUrls['48x48'] : null
};
}
return {
/* @ngInject */
controller($rootScope, PeopleApi, PersonApi, JiraDataSource) {
this.importPerson = (jiraUser) => {
return JiraDataSource.getApiClient().user()
.get({
username: jiraUser.name
}, function(jiraUser) {
let personData = createPersonDataFromJiraUser(jiraUser);
let saveHandlers = [() => {
$rootScope.$broadcast('people-changed');
}, () => {
// todo: publish a global message.
}];
PersonApi.get({id: '@' + personData.username}).$promise
.then(person => {
Object.assign(person, personData);
person.$update({id: person.id}, ...saveHandlers);
}, () => {
PeopleApi.create(personData, ...saveHandlers);
});
});
};
},
templateUrl: 'dl-tools/components/import-people-from-jira/import-from-jira.tpl.html',
bindings: {
people: '<'
},
};
}); | define([
'@shared/people'
], function() {
function createPersonDataFromJiraUser(jiraUser) {
return {
full_name: jiraUser.displayName,
email: jiraUser.email,
username: jiraUser.name,
avatar: jiraUser.avatarUrls ? jiraUser.avatarUrls['48x48'] : null
};
}
return {
/* @ngInject */
controller($rootScope, PeopleApi, PersonApi, JiraDataSource) {
this.importPerson = (jiraUser) => {
return JiraDataService.getApiClient().user()
.get({
username: jiraUser.name
}, function(jiraUser) {
let personData = createPersonDataFromJiraUser(jiraUser);
let saveHandlers = [() => {
$rootScope.$broadcast('people-changed');
}, () => {
// todo: publish a global message.
}];
PersonApi.get({id: '@' + personData.username}).$promise
.then(person => {
Object.assign(person, personData);
person.$update({id: person.id}, ...saveHandlers);
}, () => {
PeopleApi.create(personData, ...saveHandlers);
});
});
};
},
templateUrl: 'dl-tools/components/import-people-from-jira/import-from-jira.tpl.html',
bindings: {
people: '<'
},
};
}); |
BAP-1626: Customize multi-step setup forms
- abstract step provides console command run interface | <?php
namespace Oro\Bundle\InstallerBundle\Process\Step;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\StreamOutput;
use Sylius\Bundle\FlowBundle\Process\Step\ControllerStep;
abstract class AbstractStep extends ControllerStep
{
/**
* @var Application
*/
protected $application;
/**
* @var StreamOutput
*/
protected $output;
/**
* Execute Symfony2 command
*
* @param string $command Command name (for example, "cache:clear")
* @param array $params [optional] Additional command parameters, like "--no-interaction", "--force" etc
*/
protected function runCommand($command, $params = array())
{
$params = array_merge($params, array('command' => $command, '--no-debug' => true));
$this->getApplication()->run(new ArrayInput($params), $this->output);
}
/**
* @return Application
*/
protected function getApplication()
{
if (!$this->application) {
$this->application = new Application($this->get('kernel'));
$this->output = new StreamOutput(
fopen(sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'bap_install.log', 'w')
);
$this->application->setAutoExit(false);
}
return $this->application;
}
}
| <?php
namespace Oro\Bundle\InstallerBundle\Process\Step;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\StreamOutput;
use Sylius\Bundle\FlowBundle\Process\Step\ControllerStep;
abstract class AbstractStep extends ControllerStep
{
/**
* @var Application
*/
protected $application;
/**
* @var StreamOutput
*/
protected $output;
/**
* Execute Symfony2 command
*
* @param string $command Command name (for example, "cache:clear")
* @param array $params [optional] Additional command parameters, like "--no-interaction", "--force" etc
*/
protected function runCommand($command, $params = array())
{
$params = array_merge($params, array('command' => $command, '--no-debug' => true));
$this->getApplication()->run(new ArrayInput($params), $this->output);
}
/**
* @return Application
*/
protected function getApplication()
{
if (!$this->application) {
$this->application = new Application($this->get('kernel'));
$this->output = new StreamOutput(
fopen(sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'bap_install.log', 'w')
);
$this->application->setAutoExit(false);
}
return $this->application;
}
} |
build(Build): Exclude giant, static JS files from transpilation. | 'use strict';
(() => {
module.exports = (gulp, plugins, config) => {
return () => {
return gulp.src([
`${config.patternsPath}/**/*.js`,
`!${config.patternsPath}/**/*.min.js`,
`!${config.patternsPath}/base/slipsum/**/*`
])
.pipe(plugins.changed(config.buildPath))
.pipe(plugins.plumber({
errorHandler: plugins.notify.onError('Error: <%= error.message %>')
}))
.pipe(plugins.rename({ suffix: '.min' }))
.pipe(plugins.sourcemaps.init())
.pipe(plugins.babel({
presets: [
['env', { 'modules': false }]
],
ignore: [
// Keep these files from breaking until they're refactored to ES6 code.
`${config.patternsPath}/components/dialogs/**/*.js`,
`${config.patternsPath}/components/buttons/rocketbelt.dynamic-button.js`
]
}))
.pipe(plugins.uglify())
.pipe(plugins.size(config.sizeOptions))
.pipe(plugins.sourcemaps.write('.', { sourceRoot: '.' }))
.pipe(gulp.dest(config.buildPath))
;
};
};
})();
| 'use strict';
(() => {
module.exports = (gulp, plugins, config) => {
return () => {
return gulp.src([`${config.patternsPath}/**/*.js`, `!${config.patternsPath}/**/*.min.js`])
.pipe(plugins.changed(config.buildPath))
.pipe(plugins.plumber({
errorHandler: plugins.notify.onError('Error: <%= error.message %>')
}))
.pipe(plugins.rename({ suffix: '.min' }))
.pipe(plugins.sourcemaps.init())
.pipe(plugins.babel({
presets: [
['env', { 'modules': false }]
],
ignore: [
// Keep these files from breaking until they're refactored to ES6 code.
`${config.patternsPath}/components/dialogs/**/*.js`,
`${config.patternsPath}/components/buttons/rocketbelt.dynamic-button.js`,
`${config.patternsPath}/base/slipsum/**/*.js(on)?`
]
}))
.pipe(plugins.uglify())
.pipe(plugins.size(config.sizeOptions))
.pipe(plugins.sourcemaps.write('.', { sourceRoot: '.' }))
.pipe(gulp.dest(config.buildPath))
;
};
};
})();
|
Move ValidationError messages to a dictionary that can be accessed from PinForm.clean | from django import forms
from .models import Pin
class PinForm(forms.ModelForm):
url = forms.CharField(required=False)
image = forms.ImageField(label='or Upload', required=False)
_errors = {
'not_image': 'Requested URL is not an image file. Only images are currently supported.',
'pinned': 'URL has already been pinned!',
'protocol': 'Currently only support HTTP and HTTPS protocols, please be sure you include this in the URL.',
'nothing': 'Need either a URL or Upload',
}
class Meta:
model = Pin
fields = ['url', 'image', 'description', 'tags']
def clean(self):
cleaned_data = super(PinForm, self).clean()
url = cleaned_data.get('url')
image = cleaned_data.get('image')
if url:
image_file_types = ['png', 'gif', 'jpeg', 'jpg']
if not url.split('.')[-1].lower() in image_file_types:
raise forms.ValidationError(self._errors['not_image'])
protocol = url.split(':')[0]
if protocol not in ['http', 'https']:
raise forms.ValidationError(self._errors['protocol'])
try:
Pin.objects.get(url=url)
raise forms.ValidationError(self._errors['pinned'])
except Pin.DoesNotExist:
pass
elif image:
pass
else:
raise forms.ValidationError(self._errors['nothing'])
return cleaned_data
| from django import forms
from .models import Pin
class PinForm(forms.ModelForm):
url = forms.CharField(required=False)
image = forms.ImageField(label='or Upload', required=False)
class Meta:
model = Pin
fields = ['url', 'image', 'description', 'tags']
def clean(self):
cleaned_data = super(PinForm, self).clean()
url = cleaned_data.get('url')
image = cleaned_data.get('image')
if url:
image_file_types = ['png', 'gif', 'jpeg', 'jpg']
if not url.split('.')[-1].lower() in image_file_types:
raise forms.ValidationError("Requested URL is not an image file. "
"Only images are currently supported.")
try:
Pin.objects.get(url=url)
raise forms.ValidationError("URL has already been pinned!")
except Pin.DoesNotExist:
pass
protocol = url.split(':')[0]
if protocol not in ['http', 'https']:
raise forms.ValidationError("Currently only support HTTP and "
"HTTPS protocols, please be sure "
"you include this in the URL.")
try:
Pin.objects.get(url=url)
raise forms.ValidationError("URL has already been pinned!")
except Pin.DoesNotExist:
pass
elif image:
pass
else:
raise forms.ValidationError("Need either a URL or Upload.")
return cleaned_data
|
Add examples to code style validation | 'use strict';
module.exports = function (gulp, $) {
gulp.task('scripts:setup', function () {
return gulp.src('source')
.pipe($.symlink('examples/source', { force: true }));
});
gulp.task('jscs', function () {
return gulp.src([
'source/**/*.js',
'examples/js/*.js'
])
.pipe($.jscs());
});
gulp.task('jshint', function () {
return gulp.src([
'source/**/*.js',
'examples/js/*.js'
])
.pipe($.jshint())
.pipe($.jshint.reporter('jshint-stylish'))
.pipe($.jshint.reporter('fail'));
});
gulp.task('concat', function () {
return gulp.src([
'source/**/*.js',
'!**/*.spec.js'
])
.pipe($.concat('angular-ui-tree.js'))
.pipe(gulp.dest('dist'));
});
gulp.task('uglify', ['concat'], function () {
return gulp.src('dist/angular-ui-tree.js')
.pipe($.uglify({
preserveComments: 'some'
}))
.pipe($.rename('angular-ui-tree.min.js'))
.pipe(gulp.dest('dist'));
});
gulp.task('test', function () {
return $.karma.server.start({
configFile: __dirname + '/../karma.conf.js',
singleRun: true
}, function (err) {
process.exit(err ? 1 : 0);
});
});
};
| 'use strict';
module.exports = function (gulp, $) {
gulp.task('scripts:setup', function () {
return gulp.src('source')
.pipe($.symlink('examples/source', { force: true }));
});
gulp.task('jscs', function () {
return gulp.src('source/**/*.js')
.pipe($.jscs());
});
gulp.task('jshint', function () {
return gulp.src([
'source/**/*.js'
])
.pipe($.jshint())
.pipe($.jshint.reporter('jshint-stylish'))
.pipe($.jshint.reporter('fail'));
});
gulp.task('concat', function () {
return gulp.src([
'source/**/*.js',
'!**/*.spec.js'
])
.pipe($.concat('angular-ui-tree.js'))
.pipe(gulp.dest('dist'));
});
gulp.task('uglify', ['concat'], function () {
return gulp.src('dist/angular-ui-tree.js')
.pipe($.uglify({
preserveComments: 'some'
}))
.pipe($.rename('angular-ui-tree.min.js'))
.pipe(gulp.dest('dist'));
});
gulp.task('test', function () {
return $.karma.server.start({
configFile: __dirname + '/../karma.conf.js',
singleRun: true
}, function (err) {
process.exit(err ? 1 : 0);
});
});
};
|
Allow switching template and display for field | /**
* Created by dmorina on 27/06/15.
*/
/**
* mdTemplateCompilerDirective
* @namespace crowdsource.template.directives
*/
(function () {
'use strict';
angular
.module('crowdsource.template.directives')
.directive('mdTemplateCompiler', mdTemplateCompilerDirective);
function mdTemplateCompilerDirective($parse, $sce, $compile, $timeout, Template) {
return {
restrict: 'A',
replace: true,
scope: {
mdTemplateCompiler: '=',
editor: '='
},
link: function (scope, element, attrs, ctrl) {
scope.item = scope.mdTemplateCompiler;
var templateComponents = Template.getTemplateComponents(scope);
function update(newField, oldField) {
var format = _.find(templateComponents, function (item) {
return item.type == newField.type;
});
if (newField.hasOwnProperty('isSelected') && newField.isSelected && scope.editor) {
newField.toView = format.toEditor;
} else {
newField.toView = format.toHTML;
}
// TODO: Make this more robust to handle any CSV format - with quotes, commas
if (newField.hasOwnProperty('choices') && _.isString(scope.item.choices)) {
var choices = scope.item.choices;
scope.item.options = String(choices).split(',').map(function (item) {
return _.trim(item);
})
}
var template = newField.toView();
var el = angular.element(template);
element.html(el);
$compile(el)(scope);
}
scope.editor = scope.editor || false;
scope.$watch('mdTemplateCompiler', function (newField, oldField) {
if (scope.editor) {
if (!newField.hasOwnProperty('isSelected') || newField.isSelected == undefined || newField.isSelected !== oldField.isSelected) {
update(newField, oldField);
}
} else {
update(newField, oldField);
}
}, scope.editor);
}
};
}
})(); | /**
* Created by dmorina on 27/06/15.
*/
/**
* mdTemplateCompilerDirective
* @namespace crowdsource.template.directives
*/
(function () {
'use strict';
angular
.module('crowdsource.template.directives')
.directive('mdTemplateCompiler', mdTemplateCompilerDirective);
function mdTemplateCompilerDirective($parse, $sce, $compile){
return {
restrict: 'A',
link: function(scope, element, attrs){
var item = $sce.parseAsHtml(attrs.mdTemplateCompiler);
var getItem = function () {
return item(scope);
};
scope.$watch(getItem, function (newValue) {
var template = angular.element(newValue);
var linkFn = $compile(template);
var el = linkFn(scope);
if (element.children().length){
$(element.children()[0]).replaceWith(el);
}
else {
element.append(el);
}
});
}
};
}
})(); |
Fix: Use st2common log and not logging | from datetime import timedelta
import eventlet
import sys
from threading import Thread
import time
from st2common import log as logging
# Constants
SUCCESS_EXIT_CODE = 0
eventlet.monkey_patch(
os=True,
select=True,
socket=True,
thread=False if '--use-debugger' in sys.argv else True,
time=True
)
LOG = logging.getLogger('st2reactor.sensor.container')
class SensorContainer(object):
__pool = None
__sensors = None
__threads = {}
def __init__(self, thread_pool_size=100, sensor_instances=[]):
self.__pool = eventlet.GreenPool(thread_pool_size)
self.__sensors = sensor_instances
def _run_sensor(self, sensor):
"""
XXX: sensor.init() needs to be called here.
"""
sensor.start()
def _sensor_cleanup(self, sensor):
sensor.stop()
def shutdown():
LOG.info('Container shutting down. Invoking cleanup on sensors.')
for sensor, gt in self.__threads.iteritems():
gt.kill()
self._sensor_cleanup(sensor)
LOG.info('All sensors are shut down.')
def run(self):
for sensor in self.__sensors:
LOG.info('Running sensor %s' % sensor.__class__.__name__)
gt = self.__pool.spawn(self._run_sensor, sensor)
self.__threads[sensor] = gt
self.__pool.waitall()
def main(self):
self.run()
LOG.info('Container has no active sensors running.')
return SUCCESS_EXIT_CODE
| from datetime import timedelta
import eventlet
import logging
import sys
from threading import Thread
import time
# Constants
SUCCESS_EXIT_CODE = 0
eventlet.monkey_patch(
os=True,
select=True,
socket=True,
thread=False if '--use-debugger' in sys.argv else True,
time=True
)
LOG = logging.getLogger('st2reactor.sensor.container')
class SensorContainer(object):
__pool = None
__sensors = None
__threads = {}
def __init__(self, thread_pool_size=100, sensor_instances=[]):
self.__pool = eventlet.GreenPool(thread_pool_size)
self.__sensors = sensor_instances
def _run_sensor(self, sensor):
"""
XXX: sensor.init() needs to be called here.
"""
sensor.start()
def _sensor_cleanup(self, sensor):
sensor.stop()
def shutdown():
LOG.info('Container shutting down. Invoking cleanup on sensors.')
for sensor, gt in self.__threads.iteritems():
gt.kill()
self._sensor_cleanup(sensor)
LOG.info('All sensors are shut down.')
def run(self):
for sensor in self.__sensors:
LOG.info('Running sensor %s' % sensor.__class__.__name__)
gt = self.__pool.spawn(self._run_sensor, sensor)
self.__threads[sensor] = gt
self.__pool.waitall()
def main(self):
self.run()
LOG.info('Container has no active sensors running.')
return SUCCESS_EXIT_CODE
|
Fix typo an suppored -> supported | # -*- coding: utf-8 -*-
'''
Manage PagerDuty users.
Example:
.. code-block:: yaml
ensure bruce test user 1:
pagerduty.user_present:
- name: 'Bruce TestUser1'
- email: [email protected]
- requester_id: P1GV5NT
'''
def __virtual__():
'''
Only load if the pygerduty module is available in __salt__
'''
return 'pagerduty_user' if 'pagerduty_util.get_resource' in __salt__ else False
def present(profile='pagerduty', subdomain=None, api_key=None, **kwargs):
'''
Ensure pagerduty user exists.
Arguments match those supported by
https://developer.pagerduty.com/documentation/rest/users/create.
'''
return __salt__['pagerduty_util.resource_present']('users',
['email', 'name', 'id'],
None,
profile,
subdomain,
api_key,
**kwargs)
def absent(profile='pagerduty', subdomain=None, api_key=None, **kwargs):
'''
Ensure pagerduty user does not exist.
Name can be pagerduty id, email address, or user name.
'''
return __salt__['pagerduty_util.resource_absent']('users',
['email', 'name', 'id'],
profile,
subdomain,
api_key,
**kwargs)
| # -*- coding: utf-8 -*-
'''
Manage PagerDuty users.
Example:
.. code-block:: yaml
ensure bruce test user 1:
pagerduty.user_present:
- name: 'Bruce TestUser1'
- email: [email protected]
- requester_id: P1GV5NT
'''
def __virtual__():
'''
Only load if the pygerduty module is available in __salt__
'''
return 'pagerduty_user' if 'pagerduty_util.get_resource' in __salt__ else False
def present(profile='pagerduty', subdomain=None, api_key=None, **kwargs):
'''
Ensure pagerduty user exists.
Arguments match those suppored by
https://developer.pagerduty.com/documentation/rest/users/create.
'''
return __salt__['pagerduty_util.resource_present']('users',
['email', 'name', 'id'],
None,
profile,
subdomain,
api_key,
**kwargs)
def absent(profile='pagerduty', subdomain=None, api_key=None, **kwargs):
'''
Ensure pagerduty user does not exist.
Name can be pagerduty id, email address, or user name.
'''
return __salt__['pagerduty_util.resource_absent']('users',
['email', 'name', 'id'],
profile,
subdomain,
api_key,
**kwargs)
|
Use latest cub widget js | <?php namespace Cub\CubLaravel;
use Config;
class CubWidget
{
/**
* Get Cub Widget header script
*
* @return string
*/
public function headerScript()
{
$script = '<script>'
. '(function(){'
. 'if (document.getElementById("cub-widget-script")) {return;}'
. 'var firstScript = document.getElementsByTagName("script")[0];'
. 'var cubJs = document.createElement("script");'
. 'cubJs.id = "cub-widget-script";'
. 'cubJs.src = "//cub-praetorian.netdna-ssl.com/cub-widget.0.17.x.js";'
. 'firstScript.parentNode.insertBefore(cubJs, firstScript);'
. '}());'
. '</script>';
return $script;
}
/**
* Get Cub Widget footer script
*
* @return string
*/
public function footerScript()
{
$script = '<script>'
. 'var cubAsyncInit = function(cub) {'
. 'cub.start({'
. 'apiKey: "'.Config::get('cub::config.public_key').'"'
. '});'
. '};'
. '</script>';
return $script;
}
/**
* Get Cub Widget menu element
*
* @return string
*/
public function menu()
{
return '<div id="cub-widget-menu"></div>';
}
/**
* Get Cub Widget app element
*
* @return string
*/
public function app()
{
return '<div id="cub-widget-app"></div>';
}
}
| <?php namespace Cub\CubLaravel;
use Config;
class CubWidget
{
/**
* Get Cub Widget header script
*
* @return string
*/
public function headerScript()
{
$script = '<script>'
. '(function(){'
. 'if (document.getElementById("cub-widget-script")) {return;}'
. 'var firstScript = document.getElementsByTagName("script")[0];'
. 'var cubJs = document.createElement("script");'
. 'cubJs.id = "cub-widget-script";'
. 'cubJs.src = "//cub-praetorian.netdna-ssl.com/cub-widget.js";'
. 'firstScript.parentNode.insertBefore(cubJs, firstScript);'
. '}());'
. '</script>';
return $script;
}
/**
* Get Cub Widget footer script
*
* @return string
*/
public function footerScript()
{
$script = '<script>'
. 'var cubAsyncInit = function(cub) {'
. 'cub.start({'
. 'apiKey: "'.Config::get('cub::config.public_key').'"'
. '});'
. '};'
. '</script>';
return $script;
}
/**
* Get Cub Widget menu element
*
* @return string
*/
public function menu()
{
return '<div id="cub-widget-menu"></div>';
}
/**
* Get Cub Widget app element
*
* @return string
*/
public function app()
{
return '<div id="cub-widget-app"></div>';
}
}
|
Create /login, /create routes for API | import sys
from flask import Flask, render_template, jsonify, request
import subprocess
from digitalocean import SSHKey, Manager
app = Flask(__name__)
@app.route('/login')
def login():
# Get from Chrome extension
token = request.args.get('token')
manager = Manager(token=token)
# Instantiate ``api`` object to setup authentication for DO API.
my_droplets = manager.get_all_droplets()
# Check for success
print(my_droplets)
user_ssh_key = request.args.get('ssh')
key = SSHKey(token='secretspecialuniquesnowflake',
name='uniquehostname',
public_key=user_ssh_key)
# key is created succesfully.
key.create()
@app.route('/create')
def create():
# Create Droplet
keys = manager.get_all_sshkeys()
droplet = digitalocean.Droplet(token="secretspecialuniquesnowflake",
name='DropletWithSSHKeys',
region='ams3', # Amster
image='ubuntu-14-04-x64', # Ubuntu 14.04 x64
size_slug='512mb', # 512MB
ssh_keys=keys, #Automatic conversion
backups=False)
droplet.create()
@app.route('/')
def index():
return 'Hello World'
def main():
app.run(host="0.0.0.0", debug=True)
if __name__ == '__main__':
sys.exit(main()) | import sys
from flask import Flask, render_template, jsonify, request
from digitalocean import SSHKey, Manager
app = Flask(__name__)
manager = Manager(token="24611cca29682d3d54f8208b67a47dbe8b6ea01b2c8103ba61150ece4b6259b6")
my_droplets = manager.get_all_droplets()
# Check for success
print(my_droplets)
# Get from Chrome extension
user_ssh_key = ''
key = SSHKey(token='secretspecialuniquesnowflake',
name='uniquehostname',
public_key=user_ssh_key)
# key is created succesfully.
key.create()
# Create Droplet
keys = manager.get_all_sshkeys()
droplet = digitalocean.Droplet(token="secretspecialuniquesnowflake",
name='DropletWithSSHKeys',
region='ams3', # Amster
image='ubuntu-14-04-x64', # Ubuntu 14.04 x64
size_slug='512mb', # 512MB
ssh_keys=keys, #Automatic conversion
backups=False)
droplet.create()
# Instantiate ``api`` object to setup authentication for DO API.
@app.route('/')
def index():
return 'Hello World'
def main():
app.run(host="0.0.0.0", debug=True)
if __name__ == '__main__':
sys.exit(main()) |
Fix flag delimiter support from 30ec188. | #!/usr/bin/env python
#coding=utf8
"""
This module contains functions used by a Dehacked table entry to filter certain values when reading or writing
them.
"""
import math
import re
def filter_thing_flags_read(value, table):
"""
Filters a thing's flags value.
Extended patches can use mnemonics for flag names, separated by plus signs.
@raise LookupError: if the value contains an unknown mnemonic.
"""
if value.isdigit() == True:
return value
items = re.split(r"[,+| \t\f\r]+", value)
out = 0
for item in items:
item = item.strip()
# Find the index of the flag mnemonic and convert it to a flag value.
flag = table.flags.get(item)
if flag is None:
raise LookupError('Ignoring unknown thing flag {}.'.format(item))
bit = int(math.pow(2, flag['index']))
out += bit
return out
def filter_thing_flags_write(value, table):
"""
Returns a thing flags value as a string of mnemonics.
"""
bit = 1
out = []
for _ in range(0, 32):
if (value & bit) == 0:
bit *= 2
continue
for key, flag in table.flags.iteritems():
if int(math.pow(2, flag['index'])) == bit:
out.append(key)
break
bit *= 2
if len(out) == 0:
return 0
else:
return '+'.join(out) | #!/usr/bin/env python
#coding=utf8
"""
This module contains functions used by a Dehacked table entry to filter certain values when reading or writing
them.
"""
import math
import re
def filter_thing_flags_read(value, table):
"""
Filters a thing's flags value.
Extended patches can use mnemonics for flag names, separated by plus signs.
@raise LookupError: if the value contains an unknown mnemonic.
"""
items = re.split(r"[,+| \t\f\r]+", value)
if len(items) <= 1 and value.isalpha() == True:
return value
out = 0
for item in items:
item = item.strip()
# Find the index of the flag mnemonic and convert it to a flag value.
flag = table.flags.get(item)
if flag is None:
raise LookupError('Ignoring unknown thing flag {}.'.format(item))
bit = int(math.pow(2, flag['index']))
out += bit
return out
def filter_thing_flags_write(value, table):
"""
Returns a thing flags value as a string of mnemonics.
"""
bit = 1
out = []
for _ in range(0, 32):
if (value & bit) == 0:
bit *= 2
continue
for key, flag in table.flags.iteritems():
if int(math.pow(2, flag['index'])) == bit:
out.append(key)
break
bit *= 2
if len(out) == 0:
return 0
else:
return '+'.join(out) |
Switch to using MySQL Prepared Statements | <?php
require('DB_Config.php');
require('Encrypt.class.php');
class Authenticate {
private $mysqli;
//Get the table structure from DB_Config
private $usertable = TABLE_OF_USERS;
private $usercol = COLUMN_OF_USERS;
private $passwordcol = COLUMN_OF_PASSWORDS;
function __construct()
{
$mysqli = new mysqli(HOST, DB_USERNAME, DB_PASSWORD, DATABASE_NAME);
$this -> mysqli = $mysqli;
}
function login($username, $password)
{
//Check variables exist
if(empty($username) || empty($password))
{
return FALSE;
}
//Fetch password from database
$stmt = $this -> mysqli -> prepare("SELECT {$this -> passwordcol} FROM {$this -> usertable} WHERE {$this -> usercol} = ?");
$stmt -> bind_param('s', $username);
$stmt -> execute();
$stmt -> bind_result($hash);
$stmt -> fetch();
//Check if the password hashes match
$encrypt = new Encrypt(12, FALSE);
if($encrypt -> checkpassword($password, $hash))
{
return TRUE;
}
}
function createUser($username, $password, $confirmpassword, $email)
{
}
function logout()
{
session_destroy();
}
function resetPassword($username, $email)
{
}
function changePassword($username, $password, $newpassword, $confirmnewpassword)
{
}
}
?> | <?php
require('DB_Config.php');
require('Encrypt.class.php');
class Authenticate {
private $mysqli;
//Get the table structure from DB_Config
private $usertable = TABLE_OF_USERS;
private $usercol = COLUMN_OF_USERS;
private $passwordcol = COLUMN_OF_PASSWORDS;
function __construct()
{
$mysqli = new mysqli(HOST, DB_USERNAME, DB_PASSWORD, DATABASE_NAME);
$this -> mysqli = $mysqli;
}
function login($username, $password)
{
//Fetch username and password from database
$query ="SELECT {$this -> usercol}, {$this -> passwordcol} FROM {$this -> usertable} WHERE {$this -> usercol} = '$username'";
$result = $this -> mysqli -> query($query);
$row = $result -> fetch_assoc();
$hash = $row['password'];
$encrypt = new Encrypt(12, FALSE);
if($encrypt -> checkpassword($password, $hash))
{
return TRUE;
}
}
function createUser($username, $password, $confirmpassword, $email)
{
}
function logout()
{
session_destroy();
}
function resetPassword($username, $email)
{
}
function isUserActive($active)
{
}
function changePassword($username, $password, $newpassword, $confirmnewpassword)
{
}
}
?> |
Increase max accepted size of recommendation field | <?php
namespace RadDB\Http\Requests;
use Illuminate\Http\Request;
use Illuminate\Foundation\Http\FormRequest;
class StoreRecommendationRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules(Request $request)
{
// Build the validation rules
$rules = [
'surveyId' => 'required|exists:testdates,id|integer',
'recommendation' => 'required|string|max:1000',
'resolved' => 'integer',
'WONum' => 'string|nullable|max:20',
'ServiceReport' => 'file|mimes:pdf',
];
// If 'resolved' was checked, then add validation rules for
// 'RecResolveDate' and 'ResolvedBy'.
if ($request->filled('resolved')) {
$rules['RecResolveDate'] = 'required|date_format:Y-m-d';
$rules['ResolvedBy'] = 'required|string|max:10';
}
return $rules;
}
}
| <?php
namespace RadDB\Http\Requests;
use Illuminate\Http\Request;
use Illuminate\Foundation\Http\FormRequest;
class StoreRecommendationRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules(Request $request)
{
// Build the validation rules
$rules = [
'surveyId' => 'required|exists:testdates,id|integer',
'recommendation' => 'required|string|max:500',
'resolved' => 'integer',
'WONum' => 'string|nullable|max:20',
'ServiceReport' => 'file|mimes:pdf',
];
// If 'resolved' was checked, then add validation rules for
// 'RecResolveDate' and 'ResolvedBy'.
if ($request->filled('resolved')) {
$rules['RecResolveDate'] = 'required|date_format:Y-m-d';
$rules['ResolvedBy'] = 'required|string|max:10';
}
return $rules;
}
}
|
Support for python3.5 has been added for configparser | # Copyright 2017 <[email protected]>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import logging
try:
import configparser
except ImportError:
import ConfigParser as configparser
from nirikshak.common import plugins
from nirikshak.workers import base
LOG = logging.getLogger(__name__)
@plugins.register('ini')
class INIConfigValidatorWorker(base.Worker):
@base.match_expected_output
@base.validate(required=('file', 'section', 'key'))
def work(self, **kwargs):
k = kwargs['input']['args']
config = configparser.ConfigParser()
config.read(k['file'])
value = None
try:
value = config.get(k['section'], k['key'])
LOG.info("%s configuration option found in %s section",
k['section'], k['key'])
except Exception:
LOG.error("Not able to find %s configuration parameter in %s "
"section", k['key'], k['section'], exc_info=True)
return value
| # Copyright 2017 <[email protected]>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import logging
import configparser
from nirikshak.common import plugins
from nirikshak.workers import base
LOG = logging.getLogger(__name__)
@plugins.register('ini')
class INIConfigValidatorWorker(base.Worker):
@base.match_expected_output
@base.validate(required=('file', 'section', 'key'))
def work(self, **kwargs):
k = kwargs['input']['args']
config = configparser.ConfigParser()
config.read(k['file'])
value = None
try:
value = config.get(k['section'], k['key'])
LOG.info("%s configuration option found in %s section",
k['section'], k['key'])
except Exception:
LOG.error("Not able to find %s configuration parameter in %s "
"section", k['key'], k['section'], exc_info=True)
return value
|
Implement cacheKeyFn and fix lint | import DataLoader from 'dataloader';
import client from 'util/client';
export default () =>
new DataLoader(
async categoryQueries => {
const body = [];
categoryQueries.forEach(({ id, first, before, after }) => {
// TODO error independently?
if (before && after) {
throw new Error('Use of before & after is prohibited.');
}
body.push({ index: 'articles', type: 'doc' });
body.push({
query: {
nested: {
path: 'articleCategories',
query: {
term: {
'articleCategories.categoryId': id,
},
},
},
},
size: first ? first : 10,
sort: before ? [{ updatedAt: 'desc' }] : [{ updatedAt: 'asc' }],
search_after: before || after ? before || after : undefined,
});
});
return (await client.msearch({
body,
})).responses.map(({ hits }, idx) => {
if (!hits || !hits.hits) return [];
const categoryId = categoryQueries[idx].id;
return hits.hits.map(({ _id, _source: { articleCategories } }) => {
// Find corresponding articleCategory and insert articleId
//
const articleCategory = articleCategories.find(
articleCategory => articleCategory.categoryId === categoryId
);
articleCategory.articleId = _id;
return articleCategory;
});
});
},
{
cacheKeyFn: ({ id, first, before, after }) =>
`/${id}/${first}/${before}/${after}`,
}
);
| import DataLoader from 'dataloader';
import client from 'util/client';
export default () =>
new DataLoader(async categoryQueries => {
const body = [];
categoryQueries.forEach(({ id, first, before, after }) => {
// TODO error independently?
if (before && after) {
throw new Error('Use of before & after is prohibited.');
}
body.push({ index: 'articles', type: 'doc' });
body.push({
query: {
nested: {
path: 'articleCategories',
query: {
term: {
'articleCategories.categoryId': id,
},
},
},
},
size: first ? first : 10,
sort: before ? [{ updatedAt: 'desc' }] : [{ updatedAt: 'asc' }],
search_after: before || after ? before || after : undefined,
});
});
return (await client.msearch({
body,
})).responses.map(({ hits }, idx) => {
if (!hits || !hits.hits) return [];
const categoryId = categoryQueries[idx].id;
return hits.hits.map(({ _id, _source: { articleCategories } }) => {
// Find corresponding articleCategory and insert articleId
//
const articleCategory = articleCategories.find(
articleCategory => articleCategory.categoryId === categoryId
);
articleCategory.articleId = _id;
return articleCategory;
});
});
});
|
Create backtrace log file instead of dumping backtrace | <?php
/**
* Part of Cli for CodeIgniter
*
* @author Kenji Suzuki <https://github.com/kenjis>
* @license MIT License
* @copyright 2015 Kenji Suzuki
* @link https://github.com/kenjis/codeigniter-cli
*/
namespace Kenjis\CodeIgniter_Cli\Command;
use Aura\Cli\Stdio;
use Aura\Cli\Context;
use CI_Controller;
use RuntimeException;
abstract class Command
{
protected $context;
protected $stdio;
protected $ci;
protected $db;
protected $dbforge;
public function __construct(Context $context, Stdio $stdio, CI_Controller $ci)
{
$this->context = $context;
$this->stdio = $stdio;
$this->ci = $ci;
$this->ci->load->database();
$this->db = $this->ci->db;
$this->ci->load->dbforge();
$this->dbforge = $this->ci->dbforge;
}
public function __get($property)
{
if (! property_exists($this->ci, $property)) {
ob_start();
var_dump(debug_backtrace());
$backtrace = ob_get_clean();
file_put_contents(ROOTPATH . '/tmp/backtrace.log', $backtrace, LOCK_EX);
$this->stdio->errln(
'<<red>>No such property: ' . $property . ' in CodeIgniter instance<<reset>>'
);
$this->stdio->errln('Backtrace was saved in tmp/backtrace.log');
throw new RuntimeException('Property does not exist');
}
return $this->ci->$property;
}
}
| <?php
/**
* Part of Cli for CodeIgniter
*
* @author Kenji Suzuki <https://github.com/kenjis>
* @license MIT License
* @copyright 2015 Kenji Suzuki
* @link https://github.com/kenjis/codeigniter-cli
*/
namespace Kenjis\CodeIgniter_Cli\Command;
use Aura\Cli\Stdio;
use Aura\Cli\Context;
use CI_Controller;
use RuntimeException;
abstract class Command
{
protected $context;
protected $stdio;
protected $ci;
protected $db;
protected $dbforge;
public function __construct(Context $context, Stdio $stdio, CI_Controller $ci)
{
$this->context = $context;
$this->stdio = $stdio;
$this->ci = $ci;
$this->ci->load->database();
$this->db = $this->ci->db;
$this->ci->load->dbforge();
$this->dbforge = $this->ci->dbforge;
}
public function __get($property)
{
if (! property_exists($this->ci, $property)) {
var_dump(debug_backtrace());
$this->stdio->errln(
'<<red>>No such property: ' . $property . ' in CodeIgniter instance<<reset>>'
);
throw new RuntimeException('Property does not exist');
}
return $this->ci->$property;
}
}
|
Print the stack with the latest atom at the top | package net.jloop.rejoice;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
public class Stack implements Iterable<Atom> {
private final ArrayList<Atom> atoms;
public Stack() {
this.atoms = new ArrayList<>();
}
public Stack(ArrayList<Atom> atoms) {
this.atoms = atoms;
}
private int lastIndex() {
return atoms.size() - 1;
}
public <V extends Atom> V peek(Class<V> type) {
Atom atom = atoms.get(lastIndex());
if (!type.isInstance(atom)) {
throw new RuntimeException("Expecting type " + type + " but found " + atom.getClass());
} else {
return type.cast(atom);
}
}
public <V extends Atom> V consume(Class<V> type) {
V atom = peek(type);
this.pop();
return atom;
}
public Stack push(Atom atom) {
atoms.add(atom);
return this;
}
public Stack pushAll(Stack stack) {
for (Atom atom : stack) {
atoms.add(atom);
}
return this;
}
public Stack pop() {
atoms.remove(lastIndex());
return this;
}
public void print() {
ArrayList<Atom> list = new ArrayList<>(atoms);
Collections.reverse(list);
for (Atom atom : list) {
System.out.println(atom.print());
}
}
public Stack copy() {
// This is a shallow copy
return new Stack(new ArrayList<>(atoms));
}
@Override
public Iterator<Atom> iterator() {
return atoms.iterator();
}
}
| package net.jloop.rejoice;
import java.util.ArrayList;
import java.util.Iterator;
public class Stack implements Iterable<Atom> {
private final ArrayList<Atom> atoms;
public Stack() {
this.atoms = new ArrayList<>();
}
public Stack(ArrayList<Atom> atoms) {
this.atoms = atoms;
}
private int lastIndex() {
return atoms.size() - 1;
}
public <V extends Atom> V peek(Class<V> type) {
Atom atom = atoms.get(lastIndex());
if (!type.isInstance(atom)) {
throw new RuntimeException("Expecting type " + type + " but found " + atom.getClass());
} else {
return type.cast(atom);
}
}
public <V extends Atom> V consume(Class<V> type) {
V atom = peek(type);
this.pop();
return atom;
}
public Stack push(Atom atom) {
atoms.add(atom);
return this;
}
public Stack pushAll(Stack stack) {
for (Atom atom : stack) {
atoms.add(atom);
}
return this;
}
public Stack pop() {
atoms.remove(lastIndex());
return this;
}
public void print() {
for (Atom atom : atoms) {
System.out.println(atom.print());
}
}
public Stack copy() {
// This is a shallow copy
return new Stack(new ArrayList<>(atoms));
}
@Override
public Iterator<Atom> iterator() {
return atoms.iterator();
}
}
|
Fix (Dashboard Account): add newline end of file | <?php
namespace AppBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
class AccountType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('private', CheckboxType::class, array(
'label' => false,
'required' => false,
'attr' => array( 'class' => 'filled-in')
))
->remove('newsletter')
->add('newsletter', CheckboxType::class, array(
'mapped' => false,
'label' => false,
'required' => false,
'attr' => array( 'class' => 'filled-in')
))
->get('plainPassword')->setRequired(false)
;
}
public function setDefaultOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'error_bubbling' => true
));
}
public function getParent()
{
return RegisterType::class;
}
}
| <?php
namespace AppBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
class AccountType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('private', CheckboxType::class, array(
'label' => false,
'required' => false,
'attr' => array( 'class' => 'filled-in')
))
->remove('newsletter')
->add('newsletter', CheckboxType::class, array(
'mapped' => false,
'label' => false,
'required' => false,
'attr' => array( 'class' => 'filled-in')
))
->get('plainPassword')->setRequired(false)
;
}
public function setDefaultOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'error_bubbling' => true
));
}
public function getParent()
{
return RegisterType::class;
}
} |
Fix search Directories for LinkTag-News | <?php
class Kwc_Basic_LinkTag_News_DirectoriesController extends Kwf_Controller_Action_Auto_Grid
{
protected function _initColumns()
{
$this->_columns->add(new Kwf_Grid_Column('id'));
$this->_columns->add(new Kwf_Grid_Column('name'));
if ($this->_getParam('id')) {
$subRootComponentId = $this->_getParam('id');
} else if ($this->_getParam('parent_id')) {
$subRootComponentId = $this->_getParam('parent_id');
} else if ($this->_getParam('componentId')) {
$subRootComponentId = $this->_getParam('componentId');
} else {
throw new Kwf_Exception("componentId, id or parent_id required");
}
$subroot = Kwf_Component_Data_Root::getInstance()->getComponentById($subRootComponentId, array('ignoreVisible' => true));
$data = array();
$classes = Kwc_Admin::getInstance($this->_getParam('class'))->getDirectoryComponentClasses();
$news = Kwf_Component_Data_Root::getInstance()
->getComponentsBySameClass($classes, array('subroot'=>$subroot, 'ignoreVisible'=>true));
foreach ($news as $new) {
$data[] = array(
'id' => $new->dbId,
'name' => $new->getTitle(),
);
}
$this->_model = new Kwf_Model_FnF(array(
'data' => $data
));
parent::_initColumns();
}
protected function _isAllowedComponent()
{
return !!Kwf_Registry::get('userModel')->getAuthedUser();
}
}
| <?php
class Kwc_Basic_LinkTag_News_DirectoriesController extends Kwf_Controller_Action_Auto_Grid
{
protected function _initColumns()
{
$this->_columns->add(new Kwf_Grid_Column('id'));
$this->_columns->add(new Kwf_Grid_Column('name'));
if ($this->_getParam('id')) {
$subRootComponentId = $this->_getParam('id');
} else if ($this->_getParam('parent_id')) {
$subRootComponentId = $this->_getParam('parent_id');
} else if ($this->_getParam('componentId')) {
$subRootComponentId = $this->_getParam('componentId');
} else {
throw new Kwf_Exception("componentId, id or parent_id required");
}
$subroot = Kwf_Component_Data_Root::getInstance()->getComponentById($subRootComponentId);
$data = array();
$classes = Kwc_Admin::getInstance($this->_getParam('class'))->getDirectoryComponentClasses();
$news = Kwf_Component_Data_Root::getInstance()
->getComponentsBySameClass($classes, array('subroot'=>$subroot, 'ignoreVisible'=>true));
foreach ($news as $new) {
$data[] = array(
'id' => $new->dbId,
'name' => $new->getTitle(),
);
}
$this->_model = new Kwf_Model_FnF(array(
'data' => $data
));
parent::_initColumns();
}
protected function _isAllowedComponent()
{
return !!Kwf_Registry::get('userModel')->getAuthedUser();
}
}
|
Check if string before decoding | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import json
import six
import websocket
from polyaxon_client.logger import logger
class SocketTransportMixin(object):
"""Socket operations transport."""
def socket(self, url, message_handler, headers=None):
webs = websocket.WebSocketApp(
url,
on_message=lambda ws, message: self._on_message(message_handler, message),
on_error=self._on_error,
on_close=self._on_close,
header=self._get_headers(headers)
)
return webs
def stream(self, url, message_handler, headers=None):
webs = self.socket(url=url, message_handler=message_handler, headers=headers)
webs.run_forever(ping_interval=30, ping_timeout=10)
def _on_message(self, message_handler, message):
if message_handler and message:
if not isinstance(message, six.string_types):
message = message.decode('utf-8')
message_handler(json.loads(message))
@staticmethod
def _on_error(ws, error):
if isinstance(error, (KeyboardInterrupt, SystemExit)):
logger.info('Quitting... The session will be running in the background.')
else:
logger.debug('Termination cause: %s', error)
logger.debug('Session disconnected.')
@staticmethod
def _on_close(ws):
logger.info('Session ended')
| # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import json
import websocket
from polyaxon_client.logger import logger
class SocketTransportMixin(object):
"""Socket operations transport."""
def socket(self, url, message_handler, headers=None):
webs = websocket.WebSocketApp(
url,
on_message=lambda ws, message: self._on_message(message_handler, message),
on_error=self._on_error,
on_close=self._on_close,
header=self._get_headers(headers)
)
return webs
def stream(self, url, message_handler, headers=None):
webs = self.socket(url=url, message_handler=message_handler, headers=headers)
webs.run_forever(ping_interval=30, ping_timeout=10)
def _on_message(self, message_handler, message):
if message_handler and message:
message_handler(json.loads(message.decode('utf-8')))
@staticmethod
def _on_error(ws, error):
if isinstance(error, (KeyboardInterrupt, SystemExit)):
logger.info('Quitting... The session will be running in the background.')
else:
logger.debug('Termination cause: %s', error)
logger.debug('Session disconnected.')
@staticmethod
def _on_close(ws):
logger.info('Session ended')
|
Clean DO sidebar METS data on failure | (function () {
'use strict';
angular.module('drmc.directives').directive('arDigitalObjectViewerSidebar', function (SETTINGS, InformationObjectService, ModalDigitalObjectViewerService) {
return {
restrict: 'E',
templateUrl: SETTINGS.viewsPath + '/partials/digital-object-viewer-sidebar.html',
scope: {
file: '=',
_close: '&onClose'
},
replace: true,
link: function (scope) {
scope.showAipsArea = true;
scope.showCharacterizationArea = true;
scope.showMediaArea = false;
scope.$watch('file', function (value) {
InformationObjectService.getMets(value.id).then(function (response) {
scope.mets = response.data;
}, function () {
scope.mets = [];
});
if (angular.isDefined(value.media_type_id)) {
var mt = ModalDigitalObjectViewerService.mediaTypes[value.media_type_id];
if (angular.isDefined(mt) && angular.isDefined(mt.class)) {
scope.mediaType = ModalDigitalObjectViewerService.mediaTypes[value.media_type_id].class;
}
}
});
scope.close = function () {
scope._close();
};
}
};
});
})();
| (function () {
'use strict';
angular.module('drmc.directives').directive('arDigitalObjectViewerSidebar', function (SETTINGS, InformationObjectService, ModalDigitalObjectViewerService) {
return {
restrict: 'E',
templateUrl: SETTINGS.viewsPath + '/partials/digital-object-viewer-sidebar.html',
scope: {
file: '=',
_close: '&onClose'
},
replace: true,
link: function (scope) {
scope.showAipsArea = true;
scope.showCharacterizationArea = true;
scope.showMediaArea = false;
scope.$watch('file', function (value) {
InformationObjectService.getMets(value.id).then(function (response) {
scope.mets = response.data;
});
if (angular.isDefined(value.media_type_id)) {
var mt = ModalDigitalObjectViewerService.mediaTypes[value.media_type_id];
if (angular.isDefined(mt) && angular.isDefined(mt.class)) {
scope.mediaType = ModalDigitalObjectViewerService.mediaTypes[value.media_type_id].class;
}
}
});
scope.close = function () {
scope._close();
};
}
};
});
})();
|
Swap out Q for Promise and remove superfluous StatsD. | // Copyright 2014-2015, Renasar Technologies Inc.
/* jshint node: true */
"use strict";
var di = require('di');
module.exports = Runner;
di.annotate(Runner, new di.Provide('Http'));
di.annotate(Runner, new di.Inject(
'Http.Server',
'Services.Core',
'Services.Configuration',
'Profiles',
'Templates',
'common-api-router',
'fileService',
'Promise'
)
);
function Runner(
app,
core,
configuration,
profiles,
templates,
router,
fileService,
Promise
) {
function start() {
return core.start()
.then(function() {
return Promise.all([profiles.load(), templates.load()]);
})
.then(function() {
app.use('/api/common', router);
app.use('/api/current', router);
app.use('/api/1.1', router);
return fileService.start(configuration.get("fileService"));
})
.then(function() {
app.listen();
});
}
function stop() {
return Promise.resolve()
.then(function() {
return app.close();
})
.then(function() {
return core.stop();
});
}
return {
start: start,
stop: stop
};
}
| // Copyright 2014-2015, Renasar Technologies Inc.
/* jshint node: true */
"use strict";
var di = require('di');
module.exports = Runner;
di.annotate(Runner, new di.Provide('Http'));
di.annotate(Runner, new di.Inject(
'Http.Server',
'Services.Core',
'Services.Configuration',
'Profiles',
'Templates',
'common-api-router',
'fileService',
'Q',
'Services.StatsD'
)
);
function Runner(
app,
core,
configuration,
profiles,
templates,
router,
fileService,
Q,
statsd
) {
function start() {
return core.start()
.then(function() {
return Q.all([profiles.load(), templates.load()]);
})
.then(function() {
statsd.gauge('hello.world', 1);
console.log('metric sent');
app.use('/api/common', router);
app.use('/api/current', router);
app.use('/api/1.1', router);
return fileService.start(configuration.get("fileService"));
})
.then(function() {
app.listen();
});
}
function stop() {
return Q.resolve()
.then(function() {
return app.close();
})
.then(function() {
return core.stop();
});
}
return {
start: start,
stop: stop
};
}
|
comment_parser: Add __repr__ to Comment class. | #!/usr/bin/python
"""This module provides constructs common to all comment parsers."""
class Error(Exception):
"""Base Error class for all comment parsers."""
pass
class FileError(Error):
"""Raised if there is an issue reading a given file."""
pass
class UnterminatedCommentError(Error):
"""Raised if an Unterminated multi-line comment is encountered."""
pass
class Comment(object):
"""Represents comments found in source files."""
def __init__(self, text, line_number, multiline=False):
"""Initializes Comment.
Args:
text: String text of comment.
line_number: Line number (int) comment was found on.
multiline: Boolean whether this comment was a multiline comment.
"""
self._text = text
self._line_number = line_number
self._multiline = multiline
def text(self):
"""Returns the comment's text.
Returns:
String
"""
return self._text
def line_number(self):
"""Returns the line number the comment was found on.
Returns:
Int
"""
return self._line_number
def is_multiline(self):
"""Returns whether this comment was a multiline comment.
Returns:
True if comment was a multiline comment, False if not.
"""
return self._multiline
def __str__(self):
return self._text
def __repr__(self):
return 'Comment(%s, %d, %s)' % (
self._text, self._line_number, self._multiline)
def __eq__(self, other):
if isinstance(other, self.__class__):
if self.__dict__ == other.__dict__:
return True
return False
| #!/usr/bin/python
"""This module provides constructs common to all comment parsers."""
class Error(Exception):
"""Base Error class for all comment parsers."""
pass
class FileError(Error):
"""Raised if there is an issue reading a given file."""
pass
class UnterminatedCommentError(Error):
"""Raised if an Unterminated multi-line comment is encountered."""
pass
class Comment(object):
"""Represents comments found in source files."""
def __init__(self, text, line_number, multiline=False):
"""Initializes Comment.
Args:
text: String text of comment.
line_number: Line number (int) comment was found on.
multiline: Boolean whether this comment was a multiline comment.
"""
self._text = text
self._line_number = line_number
self._multiline = multiline
def text(self):
"""Returns the comment's text.
Returns:
String
"""
return self._text
def line_number(self):
"""Returns the line number the comment was found on.
Returns:
Int
"""
return self._line_number
def is_multiline(self):
"""Returns whether this comment was a multiline comment.
Returns:
True if comment was a multiline comment, False if not.
"""
return self._multiline
def __str__(self):
return self._text
def __eq__(self, other):
if isinstance(other, self.__class__):
if self.__dict__ == other.__dict__:
return True
return False
|
Use abspath for COPY command | import os
import glob
from django.apps import apps
from django.db import connection
from django.core.management.base import BaseCommand
class Command(BaseCommand):
"""
Turn off auto system check for all apps
We will maunally run system checks only for the
'addressbase' and 'pollingstations' apps
"""
requires_system_checks = False
def add_arguments(self, parser):
parser.add_argument(
'cleaned_ab_path',
help='The path to the folder containing the cleaned AddressBase CSVs'
)
def handle(self, *args, **kwargs):
"""
Manually run system checks for the
'addressbase' and 'pollingstations' apps
Management commands can ignore checks that only apply to
the apps supporting the website part of the project
"""
self.check([
apps.get_app_config('addressbase'),
apps.get_app_config('pollingstations')
])
glob_str = os.path.join(
kwargs['cleaned_ab_path'],
"*_cleaned.csv"
)
for cleaned_file_path in glob.glob(glob_str):
cleaned_file_path = os.path.abspath(cleaned_file_path)
print(cleaned_file_path)
cursor = connection.cursor()
cursor.execute("""
COPY addressbase_address (UPRN,address,postcode,location)
FROM '{}' (FORMAT CSV, DELIMITER ',', quote '"');
""".format(cleaned_file_path))
| import os
import glob
from django.apps import apps
from django.db import connection
from django.core.management.base import BaseCommand
class Command(BaseCommand):
"""
Turn off auto system check for all apps
We will maunally run system checks only for the
'addressbase' and 'pollingstations' apps
"""
requires_system_checks = False
def add_arguments(self, parser):
parser.add_argument(
'cleaned_ab_path',
help='The path to the folder containing the cleaned AddressBase CSVs'
)
def handle(self, *args, **kwargs):
"""
Manually run system checks for the
'addressbase' and 'pollingstations' apps
Management commands can ignore checks that only apply to
the apps supporting the website part of the project
"""
self.check([
apps.get_app_config('addressbase'),
apps.get_app_config('pollingstations')
])
glob_str = os.path.join(
kwargs['cleaned_ab_path'],
"*_cleaned.csv"
)
for cleaned_file_path in glob.glob(glob_str):
print(cleaned_file_path)
cursor = connection.cursor()
cursor.execute("""
COPY addressbase_address (UPRN,address,postcode,location)
FROM '{}' (FORMAT CSV, DELIMITER ',', quote '"');
""".format(cleaned_file_path))
|
Fix true test, add false test | class TestEnumberable(object):
def test_inject(self, ec):
w_res = ec.space.execute(ec, """
return (5..10).inject(1) do |prod, n|
prod * n
end
""")
assert ec.space.int_w(w_res) == 15120
w_res = ec.space.execute(ec, """
return (1..10).inject 0 do |sum, n|
sum + n
end
""")
assert ec.space.int_w(w_res) == 45
def test_each_with_index(self, ec):
w_res = ec.space.execute(ec, """
result = []
(5..10).each_with_index do |n, idx|
result << [n, idx]
end
return result
""")
assert [[ec.space.int_w(w_x) for w_x in ec.space.listview(w_sub)] for w_sub in ec.space.listview(w_res)] == [[5, 0], [6, 1], [7, 2], [8, 3], [9, 4]]
def test_all(self, ec):
w_res = ec.space.execute(ec, """
return ["ant", "bear", "cat"].all? do |word|
word.length >= 3
end
""")
assert w_res is ec.space.w_true
def test_all_false(self, ec):
w_res = ec.space.execute(ec, """
return ["ant", "bear", "cat"].all? do |word|
word.length >= 4
end
""")
assert w_res is ec.space.w_false
| class TestEnumberable(object):
def test_inject(self, ec):
w_res = ec.space.execute(ec, """
return (5..10).inject(1) do |prod, n|
prod * n
end
""")
assert ec.space.int_w(w_res) == 15120
w_res = ec.space.execute(ec, """
return (1..10).inject 0 do |sum, n|
sum + n
end
""")
assert ec.space.int_w(w_res) == 45
def test_each_with_index(self, ec):
w_res = ec.space.execute(ec, """
result = []
(5..10).each_with_index do |n, idx|
result << [n, idx]
end
return result
""")
assert [[ec.space.int_w(w_x) for w_x in ec.space.listview(w_sub)] for w_sub in ec.space.listview(w_res)] == [[5, 0], [6, 1], [7, 2], [8, 3], [9, 4]]
def test_all(self, ec):
w_res = ec.space.execute(ec, """
return ["ant", "bear", "cat"].all? do |word|
word.length >= 3
end
""")
assert ec.space.w_true
|
Add a method for line by line asset parsing | class Asset:
"""
This is an ooni-probe asset. It is a python
iterator object, allowing it to be efficiently looped.
To create your own custom asset your should subclass this
and override the next_asset method and the len method for
computing the length of the asset.
"""
def __init__(self, file=None, *args, **argv):
self.fh = None
if file:
self.name = file
self.fh = open(file, 'r')
self.eof = False
def __iter__(self):
return self
def len(self):
"""
Returns the length of the asset
"""
for i, l in enumerate(self.fh):
pass
# rewind the file
self.fh.seek(0)
return i + 1
def parse_line(self, line):
"""
Override this method if you need line
by line parsing of an Asset.
"""
return line.replace('\n','')
def next_asset(self):
"""
Return the next asset.
"""
# XXX this is really written with my feet.
# clean me up please...
line = self.fh.readline()
if line:
parsed_line = self.parse_line(line)
if parsed_line:
return parsed_line
else:
self.fh.seek(0)
raise StopIteration
def next(self):
try:
return self.next_asset()
except:
raise StopIteration
| class Asset:
"""
This is an ooni-probe asset. It is a python
iterator object, allowing it to be efficiently looped.
To create your own custom asset your should subclass this
and override the next_asset method and the len method for
computing the length of the asset.
"""
def __init__(self, file=None, *args, **argv):
self.fh = None
if file:
self.name = file
self.fh = open(file, 'r')
self.eof = False
def __iter__(self):
return self
def len(self):
"""
Returns the length of the asset
"""
for i, l in enumerate(self.fh):
pass
# rewind the file
self.fh.seek(0)
return i + 1
def parse_line(self, line):
"""
Override this method if you need line
by line parsing of an Asset.
"""
return line.replace('\n','')
def next_asset(self):
"""
Return the next asset.
"""
# XXX this is really written with my feet.
# clean me up please...
line = self.fh.readline()
if line:
return self.parse_line(line)
else:
self.fh.seek(0)
raise StopIteration
def next(self):
try:
return self.next_asset()
except:
raise StopIteration
|
Add tests for `getFullString` in Selectors | const Selector = require('selector_manager/model/Selector');
const Selectors = require('selector_manager/model/Selectors');
module.exports = {
run() {
describe('Selector', () => {
var obj;
beforeEach(() => {
obj = new Selector();
});
afterEach(() => {
obj = null;
});
it('Has name property', () => {
expect(obj.has('name')).toEqual(true);
});
it('Has label property', () => {
expect(obj.has('label')).toEqual(true);
});
it('Has active property', () => {
expect(obj.has('active')).toEqual(true);
});
it('escapeName test', () => {
expect(Selector.escapeName('@Te sT*')).toEqual('-Te-sT-');
});
it('Name is corrected at instantiation', () => {
obj = new Selector({ name: '@Te sT*'});
expect(obj.get('name')).toEqual('-Te-sT-');
});
});
describe.only('Selectors', () => {
var obj;
beforeEach(() => {
obj = new Selectors();
});
it('Creates collection item correctly', () => {
var c = new Selectors();
var m = c.add({});
expect(m instanceof Selector).toEqual(true);
});
it('getFullString with single class', () => {
obj.add({name: 'test'});
expect(obj.getFullString()).toEqual('.test');
});
it('getFullString with multiple classes', () => {
obj.add([{name: 'test'}, {name: 'test2'}]);
expect(obj.getFullString()).toEqual('.test.test2');
});
it('getFullString with mixed selectors', () => {
obj.add([{name: 'test'}, {name: 'test2', type: Selector.TYPE_ID}]);
expect(obj.getFullString()).toEqual('.test#test2');
});
});
}
};
| const Selector = require('selector_manager/model/Selector');
const Selectors = require('selector_manager/model/Selectors');
module.exports = {
run() {
describe('Selector', () => {
var obj;
beforeEach(() => {
obj = new Selector();
});
afterEach(() => {
obj = null;
});
it('Has name property', () => {
expect(obj.has('name')).toEqual(true);
});
it('Has label property', () => {
expect(obj.has('label')).toEqual(true);
});
it('Has active property', () => {
expect(obj.has('active')).toEqual(true);
});
it('escapeName test', () => {
expect(Selector.escapeName('@Te sT*')).toEqual('-Te-sT-');
});
it('Name is corrected at instantiation', () => {
obj = new Selector({ name: '@Te sT*'});
expect(obj.get('name')).toEqual('-Te-sT-');
});
});
describe('Selectors', () => {
it('Creates collection item correctly', () => {
var c = new Selectors();
var m = c.add({});
expect(m instanceof Selector).toEqual(true);
});
});
}
};
|
Fix bugs in new class | def compare_vectors(x, y):
for x_i, y_i in zip(x, y):
comparison = _compare(x_i, y_i)
if comparison == 0:
continue
else:
return comparison
return 0
def _compare(x, y):
if x is not None and y is not None:
return int(x > y) - int(x < y)
elif x is not None and y is None:
return -1
elif x is None and y is not None:
return 1
else:
return 0
class ConstantDict(dict):
def __init__(self, constant):
super(ConstantDict, self).__init__()
self.constant = constant
self.deleted_keys = set()
def update(self, E=None, **F):
super(ConstantDict, self).update(E, **F)
if type(E) is type(self):
self.constant = E.constant
def values(self):
return [self.constant] + list(super(ConstantDict, self).values())
def __delitem__(self, key):
try:
super(ConstantDict, self).__delitem__(key)
except KeyError:
self.deleted_keys.add(key)
def __eq__(self, other):
if type(other) is not type(self):
return False
elif other.constant == self.constant and super(ConstantDict, self).__eq__(other):
return True
else:
return False
def __getitem__(self, item):
try:
return super(ConstantDict, self).__getitem__(item)
except KeyError:
if item in self.deleted_keys:
raise
else:
return self.constant
def __repr__(self):
return 'ConstantDict({}, {})'.format(self.constant, super(ConstantDict, self).__repr__())
| def compare_vectors(x, y):
for x_i, y_i in zip(x, y):
comparison = _compare(x_i, y_i)
if comparison == 0:
continue
else:
return comparison
return 0
def _compare(x, y):
if x is not None and y is not None:
return int(x > y) - int(x < y)
elif x is not None and y is None:
return -1
elif x is None and y is not None:
return 1
else:
return 0
class ConstantDict(dict):
def __init__(self, constant):
super(ConstantDict, self).__init__()
self.constant = constant
def values(self):
return [self.constant]
def __delitem__(self, key):
try:
super(ConstantDict, self).__delitem__(key)
except KeyError:
pass
def __eq__(self, other):
if type(other) is not type(self):
return False
elif other.constant == self.constant:
return True
else:
return False
def __getitem__(self, item):
try:
return super(ConstantDict, self).__getitem__(item)
except KeyError:
return self.constant
def __repr__(self):
return 'ConstantDict({})'.format(self.constant)
|
Remove public declaration from test class. | package main;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
class MatrixTransformationTest {
@Test
void rotateTo90Degrees() throws Exception {
int[][] matrix = new int[][] {
{0, 0, 0, 0},
{1, 1, 1, 1},
{2, 2, 2, 2},
{3, 3, 3, 3}
};
int[][] result = new int[][] {
{3, 2, 1, 0},
{3, 2, 1, 0},
{3, 2, 1, 0},
{3, 2, 1, 0}
};
assertArrayEquals(result, MatrixTransformation.rotateTo90Degrees(matrix));
}
@Test
void zeroefyMatrix() throws Exception {
int[][] matrix = new int[][] {
{1, 1, 1, 1, 1},
{1, 1, 1, 0, 1},
{1, 1, 1, 1, 1},
{1, 0, 1, 1, 1}
};
int[][] result = new int[][] {
{1, 0, 1, 0, 1},
{0, 0, 0, 0, 0},
{1, 0, 1, 0, 1},
{0, 0, 0, 0, 0}
};
assertArrayEquals(result, MatrixTransformation.zeroefyMatrix(matrix));
}
}
| package main;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
public class MatrixTransformationTest {
@Test
void rotateTo90Degrees() throws Exception {
int[][] matrix = new int[][] {
{0, 0, 0, 0},
{1, 1, 1, 1},
{2, 2, 2, 2},
{3, 3, 3, 3}
};
int[][] result = new int[][] {
{3, 2, 1, 0},
{3, 2, 1, 0},
{3, 2, 1, 0},
{3, 2, 1, 0}
};
assertArrayEquals(result, MatrixTransformation.rotateTo90Degrees(matrix));
}
@Test
void zeroefyMatrix() throws Exception {
int[][] matrix = new int[][] {
{1, 1, 1, 1, 1},
{1, 1, 1, 0, 1},
{1, 1, 1, 1, 1},
{1, 0, 1, 1, 1}
};
int[][] result = new int[][] {
{1, 0, 1, 0, 1},
{0, 0, 0, 0, 0},
{1, 0, 1, 0, 1},
{0, 0, 0, 0, 0}
};
assertArrayEquals(result, MatrixTransformation.zeroefyMatrix(matrix));
}
}
|
Add 'grunt check' for quick checking | module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-blanket');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-coveralls');
grunt.loadNpmTasks('grunt-mocha-test');
grunt.loadNpmTasks('grunt-screeps');
grunt.initConfig({
blanket: {
coverage: {
src: ['scripts/'],
dest: 'lib-cov/scripts/'
}
},
copy: {
coverage: {
expand: true,
src: ['test/**', 'lib/mocks/**'],
dest: 'lib-cov/'
}
},
coveralls: {
options: {
force: true
},
coverage: {
src: 'coverage/lcov.info'
}
},
mochaTest: {
test: {
src: 'test/**/*.js',
options: {
slow: 20
}
},
coverage: {
src: 'lib-cov/test/**/*.js',
options: {
reporter: 'mocha-lcov-reporter',
quiet: true,
captureFile: 'coverage/lcov.info'
}
}
},
screeps: {
options: {
email: null,
password: null
},
dist: {
src: ['scripts/*.js']
}
}
});
grunt.task.registerTask('check', [
'mochaTest:test'
]);
grunt.task.registerTask('test', [
'blanket',
'copy',
'mochaTest',
'coveralls'
]);
grunt.task.registerTask('default', [
'test'
]);
}; | module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-blanket');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-coveralls');
grunt.loadNpmTasks('grunt-mocha-test');
grunt.loadNpmTasks('grunt-screeps');
grunt.initConfig({
blanket: {
coverage: {
src: ['scripts/'],
dest: 'lib-cov/scripts/'
}
},
copy: {
coverage: {
expand: true,
src: ['test/**', 'lib/mocks/**'],
dest: 'lib-cov/'
}
},
coveralls: {
options: {
force: true
},
coverage: {
src: 'coverage/lcov.info'
}
},
mochaTest: {
test: {
src: 'test/**/*.js',
options: {
slow: 20
}
},
coverage: {
src: 'lib-cov/test/**/*.js',
options: {
reporter: 'mocha-lcov-reporter',
quiet: true,
captureFile: 'coverage/lcov.info'
}
}
},
screeps: {
options: {
email: null,
password: null
},
dist: {
src: ['scripts/*.js']
}
}
});
grunt.task.registerTask('test', [
'blanket',
'copy',
'mochaTest',
'coveralls'
]);
grunt.task.registerTask('default', [
'test'
]);
}; |
Decrease cookie length in User model from 255 to 100 chars | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
class User(models.Model):
MALE = -1
UNDEFINED = 0
FEMALE = 1
GENDER_CHOICES = (
(MALE, 'Male'),
(UNDEFINED, 'Undefined'),
(FEMALE, 'Female')
)
school = models.ForeignKey('unichat.School')
email = models.EmailField(
unique=True,
help_text=("The user's academic email.")
)
password = models.CharField(
max_length=100,
help_text=("The user's password.")
)
gender = models.IntegerField(
default=0,
choices=GENDER_CHOICES,
help_text=("The user's gender, by default UNDEFINED, unless otherwise "
"explicitly specified by the user.")
)
interestedInGender = models.IntegerField(
default=0,
choices=GENDER_CHOICES,
help_text=("The gender that the user is interested in talking to, by "
"default UNDEFINED.")
)
interestedInSchools = models.ManyToManyField('unichat.School', related_name='user_interested_schools')
cookie = models.CharField(
default='',
max_length=100,
db_index=True,
help_text=("The user's active cookie.")
)
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
class User(models.Model):
MALE = -1
UNDEFINED = 0
FEMALE = 1
GENDER_CHOICES = (
(MALE, 'Male'),
(UNDEFINED, 'Undefined'),
(FEMALE, 'Female')
)
school = models.ForeignKey('unichat.School')
email = models.EmailField(
unique=True,
help_text=("The user's academic email.")
)
password = models.CharField(
max_length=100,
help_text=("The user's password.")
)
gender = models.IntegerField(
default=0,
choices=GENDER_CHOICES,
help_text=("The user's gender, by default UNDEFINED, unless otherwise "
"explicitly specified by the user.")
)
interestedInGender = models.IntegerField(
default=0,
choices=GENDER_CHOICES,
help_text=("The gender that the user is interested in talking to, by "
"default UNDEFINED.")
)
interestedInSchools = models.ManyToManyField('unichat.School', related_name='user_interested_schools')
cookie = models.CharField(
default='',
max_length=255,
db_index=True,
help_text=("The user's active cookie.")
)
|
Remove redundant property definitions from gRenderer | gRenderer = {
frame: 0,
render: function() {
this.context.fillStyle = '#000';
this.context.fillRect(0, 0, this.context.canvas.width, this.context.canvas.height);
switch (gScene.scene) {
case 'title':
gScene.renderTitle();
break;
case 'hangar':
case 'game':
gScene.renderBack();
gPlayer.render();
gScene.renderFore();
gPlayer.projectiles.forEach(function(p) { p.render() }.bind(this));
if (gScene.inTransition) gScene.renderTransition();
break;
case 'levelTitle':
gScene.renderLevelTitle();
break;
}
if (!gScene.inTransition) gInput.render();
// Debug display
// this.context.font = '16px monospace';
// this.context.textAlign = 'left';
// this.context.fillStyle = '#FFF';
// this.context.fillText('gCamera: ' + gCamera.x + ', ' + gCamera.y + ' vel: ' + gCamera.xVel + ', ' + gCamera.yVel, 12, 12);
// this.context.fillText('gPlayer: ' + gPlayer.x + ', ' + gPlayer.y + ' vel: ' + gPlayer.xVel + ', ' + gPlayer.yVel, 12, 36);
this.frame = (this.frame + 1) % 60;
}
}
| gRenderer = {
frame: 0,
canvas: document.getElementById('canvas'),
context: this.canvas.getContext('2d'),
render: function() {
this.context.fillStyle = '#000';
this.context.fillRect(0, 0, canvas.width, canvas.height);
switch (gScene.scene) {
case 'title':
gScene.renderTitle();
break;
case 'hangar':
case 'game':
gScene.renderBack();
gPlayer.render();
gScene.renderFore();
gPlayer.projectiles.forEach(function(p) { p.render() }.bind(this));
if (gScene.inTransition) gScene.renderTransition();
break;
case 'levelTitle':
gScene.renderLevelTitle();
break;
}
if (!gScene.inTransition) gInput.render();
// Debug display
// this.context.font = '16px monospace';
// this.context.textAlign = 'left';
// this.context.fillStyle = '#FFF';
// this.context.fillText('gCamera: ' + gCamera.x + ', ' + gCamera.y + ' vel: ' + gCamera.xVel + ', ' + gCamera.yVel, 12, 12);
// this.context.fillText('gPlayer: ' + gPlayer.x + ', ' + gPlayer.y + ' vel: ' + gPlayer.xVel + ', ' + gPlayer.yVel, 12, 36);
this.frame = (this.frame + 1) % 60;
}
}
|
Make the X Y and Z checkboxes automatically selected on program start | package graphics;
import javax.swing.*;
import java.awt.*;
public class EvolutionSelector extends JPanel {
private static JFrame frame;
//Used to allow JLabel to word-wrap
private static final String HTML_Formatting = "<html><body style='width: 100px'>";
public static JCheckBox xEquation = new JCheckBox("x");
public static JCheckBox yEquation = new JCheckBox("y");
public static JCheckBox zEquation = new JCheckBox("z");
public static JCheckBox colorEquation = new JCheckBox("color");
private static JLabel title = new JLabel(HTML_Formatting + "Select Equations to Evolve:");
public EvolutionSelector(int x, int y) {
xEquation.setSelected(true);
yEquation.setSelected(true);
zEquation.setSelected(true);
frame = new JFrame("Evolution Selector");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(x, y);
frame.setSize(150, 300);
frame.setResizable(false);
frame.setVisible(true);
//Don't let this window take focus away from the GraphicalInterface window
frame.setFocusableWindowState(false);
frame.getContentPane().setLayout(new GridLayout(5, 2));
//Add the title text to the windows
frame.getContentPane().add(title);
//Add the evolution selectors
frame.getContentPane().add(xEquation);
frame.getContentPane().add(yEquation);
frame.getContentPane().add(zEquation);
frame.getContentPane().add(colorEquation);
}
}
| package graphics;
import javax.swing.*;
import java.awt.*;
public class EvolutionSelector extends JPanel {
private static JFrame frame;
//Used to allow JLabel to word-wrap
private static final String HTML_Formatting = "<html><body style='width: 100px'>";
public static JCheckBox xEquation = new JCheckBox("x");
public static JCheckBox yEquation = new JCheckBox("y");
public static JCheckBox zEquation = new JCheckBox("z");
public static JCheckBox colorEquation = new JCheckBox("color");
private static JLabel title = new JLabel(HTML_Formatting + "Select Equations to Evolve:");
public EvolutionSelector(int x, int y) {
frame = new JFrame("Evolution Selector");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(x, y);
frame.setSize(150, 300);
frame.setResizable(false);
frame.setVisible(true);
//Don't let this window take focus away from the GraphicalInterface window
frame.setFocusableWindowState(false);
frame.getContentPane().setLayout(new GridLayout(5, 2));
//Add the title text to the windows
frame.getContentPane().add(title);
//Add the evolution selectors
frame.getContentPane().add(xEquation);
frame.getContentPane().add(yEquation);
frame.getContentPane().add(zEquation);
frame.getContentPane().add(colorEquation);
}
}
|
Change abao test to use the local installation instead of the global. | var assert = require('assert');
var request = require('supertest');
var exec = require('child_process').exec;
var application = require(__dirname + '/server.js');
describe('server', function () {
before(function () {
application.listen();
});
after(function () {
application.close();
});
describe('Array', function () {
describe('#indexOf()', function () {
it('should return -1 when the value is not present', function () {
assert.equal(-1, [1, 2, 3].indexOf(5));
assert.equal(-1, [1, 2, 3].indexOf(0));
});
});
describe('#indexOf()', function () {
it('should return -1 when the value is not present', function () {
assert.equal(-1, [1, 2, 3].indexOf(5));
});
});
describe('GET /', function() {
it('respond with json', function(done) {
request(application.app)
.get('/')
.set('Accept', 'application/json')
.expect('Content-Type', /html/)
.expect(200, done);
});
});
describe('Run Abao', function() {
it('respond with json', function(done) {
this.timeout(15000);
exec('node node_modules/.bin/abao ./raml/api.raml --server http://localhost:3000/api', function (err, stdout) {
console.log(stdout);
done();
});
});
});
});
});
| var assert = require('assert');
var request = require('supertest');
var exec = require('child_process').exec;
var application = require(__dirname + '/server.js');
describe('server', function () {
before(function () {
application.listen();
});
after(function () {
application.close();
});
describe('Array', function () {
describe('#indexOf()', function () {
it('should return -1 when the value is not present', function () {
assert.equal(-1, [1, 2, 3].indexOf(5));
assert.equal(-1, [1, 2, 3].indexOf(0));
});
});
describe('#indexOf()', function () {
it('should return -1 when the value is not present', function () {
assert.equal(-1, [1, 2, 3].indexOf(5));
});
});
describe('GET /', function() {
it('respond with json', function(done) {
request(application.app)
.get('/')
.set('Accept', 'application/json')
.expect('Content-Type', /html/)
.expect(200, done);
});
});
describe('Run Abao', function() {
it('respond with json', function(done) {
this.timeout(15000);
exec('abao ./raml/api.raml --server http://localhost:3000/api', function (err) {
done();
});
});
});
});
});
|
Revert changes that broke everything | vars = require('./vars');
dash_button = require('node-dash-button');
nest = require('unofficial-nest-api');
util = require('util');
var device;
var structure;
var dash = dash_button(vars.AMAZON_DASH_BUTTON_MAC);
console.log("Nest API Connecting...");
nest.login(vars.NEST_USER_NAME, vars.NEST_PASSWORD, function (err, data) {
if (err) {
console.log(err.message);
process.exit(1);
return;
}
console.log('Logged in!');
listenForDash();
});
function fetchNestStatus(callback) {
nest.fetchStatus(function (data) {
structure = data.structure[vars.NEST_STRUCTURE_ID];
for (var deviceId in data.device) {
if (data.device.hasOwnProperty(deviceId)) {
device = data.shared[deviceId];
}
}
callback();
});
}
function listenForDash() {
console.log("Listening For Dash Button...");
dash.on("detected", function () {
console.log("Button Pressed!");
fetchNestStatus(function () {
console.log("Current Temp: " + nest.ctof(device.current_temperature));
if (structure.away) {
console.log("Nest is set to Away. Setting to home.");
nest.setHome();
} else {
console.log("Nest is set to home.");
}
});
});
}
| vars = require('./vars');
dash_button = require('node-dash-button');
nest = require('unofficial-nest-api');
var dash = dash_button(vars.AMAZON_DASH_BUTTON_MAC);
console.log("Nest API Connecting...");
nest.login(vars.NEST_USER_NAME, vars.NEST_PASSWORD, function (err, data) {
if (err) {
console.log(err.message);
process.exit(1);
return;
}
console.log('Logged in!');
listenForDash();
});
function fetchNestStatus(callback) {
nest.fetchStatus(function (data) {
var structure = data.structure[vars.NEST_STRUCTURE_ID];
var device;
for (var deviceId in data.device) {
if (data.device.hasOwnProperty(deviceId)) {
device = data.shared[deviceId];
}
}
callback(structure, device);
});
}
function listenForDash() {
console.log("Listening For Dash Button...");
dash.on("detected", function () {
console.log("Button Pressed!");
fetchNestStatus(function (device, structure) {
console.log("Current Temp: " + nest.ctof(device.current_temperature));
if (structure.away) {
console.log("Nest is set to Away. Setting to home.");
nest.setHome();
} else {
console.log("Nest is set to home.");
}
});
});
}
|
Fix json to sql converter. | import os
import os.path
from json import loads
import click
from vendcrawler.scripts.vendcrawlerdb import VendCrawlerDB
class JSONToSQL(object):
def __init__(self, json, user, password, database):
data = loads(json.read())
db = VendCrawlerDB(user, password, database)
table = 'items'
columns = ['item_id', 'item_name', 'vendor_id', 'shop_name',
'amount', 'price', 'map', 'datetime']
values = []
for items in data:
for item in items:
value = [int(item['id']),
item['name'],
int(item['vendor_id']),
item['shop'],
int(item['amount'].replace(',', '')),
int(item['price'].replace(',', '')),
item['map'],
item['datetime']]
values.append(value)
self.db.insert(table, columns, values)
@click.command()
@click.argument('json', type=click.File('r'))
@click.argument('user')
@click.argument('password')
@click.argument('database')
def cli(json, user, password, database):
JSONToSQL(json, user, password, database)
if __name__ == '__main__':
cli()
| import os
import os.path
from json import loads
import click
from vendcrawler.scripts.vendcrawlerdb import VendCrawlerDB
class JSONToSQL(object):
def __init__(self, json, user, password, database):
self.data = loads(json.read())
self.db = VendCrawlerDB(user, password, database)
table = 'items'
columns = ['item_id', 'item_name', 'vendor_id', 'shop_name',
'amount', 'price', 'map', 'datetime']
values = []
for items in data:
for item in items:
value = [int(item['id']),
item['name'],
int(item['vendor_id']),
item['shop'],
int(item['amount'].replace(',', '')),
int(item['price'].replace(',', '')),
item['map'],
item['datetime']]
values.append(value)
self.vcdb.insert(table, columns, values)
@click.command()
@click.argument('json', type=click.File('r'))
@click.argument('user')
@click.argument('password')
@click.argument('database')
def cli(json, user, password, database):
JSONToSQL(json, user, password, database)
if __name__ == '__main__':
cli()
|
Adjust setting responsiveRefreshRate to trigger resize before elementWidthChange | <?php
class Kwf_Owlcarousel_Kwc_Carousel_Component extends Kwc_Abstract_List_Component
{
public static function getSettings()
{
$ret = parent::getSettings();
$ret['componentName'] = trlKwfStatic('List Carousel');
$ret['generators']['child']['component'] = 'Kwf_Owlcarousel_Kwc_Carousel_Image_Component';
$ret['carouselConfig'] = array(
'loop' => true,
'center' => true,
'items' => 2,
'nav' => true,
'dots' => false,
'margin' => 10,
'smartSpeed' => 1500,
'touchSmartSpeed' => 600,
'startRandom' => false,
'autoplay' => false,
'autoplayTimeout' => 7000,
'responsiveRefreshRate' => 90
);
$ret['assetsDefer']['dep'][] = 'owlcarousel';
return $ret;
}
public function getTemplateVars()
{
$ret = parent::getTemplateVars();
$ret['config'] = array(
'carouselConfig' => $this->_getSetting('carouselConfig'),
'countItems' => count($ret['listItems']),
'contentWidth' => $this->getContentWidth()
);
return $ret;
}
}
| <?php
class Kwf_Owlcarousel_Kwc_Carousel_Component extends Kwc_Abstract_List_Component
{
public static function getSettings()
{
$ret = parent::getSettings();
$ret['componentName'] = trlKwfStatic('List Carousel');
$ret['generators']['child']['component'] = 'Kwf_Owlcarousel_Kwc_Carousel_Image_Component';
$ret['carouselConfig'] = array(
'loop' => true,
'center' => true,
'items' => 2,
'nav' => true,
'dots' => false,
'margin' => 10,
'smartSpeed' => 1500,
'touchSmartSpeed' => 600,
'startRandom' => false,
'autoplay' => false,
'autoplayTimeout' => 7000
);
$ret['assetsDefer']['dep'][] = 'owlcarousel';
return $ret;
}
public function getTemplateVars()
{
$ret = parent::getTemplateVars();
$ret['config'] = array(
'carouselConfig' => $this->_getSetting('carouselConfig'),
'countItems' => count($ret['listItems']),
'contentWidth' => $this->getContentWidth()
);
return $ret;
}
}
|
Revert "Revert "drop old requirements""
This reverts commit f444e853936eb95bbe61c2bbf26098e417cc5fef. | #!/usr/bin/env python
from setuptools import setup, find_packages
from pupa import __version__
long_description = ''
setup(name='pupa',
version=__version__,
packages=find_packages(),
author='James Turk',
author_email='[email protected]',
license='BSD',
url='http://github.com/opencivicdata/pupa/',
description='scraping framework for muncipal data',
long_description=long_description,
platforms=['any'],
entry_points='''[console_scripts]
pupa = pupa.cli.__main__:main''',
install_requires=[
#'Django==1.7.0',
'dj_database_url==0.3.0',
'opencivicdata-django>=0.7.0',
'opencivicdata-divisions',
'scrapelib>=0.10',
'validictory>=1.0.0a2',
'psycopg2',
'pytz',
'boto',
#'kafka-python', # Optional Kafka dep
],
classifiers=["Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3.4",
"Topic :: Software Development :: Libraries :: Python Modules",
],
)
| #!/usr/bin/env python
from setuptools import setup, find_packages
from pupa import __version__
long_description = ''
setup(name='pupa',
version=__version__,
packages=find_packages(),
author='James Turk',
author_email='[email protected]',
license='BSD',
url='http://github.com/opencivicdata/pupa/',
description='scraping framework for muncipal data',
long_description=long_description,
platforms=['any'],
entry_points='''[console_scripts]
pupa = pupa.cli.__main__:main''',
install_requires=[
#'Django==1.7.0',
'dj_database_url==0.3.0',
'django-uuidfield==0.5.0',
'djorm-pgarray==1.0',
'jsonfield>=0.9.20,<1',
'opencivicdata-django>=0.6.0',
'opencivicdata-divisions',
'scrapelib>=0.10',
'validictory>=1.0.0a2',
'psycopg2',
'pytz',
'boto',
#'kafka-python', # Optional Kafka dep
],
classifiers=["Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Topic :: Software Development :: Libraries :: Python Modules",
],
)
|
Use getter woko use Java... | package woko.ext.usermanagement.facets.registration;
import net.sourceforge.jfacets.IFacetDescriptorManager;
import net.sourceforge.jfacets.annotations.FacetKey;
import woko.ext.usermanagement.core.DatabaseUserManager;
import woko.ext.usermanagement.core.User;
import woko.facets.BaseFragmentFacet;
import woko.persistence.ObjectStore;
import woko.users.UsernameResolutionStrategy;
@FacetKey(name="renderRegisterProperties", profileId = "all")
public class RenderRegisterProperties<T extends User,
OsType extends ObjectStore,
UmType extends DatabaseUserManager<?,T>,
UnsType extends UsernameResolutionStrategy,
FdmType extends IFacetDescriptorManager
> extends BaseFragmentFacet<OsType,UmType,UnsType,FdmType> {
public static final String FACET_NAME = "renderRegisterProperties";
public static final String FRAGMENT_PATH = "/WEB-INF/woko/ext/usermanagement/renderRegisterProperties.jsp";
private Register registerFacet;
public String getPath() {
return FRAGMENT_PATH;
}
public String getReCaptchaPublicKey() {
return getRegisterFacet().getReCaptchaPublicKey();
}
public String getReCaptchaPrivateKey() {
return getRegisterFacet().getReCaptchaPrivateKey();
}
public boolean isUseCaptcha() {
return getRegisterFacet().isUseCaptcha();
}
public Register getRegisterFacet(){
if (registerFacet==null)
registerFacet = getWoko().getFacet("register", getRequest(), null);
return registerFacet;
}
}
| package woko.ext.usermanagement.facets.registration;
import net.sourceforge.jfacets.IFacetDescriptorManager;
import net.sourceforge.jfacets.annotations.FacetKey;
import woko.ext.usermanagement.core.DatabaseUserManager;
import woko.ext.usermanagement.core.User;
import woko.facets.BaseFragmentFacet;
import woko.persistence.ObjectStore;
import woko.users.UsernameResolutionStrategy;
@FacetKey(name="renderRegisterProperties", profileId = "all")
public class RenderRegisterProperties<T extends User,
OsType extends ObjectStore,
UmType extends DatabaseUserManager<?,T>,
UnsType extends UsernameResolutionStrategy,
FdmType extends IFacetDescriptorManager
> extends BaseFragmentFacet<OsType,UmType,UnsType,FdmType> {
public static final String FACET_NAME = "renderRegisterProperties";
public static final String FRAGMENT_PATH = "/WEB-INF/woko/ext/usermanagement/renderRegisterProperties.jsp";
private Register registerFacet;
public String getPath() {
return FRAGMENT_PATH;
}
public String getReCaptchaPublicKey() {
return registerFacet.getReCaptchaPublicKey();
}
public String getReCaptchaPrivateKey() {
return registerFacet.getReCaptchaPrivateKey();
}
public boolean isUseCaptcha() {
return registerFacet.isUseCaptcha();
}
public Register getRegisterFacet(){
if (registerFacet==null)
registerFacet = getWoko().getFacet("register", getRequest(), null);
return registerFacet;
}
}
|
Change visibility of scope methods from default to public | package fc.lang;
import java.util.HashMap;
import java.util.Map;
/**
* Implementation of flat static scope
*/
public class Scope {
private final Map<String, Expression> bindings = new HashMap<String, Expression>();
/**
* Bind a variable with the given name to an expression. If the variable
* already exists in the scope, the old value will be replaced with the new
* one.
*
* @param name
* of the variable
* @param expression
* which should be bound to the given name
*/
public void bind(String name, Expression expression) {
bindings.put(name, expression);
}
/**
* Delete the bound variable with the given name in this scope.
*
* @param name
* of a variable bound in this scope
*/
public void unbind(String name) {
bindings.remove(name);
}
/**
* Resolve the value of the bound variable with the given name
*
* @param name
* of a variable bound in this scope
* @return Expression representing the value of the variable
* @throws UnboundVariableException
* given variable is not bound in the current scope.
*/
public Expression resolve(String name) throws UnboundVariableException {
Expression result = bindings.get(name);
if (result == null) {
throw new UnboundVariableException("Variable '" + name
+ "' is not bound");
}
return result;
}
}
| package fc.lang;
import java.util.HashMap;
import java.util.Map;
/**
* Implementation of flat static scope
*/
public class Scope {
private final Map<String, Expression> bindings = new HashMap<String, Expression>();
/**
* Bind a variable with the given name to an expression. If the variable
* already exists in the scope, the old value will be replaced with the new
* one.
*
* @param name
* of the variable
* @param expression
* which should be bound to the given name
*/
void bind(String name, Expression expression) {
bindings.put(name, expression);
}
/**
* Delete the bound variable with the given name in this scope.
*
* @param name
* of a variable bound in this scope
*/
void unbind(String name) {
bindings.remove(name);
}
/**
* Resolve the value of the bound variable with the given name
*
* @param name
* of a variable bound in this scope
* @return Expression representing the value of the variable
* @throws UnboundVariableException
* given variable is not bound in the current scope.
*/
Expression resolve(String name) throws UnboundVariableException {
Expression result = bindings.get(name);
if (result == null) {
throw new UnboundVariableException("Variable '" + name
+ "' is not bound");
}
return result;
}
}
|
Allow to set lang of foreignKeys through attribute | 'use strict';
angular.module('arethusa.core').directive('foreignKeys',[
'keyCapture',
'languageSettings',
function (keyCapture, languageSettings) {
return {
restrict: 'A',
scope: {
ngChange: '&',
ngModel: '@',
foreignKeys: '='
},
link: function (scope, element, attrs) {
var parent = scope.$parent;
function extractLanguage() {
return (languageSettings.getFor('treebank') || {}).lang;
}
element.on('keydown', function (event) {
var lang = scope.foreignKeys || extractLanguage();
var input = event.target.value;
if (lang) {
var fK = keyCapture.getForeignKey(event, lang);
if (fK === false) {
return false;
}
if (fK === undefined) {
return true;
} else {
event.target.value = input + fK;
scope.$apply(function() {
parent.$eval(scope.ngModel + ' = i + k', { i: input, k: fK });
scope.ngChange();
});
return false;
}
} else {
return true;
}
});
}
};
}
]);
| 'use strict';
angular.module('arethusa.core').directive('foreignKeys',[
'keyCapture',
'languageSettings',
function (keyCapture, languageSettings) {
return {
restrict: 'A',
scope: {
ngChange: '&',
ngModel: '@'
},
link: function (scope, element, attrs) {
var parent = scope.$parent;
element.on('keydown', function (event) {
var lang = (languageSettings.getFor('treebank') || {}).lang;
var input = event.target.value;
if (lang) {
var fK = keyCapture.getForeignKey(event, lang);
if (fK === false) {
return false;
}
if (fK === undefined) {
return true;
} else {
event.target.value = input + fK;
scope.$apply(function() {
parent.$eval(scope.ngModel + ' = i + k', { i: input, k: fK });
scope.ngChange();
});
return false;
}
} else {
return true;
}
});
}
};
}
]);
|
Rename from to to name | const request = require('supertest');
const app = require('../app');
describe('transforms the name of the object in a coordinate', function () {
it('Input place name-string,base coordinate, return coordinate and full name point',
function (done) {
request(app)
.post('/searchCoordinate')
.send({
location: {
accuracy: 40,
lat: '53.663482',
lon: '23.834427',
},
name: 'ул. Лиможа 27/1',
})
.expect(200)
.expect({
lat: '53.70177645',
lon: '23.8347894179425',
display_name: 'OldCity, 17, улица Дубко, Девятовка, Ленинский район, ' +
'Hrodna, Hrodna region, 230012, Belarus',
})
.end(function (err, res) {
if (err) {
return done(err);
}
done();
});
});
});
| const request = require('supertest');
const app = require('../app');
describe('transforms the name of the object in a coordinate', function () {
it('Input place name-string,base coordinate, return coordinate and full name point',
function (done) {
request(app)
.post('/searchCoordinate')
.send({
location: {
accuracy: 40,
lat: '53.663482',
lon: '23.834427',
},
to: 'ул. Лиможа 27/1',
})
.expect(200)
.expect({
lat: '53.70177645',
lon: '23.8347894179425',
display_name: 'OldCity, 17, улица Дубко, Девятовка, Ленинский район, ' +
'Hrodna, Hrodna region, 230012, Belarus',
})
.end(function (err, res) {
if (err) {
return done(err);
}
done();
});
});
});
|
Add require field on fields | <h1>Novi scripti</h1>
<form id="novi_scripti" action="../api.php?s=scriptum" method="post">
<div class="row">
<div class="col-md-6 form-group">
<label for="content">Content</label>
<textarea name="content" id="content" rows="20" cols="50" class="form-control vert" required></textarea>
</div>
<div class="col-md-6 form-group">
<label>Settings</label>
<div class="input-group">
<label class="input-group-addon" for="title">Title</label>
<input type="text" name="title" id="title" class="form-control" required/>
</div>
<div class="input-group">
<label class="input-group-addon" for="destruction">Destruction date</label>
<input type="text" name="destruction" id="destruction" class="form-control datepicker" required/>
</div>
</div>
</div>
<input type="submit" value="Create" class="btn btn-primary btn-block"/>
</form>
<!-- App JS -->
<script src="https://code.jquery.com/ui/1.11.3/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css"/>
<script src="/js/datepicker.js"></script>
<script src="/js/novi_scripti.js"></script> | <h1>Novi scripti</h1>
<form id="novi_scripti" action="../api.php?s=scriptum" method="post">
<div class="row">
<div class="col-md-6 form-group">
<label for="content">Content</label>
<textarea name="content" id="content" rows="20" cols="50" class="form-control vert"></textarea>
</div>
<div class="col-md-6 form-group">
<label>Settings</label>
<div class="input-group">
<label class="input-group-addon" for="title">Title</label>
<input type="text" name="title" id="title" class="form-control"/>
</div>
<div class="input-group">
<label class="input-group-addon" for="destruction">Destruction date</label>
<input type="text" name="destruction" id="destruction" class="form-control datepicker"/>
</div>
</div>
</div>
<input type="submit" value="Create" class="btn btn-primary btn-block"/>
</form>
<!-- App JS -->
<script src="https://code.jquery.com/ui/1.11.3/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css"/>
<script src="/js/datepicker.js"></script>
<script src="/js/novi_scripti.js"></script> |
Fix decoding of admin authorities from access tokens | package com.digirati.elucidate.infrastructure.security.impl;
import com.digirati.elucidate.infrastructure.security.UserSecurityDetails;
import com.digirati.elucidate.infrastructure.security.UserSecurityDetailsLoader;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter;
public final class JwtUserAuthenticationConverter extends DefaultUserAuthenticationConverter {
private List<String> uidProperties;
private UserSecurityDetailsLoader securityDetailsLoader;
public JwtUserAuthenticationConverter(List<String> uidProperties, UserSecurityDetailsLoader securityDetailsLoader) {
this.uidProperties = uidProperties;
this.securityDetailsLoader = securityDetailsLoader;
}
@Override
public Authentication extractAuthentication(Map<String, ?> details) {
return uidProperties.stream()
.filter(details::containsKey)
.map(prop -> (String) details.get(prop))
.findFirst()
.map(uid -> {
UserSecurityDetails securityDetails = securityDetailsLoader.findOrCreateUserDetails(uid);
Collection<String> roles = (Collection<String>) details.get(AUTHORITIES);
if (roles == null) {
roles = Collections.emptyList();
}
List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(roles.toArray(new String[0]));
Authentication auth = new UsernamePasswordAuthenticationToken(
securityDetails,
"N/A",
authorities
);
return auth;
})
.orElse(null);
}
}
| package com.digirati.elucidate.infrastructure.security.impl;
import com.digirati.elucidate.infrastructure.security.UserSecurityDetails;
import com.digirati.elucidate.infrastructure.security.UserSecurityDetailsLoader;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter;
import java.util.Collections;
import java.util.List;
import java.util.Map;
public final class JwtUserAuthenticationConverter extends DefaultUserAuthenticationConverter {
private List<String> uidProperties;
private UserSecurityDetailsLoader securityDetailsLoader;
public JwtUserAuthenticationConverter(List<String> uidProperties, UserSecurityDetailsLoader securityDetailsLoader) {
this.uidProperties = uidProperties;
this.securityDetailsLoader = securityDetailsLoader;
}
@Override
public Authentication extractAuthentication(Map<String, ?> details) {
return uidProperties.stream()
.filter(details::containsKey)
.map(prop -> (String) details.get(prop))
.findFirst()
.map(uid -> {
UserSecurityDetails securityDetails = securityDetailsLoader.findOrCreateUserDetails(uid);
Authentication auth = new UsernamePasswordAuthenticationToken(
securityDetails,
"N/A",
Collections.emptySet()
);
return auth;
})
.orElse(null);
}
}
|
Add default meta for empty tiles | (() => {
const tools = [];
DTile.Tool = class DTileTool {
static register() {
tools.push(new this());
}
static get allTools() { return tools; }
static get store() { return DTile.store; }
static get state() { return DTileTool.store.getState(); }
get currentMap() {
const state = DTileTool.state;
return state.entities.maps[state.ui.currentMapId].present;
}
get currentLayerIndex() {
return DTileTool.state.ui.currentLayerIndex;
}
get currentLayer() {
return this.currentMap.layers[this.currentLayerIndex];
}
get layerAsTileArea() {
if (!this.currentLayer) return;
const map = this.currentMap;
return {
width: map.width,
height: map.height,
tiles: this.currentLayer.tiles
};
}
get tileArea() {
return DTileTool.state.ui.currentTileArea;
}
getTileMeta(tilesetId, tileId) {
if (tilesetId < 0 || tileId < 0) return {};
return DTileTool.state.entities.tilesets[tilesetId].tileMeta[tileId] || {};
}
onMove() {}
onTap() {}
onTrack() {}
};
})();
| (() => {
const tools = [];
DTile.Tool = class DTileTool {
static register() {
tools.push(new this());
}
static get allTools() { return tools; }
static get store() { return DTile.store; }
static get state() { return DTileTool.store.getState(); }
get currentMap() {
const state = DTileTool.state;
return state.entities.maps[state.ui.currentMapId].present;
}
get currentLayerIndex() {
return DTileTool.state.ui.currentLayerIndex;
}
get currentLayer() {
return this.currentMap.layers[this.currentLayerIndex];
}
get layerAsTileArea() {
if (!this.currentLayer) return;
const map = this.currentMap;
return {
width: map.width,
height: map.height,
tiles: this.currentLayer.tiles
};
}
get tileArea() {
return DTileTool.state.ui.currentTileArea;
}
getTileMeta(tilesetId, tileId) {
return DTileTool.state.entities.tilesets[tilesetId].tileMeta[tileId] || {};
}
onMove() {}
onTap() {}
onTrack() {}
};
})();
|
Improve removal of qualifiers when fetching suggestions. | import uniqueId from 'lodash/uniqueId';
import npmsRequest from '../../util/npmsRequest';
const maxResults = 10;
// TODO: Use a LRU to cache results
function normalizeQuery(query) {
return query
.replace(/(\S+:'(?:[^'\\]|\\.)*')|(\S+:"(?:[^"\\]|\\.)*")|\S+:\S+/g, '') // Remove qualifiers
.replace(/\s\s*/g, ' ') // Remove extra spaces left behind
.trim();
}
export function reset() {
return {
type: 'SearchSuggestions.RESET',
};
}
export function fetch(query) {
return (dispatch, getState) => {
query = normalizeQuery(query);
// Do nothing if current query is the same
if (getState().searchSuggestions.query === query) {
return;
}
// Reset if query is empty
if (!query) {
return dispatch(reset());
}
dispatch({
type: 'SearchSuggestions.FETCH',
meta: { uid: uniqueId('search-suggestions-') },
payload: {
data: query,
promise: npmsRequest(`/search/suggestions?q=${encodeURIComponent(query)}&size=${maxResults}`),
},
})
.catch(() => {}); // SearchSuggestions.FETCH_REJECTED will be dispatched, so swallow any error
};
}
| import uniqueId from 'lodash/uniqueId';
import npmsRequest from '../../util/npmsRequest';
const maxResults = 10;
// TODO: Use a LRU to cache results
function normalizeQuery(query) {
return query
.replace(/[a-z0-9]+:([a-z0-9:]+)*/ig, '') // Remove qualifiers
.replace(/\s\s*/g, ' ') // Remove extra spaces
.trim();
}
export function reset() {
return {
type: 'SearchSuggestions.RESET',
};
}
export function fetch(query) {
return (dispatch, getState) => {
query = normalizeQuery(query);
// Do nothing if current query is the same
if (getState().searchSuggestions.query === query) {
return;
}
// Reset if query is empty
if (!query) {
return dispatch(reset());
}
dispatch({
type: 'SearchSuggestions.FETCH',
meta: { uid: uniqueId('search-suggestions-') },
payload: {
data: query,
promise: npmsRequest(`/search/suggestions?q=${encodeURIComponent(query)}&size=${maxResults}`),
},
})
.catch(() => {}); // SearchSuggestions.FETCH_REJECTED will be dispatched, so swallow any error
};
}
|
Add shim config for jquery expander plugin so we don't have intermittent JS errors about jQuery not being defined | // Common configuration for RequireJS
var require = {
baseUrl: "/scripts",
paths: {
"jquery": "bower_components/jquery/dist/jquery.min",
"knockout": "bower_components/knockout/dist/knockout",
"bootstrap": "bower_components/bootstrap/dist/js/bootstrap.min",
"text": "bower_components/requirejs-text/text",
"domReady": "bower_components/requirejs-domReady/domReady",
"moment": "bower_components/moment/min/moment.min",
"videojs": "bower_components/videojs/dist/video-js/video",
"knockout-postbox": "bower_components/knockout-postbox/build/knockout-postbox.min",
"knockout-validation": "bower_components/knockout-validation/Dist/knockout.validation.min",
"perfect-scrollbar": "bower_components/perfect-scrollbar/src/perfect-scrollbar",
"jquery-expander": "bower_components/jquery-expander/jquery.expander",
"bootstrap-select": "bower_components/bootstrap-select/dist/js/bootstrap-select",
"bootstrap-tagsinput": "bower_components/bootstrap-tagsinput/dist/bootstrap-tagsinput",
},
shim: {
"bootstrap": {
deps: ["jquery"],
exports: "$.fn.popover"
},
"jquery-expander": ["jquery"]
}
}; | // Common configuration for RequireJS
var require = {
baseUrl: "/scripts",
paths: {
"jquery": "bower_components/jquery/dist/jquery.min",
"knockout": "bower_components/knockout/dist/knockout",
"bootstrap": "bower_components/bootstrap/dist/js/bootstrap.min",
"text": "bower_components/requirejs-text/text",
"domReady": "bower_components/requirejs-domReady/domReady",
"moment": "bower_components/moment/min/moment.min",
"videojs": "bower_components/videojs/dist/video-js/video",
"knockout-postbox": "bower_components/knockout-postbox/build/knockout-postbox.min",
"knockout-validation": "bower_components/knockout-validation/Dist/knockout.validation.min",
"perfect-scrollbar": "bower_components/perfect-scrollbar/src/perfect-scrollbar",
"jquery-expander": "bower_components/jquery-expander/jquery.expander",
"bootstrap-select": "bower_components/bootstrap-select/dist/js/bootstrap-select",
"bootstrap-tagsinput": "bower_components/bootstrap-tagsinput/dist/bootstrap-tagsinput",
},
shim: {
"bootstrap": {
deps: ["jquery"],
exports: "$.fn.popover"
}
}
}; |
Ch23: Remove password from UserAdmin fieldsets. | from django.contrib import admin
from .models import User
@admin.register(User)
class UserAdmin(admin.ModelAdmin):
# list view
list_display = (
'get_name',
'email',
'get_date_joined',
'is_staff',
'is_superuser')
list_display_links = ('get_name', 'email')
list_filter = (
'is_staff',
'is_superuser',
'profile__joined')
ordering = ('email',)
search_fields = ('email',)
# form view
fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email',)}),
('Permissions', {
'classes': ('collapse',),
'fields': (
'is_active',
'is_staff',
'is_superuser',
'groups',
'user_permissions')}),
('Important dates', {
'classes': ('collapse',),
'fields': ('last_login',)}),
)
filter_horizontal = (
'groups', 'user_permissions',)
def get_date_joined(self, user):
return user.profile.joined
get_date_joined.short_description = 'Joined'
get_date_joined.admin_order_field = (
'profile__joined')
def get_name(self, user):
return user.profile.name
get_name.short_description = 'Name'
get_name.admin_order_field = 'profile__name'
| from django.contrib import admin
from .models import User
@admin.register(User)
class UserAdmin(admin.ModelAdmin):
# list view
list_display = (
'get_name',
'email',
'get_date_joined',
'is_staff',
'is_superuser')
list_display_links = ('get_name', 'email')
list_filter = (
'is_staff',
'is_superuser',
'profile__joined')
ordering = ('email',)
search_fields = ('email',)
# form view
fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'password')}),
('Permissions', {
'classes': ('collapse',),
'fields': (
'is_active',
'is_staff',
'is_superuser',
'groups',
'user_permissions')}),
('Important dates', {
'classes': ('collapse',),
'fields': ('last_login',)}),
)
filter_horizontal = (
'groups', 'user_permissions',)
def get_date_joined(self, user):
return user.profile.joined
get_date_joined.short_description = 'Joined'
get_date_joined.admin_order_field = (
'profile__joined')
def get_name(self, user):
return user.profile.name
get_name.short_description = 'Name'
get_name.admin_order_field = 'profile__name'
|
[default-layout] Add prop type for versions | import React from 'react'
import PropTypes from 'prop-types'
import Button from 'part:@sanity/components/buttons/default'
import Dialog from 'part:@sanity/components/dialogs/default'
import styles from './styles/UpdateNotifierDialog.css'
function CurrentVersionsDialog(props) {
const {onClose, versions} = props
return (
<Dialog isOpen onClose={onClose}>
<div className={styles.content}>
<div>
<h2>Studio is up to date</h2>
<table className={styles.versionsTable}>
<thead>
<tr>
<th>Module</th>
<th>Installed</th>
<th>Latest</th>
</tr>
</thead>
<tbody>
{Object.keys(versions).map(pkgName => (
<tr key={pkgName}>
<td>{pkgName}</td>
<td>{versions[pkgName]}</td>
<td>{versions[pkgName]}</td>
</tr>
))}
</tbody>
</table>
<Button color="primary" onClick={onClose}>
Close
</Button>
</div>
</div>
</Dialog>
)
}
CurrentVersionsDialog.defaultProps = {
versions: {}
}
CurrentVersionsDialog.propTypes = {
onClose: PropTypes.func.isRequired,
versions: PropTypes.objectOf(PropTypes.string)
}
export default CurrentVersionsDialog
| import React from 'react'
import PropTypes from 'prop-types'
import Button from 'part:@sanity/components/buttons/default'
import Dialog from 'part:@sanity/components/dialogs/default'
import styles from './styles/UpdateNotifierDialog.css'
function CurrentVersionsDialog(props) {
const {onClose, versions} = props
return (
<Dialog isOpen onClose={onClose}>
<div className={styles.content}>
<div>
<h2>Studio is up to date</h2>
<table className={styles.versionsTable}>
<thead>
<tr>
<th>Module</th>
<th>Installed</th>
<th>Latest</th>
</tr>
</thead>
<tbody>
{Object.keys(versions).map(pkgName => (
<tr key={pkgName}>
<td>{pkgName}</td>
<td>{versions[pkgName]}</td>
<td>{versions[pkgName]}</td>
</tr>
))}
</tbody>
</table>
<Button color="primary" onClick={onClose}>
Close
</Button>
</div>
</div>
</Dialog>
)
}
CurrentVersionsDialog.propTypes = {
onClose: PropTypes.func.isRequired
// versions: PropTypes.object.isRequired
}
export default CurrentVersionsDialog
|
Change location of Open Data Folder action to @user.home/Documents/Archi | /**
* This program and the accompanying materials
* are made available under the terms of the License
* which accompanies this distribution in the file LICENSE.txt
*/
package com.archimatetool.editor.actions;
import java.awt.Desktop;
import java.awt.Desktop.Action;
import java.io.File;
import java.io.IOException;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import com.archimatetool.editor.ArchiPlugin;
/**
* Open Archi Data folder
*
* @author Phillip Beauvoir
*/
public class OpenDataFolderHandler extends AbstractHandler {
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
File folder = ArchiPlugin.INSTANCE.getUserDataFolder();
if(folder != null) {
try {
Desktop.getDesktop().open(folder);
}
catch(IOException ex) {
ex.printStackTrace();
}
}
return null;
}
@Override
public boolean isEnabled() {
File folder = ArchiPlugin.INSTANCE.getUserDataFolder();
return folder != null && folder.exists() && Desktop.getDesktop().isSupported(Action.OPEN);
}
}
| /**
* This program and the accompanying materials
* are made available under the terms of the License
* which accompanies this distribution in the file LICENSE.txt
*/
package com.archimatetool.editor.actions;
import java.awt.Desktop;
import java.awt.Desktop.Action;
import java.io.File;
import java.io.IOException;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.runtime.Platform;
import org.eclipse.osgi.service.datalocation.Location;
/**
* Open Archi Data folder
*
* @author Phillip Beauvoir
*/
public class OpenDataFolderHandler extends AbstractHandler {
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
File folder = getInstanceLocation();
if(folder != null) {
try {
Desktop.getDesktop().open(folder);
}
catch(IOException ex) {
ex.printStackTrace();
}
}
return null;
}
private File getInstanceLocation() {
Location instanceLoc = Platform.getInstanceLocation();
if(instanceLoc != null && instanceLoc.getURL() != null) {
return new File(Platform.getInstanceLocation().getURL().getPath());
}
return null;
}
@Override
public boolean isEnabled() {
File folder = getInstanceLocation();
return folder != null && folder.exists() && Desktop.getDesktop().isSupported(Action.OPEN);
}
}
|
Fix bug in web UI | if (document.body.className.indexOf("no-contains-view")>-1) {
console.log("No view detected");
} else {
var cvbtn = document.querySelector(".view-buttons .cards");
var lvbtn = document.querySelector(".view-buttons .list");
var vlst = document.querySelector(".view");
var listView = function () {
cvbtn.classList.remove("active");
lvbtn.classList.add("active");
vlst.classList.remove("cards");
vlst.classList.add("list");
localStorage.setItem("view", "list");
}
var cardsView = function () {
lvbtn.classList.remove("active");
cvbtn.classList.add("active");
vlst.classList.remove("list");
vlst.classList.add("cards");
localStorage.setItem("view", "cards");
}
var restoreView = function () {
if (window.localStorage) {
var v = localStorage.getItem("view");
if (v !== null) {
if (v == "list") {
listView();
} else {
cardsView();
}
} else {
cardsView();
}
} else {
cardsView();
}
}
lvbtn.addEventListener("click", listView);
cvbtn.addEventListener("click", cardsView);
restoreView();
} | if (document.body.className.indexOf("no-contains-view")>-1) {
console.log("No view detected");
} else {
var cvbtn = document.querySelector(".view-buttons .cards");
var lvbtn = document.querySelector(".view-buttons .list");
var vlst = document.querySelector(".view");
var listView = function () {
cvbtn.classList.remove("active");
lvbtn.classList.add("active");
vlst.classList.remove("cards");
vlst.classList.add("list");
localStorage.setItem("view", "list");
}
var cardsView = function () {
lvbtn.classList.remove("active");
cvbtn.classList.add("active");
vlst.classList.remove("list");
vlst.classList.add("cards");
localStorage.setItem("view", "cards");
}
var restoreView = function () {
if (localStorage in window) {
var v = localStorage.getItem("view");
if (v !== null) {
if (v == "list") {
listView();
} else {
cardsView();
}
} else {
cardsView();
}
} else {
cardsView();
}
}
lvbtn.addEventListener("click", listView);
cvbtn.addEventListener("click", cardsView);
restoreView();
} |
[AC-5625] Address CodeClimate cognitive complexity concern | # MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from django.db.models import Q
from impact.v1.helpers.criterion_helper import CriterionHelper
class MatchingCriterionHelper(CriterionHelper):
def __init__(self, subject):
super().__init__(subject)
self._app_ids_to_targets = {}
self._target_counts = {}
def app_count(self, apps, option_name):
return self.target_counts(apps).get(option_name, 0)
def refine_feedbacks(self, feedbacks, target, refinement):
if not target:
return None
query = Q(**{refinement: target})
return feedbacks.filter(query)
def find_app_ids(self, feedbacks, apps, target):
if not feedbacks:
return []
result = []
app_map = self.app_ids_to_targets(apps)
return [app_id for app_id in
feedbacks.values_list("application_id", flat=True)
if app_id in app_map and app_map[app_id] == target.id]
def app_ids_to_targets(self, apps):
if not self._app_ids_to_targets:
self.calc_app_ids_to_targets(apps)
return self._app_ids_to_targets
def target_counts(self, apps):
if not self._app_ids_to_targets:
self.calc_app_ids_to_targets(apps)
return self._target_counts
| # MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from django.db.models import Q
from impact.v1.helpers.criterion_helper import CriterionHelper
class MatchingCriterionHelper(CriterionHelper):
def __init__(self, subject):
super().__init__(subject)
self._app_ids_to_targets = {}
self._target_counts = {}
def app_count(self, apps, option_name):
return self.target_counts(apps).get(option_name, 0)
def refine_feedbacks(self, feedbacks, target, refinement):
if not target:
return None
query = Q(**{refinement: target})
return feedbacks.filter(query)
def find_app_ids(self, feedbacks, apps, target):
result = []
if feedbacks:
app_map = self.app_ids_to_targets(apps)
for app_id in feedbacks.values_list("application_id", flat=True):
if app_id in app_map and app_map[app_id] == target.id:
result.append(app_id)
return result
def app_ids_to_targets(self, apps):
if not self._app_ids_to_targets:
self.calc_app_ids_to_targets(apps)
return self._app_ids_to_targets
def target_counts(self, apps):
if not self._app_ids_to_targets:
self.calc_app_ids_to_targets(apps)
return self._target_counts
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.