text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Add select part test for invalid column name | <?php
use Mdd\QueryBuilder\Queries\Parts;
class SelectPartBuilderTest extends PHPUnit_Framework_TestCase
{
/**
* @dataProvider providerTestSelectViaConstructor
*/
public function testSelectViaConstructor($expected, $columns)
{
$select = new Parts\Select($columns);
$this->assertSame($expected, $select->toString());
}
/**
* @dataProvider providerTestSelectViaConstructor
*/
public function testSelectViaSetter($expected, $columns)
{
$select = new Parts\Select();
$select->select($columns);
$this->assertSame($expected, $select->toString());
}
public function providerTestSelectViaConstructor()
{
return array(
'single column' => array('SELECT name', 'name'),
'multiple column' => array('SELECT name, color, age', array('name', 'color', 'age')),
'duplicated columns' => array('SELECT name, color, age', array('name', 'color', 'age', 'name')),
'all columns' => array('SELECT *', '*'),
);
}
public function testAddColumnsOnTheFly()
{
$select = new Parts\Select('id');
$select
->select('name')
->select(array('color', 'taste'));
$this->assertSame('SELECT id, name, color, taste', $select->toString());
}
/**
* @expectedException \InvalidArgumentException
*/
public function testInvalidColumnName()
{
$select = new Parts\Select(array('poney', new stdClass()));
$select->toString();
}
} | <?php
use Mdd\QueryBuilder\Queries\Parts;
class SelectPartBuilderTest extends PHPUnit_Framework_TestCase
{
/**
* @dataProvider providerTestSelectViaConstructor
*/
public function testSelectViaConstructor($expected, $columns)
{
$select = new Parts\Select($columns);
$this->assertSame($expected, $select->toString());
}
/**
* @dataProvider providerTestSelectViaConstructor
*/
public function testSelectViaSetter($expected, $columns)
{
$select = new Parts\Select();
$select->select($columns);
$this->assertSame($expected, $select->toString());
}
public function providerTestSelectViaConstructor()
{
return array(
'single column' => array('SELECT name', 'name'),
'multiple column' => array('SELECT name, color, age', array('name', 'color', 'age')),
'duplicated columns' => array('SELECT name, color, age', array('name', 'color', 'age', 'name')),
'all columns' => array('SELECT *', '*'),
);
}
public function testAddColumnsOnTheFly()
{
$select = new Parts\Select('id');
$select
->select('name')
->select(array('color', 'taste'));
$this->assertSame('SELECT id, name, color, taste', $select->toString());
}
} |
Simplify loading of Quarkus CLI version | package io.quarkus.cli.core;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.util.Properties;
import io.smallrye.common.classloader.ClassPathUtils;
import picocli.CommandLine;
public class QuarkusCliVersion implements CommandLine.IVersionProvider {
private static String version;
public static String version() {
if (version != null) {
return version;
}
final Properties props = new Properties();
final URL quarkusPropertiesUrl = Thread.currentThread().getContextClassLoader().getResource("quarkus.properties");
if (quarkusPropertiesUrl == null) {
throw new RuntimeException("Failed to locate quarkus.properties on the classpath");
}
// we have a special case for file and jar as using getResourceAsStream() on Windows might cause file locks
if ("file".equals(quarkusPropertiesUrl.getProtocol()) || "jar".equals(quarkusPropertiesUrl.getProtocol())) {
ClassPathUtils.consumeAsPath(quarkusPropertiesUrl, p -> {
try (BufferedReader reader = Files.newBufferedReader(p)) {
props.load(reader);
} catch (IOException e) {
throw new RuntimeException("Failed to load quarkus.properties", e);
}
});
} else {
try {
props.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("quarkus.properties"));
} catch (IOException e) {
throw new IllegalStateException("Failed to load quarkus.properties", e);
}
}
version = props.getProperty("quarkus-core-version");
if (version == null) {
throw new RuntimeException("Failed to locate quarkus-core-version property in the bundled quarkus.properties");
}
return version;
}
@Override
public String[] getVersion() throws Exception {
return new String[] { version() };
}
}
| package io.quarkus.cli.core;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.util.Properties;
import io.smallrye.common.classloader.ClassPathUtils;
import picocli.CommandLine;
public class QuarkusCliVersion implements CommandLine.IVersionProvider {
private static String version;
public static String version() {
if (version != null) {
return version;
}
final URL quarkusPropsUrl = Thread.currentThread().getContextClassLoader().getResource("quarkus.properties");
if (quarkusPropsUrl == null) {
throw new RuntimeException("Failed to locate quarkus.properties on the classpath");
}
final Properties props = new Properties();
ClassPathUtils.consumeAsPath(quarkusPropsUrl, p -> {
try (BufferedReader reader = Files.newBufferedReader(p)) {
props.load(reader);
} catch (IOException e) {
throw new RuntimeException("Failed to load quarkus.properties", e);
}
});
version = props.getProperty("quarkus-core-version");
if (version == null) {
throw new RuntimeException("Failed to locate quarkus-core-version property in the bundled quarkus.properties");
}
return version;
}
@Override
public String[] getVersion() throws Exception {
return new String[] { version() };
}
}
|
Use justify-content-center on the manga list row.
Basically just centers the columns. | <div class="row">
<div class="col-12">
@if (isset($header))
<h3 class="text-center">
<b>{{ $header }}</b>
</h3>
@endif
</div>
</div>
<div class="row justify-content-center">
@if (isset($manga_list))
@foreach ($manga_list as $manga)
<div class="col-6 col-sm-4 col-md-3 col-xl-2">
<div class="card mt-1 mb-1">
<a href="{{ URL::action('MangaController@index', [$manga]) }}">
<img class="card-img-top" src="{{ URL::action('CoverController@smallDefault', [$manga]) }}">
</a>
<div class="card-footer text-center pt-2 pb-0">
<div class="card-title" title="{{ $manga->name }}">
<a class="card-link" href="{{ URL::action('MangaController@index', [$manga]) }}">{{ $manga->name }}</a>
</div>
</div>
</div>
</div>
@endforeach
@else
@endif
</div>
<div class="row mt-3">
<div class="col-12">
@if (isset($manga_list))
{{ $manga_list->render('vendor.pagination.bootstrap-4') }}
@endif
</div>
</div> | <div class="row">
<div class="col-12">
@if (isset($header))
<h3 class="text-center">
<b>{{ $header }}</b>
</h3>
@endif
</div>
</div>
<div class="row">
@if (isset($manga_list))
@foreach ($manga_list as $manga)
<div class="col-6 col-sm-4 col-md-3 col-xl-2">
<div class="card mt-1 mb-1">
<a href="{{ URL::action('MangaController@index', [$manga]) }}">
<img class="card-img-top" src="{{ URL::action('CoverController@smallDefault', [$manga]) }}">
</a>
<div class="card-footer text-center pt-2 pb-0">
<div class="card-title" title="{{ $manga->name }}">
<a class="card-link" href="{{ URL::action('MangaController@index', [$manga]) }}">{{ $manga->name }}</a>
</div>
</div>
</div>
</div>
@endforeach
@else
@endif
</div>
<div class="row mt-3">
<div class="col-12">
@if (isset($manga_list))
{{ $manga_list->render('vendor.pagination.bootstrap-4') }}
@endif
</div>
</div> |
Delete unnecessary vars attr of Proj | """proj.py: aospy.Proj class for organizing work in single project."""
import time
from .utils import dict_name_keys
class Proj(object):
"""Project parameters: models, regions, directories, etc."""
def __init__(self, name, vars={}, models={}, default_models={}, regions={},
direc_out='', nc_dir_struc=False, verbose=True):
self.verbose = verbose
if self.verbose:
print ("Initializing Project instance: %s (%s)"
% (name, time.ctime()))
self.name = name
self.direc_out = direc_out
self.nc_dir_struc = nc_dir_struc
if models:
self.models = dict_name_keys(models)
else:
self.models = {}
if default_models == 'all':
self.default_models = self.models
elif default_models:
self.default_models = dict_name_keys(default_models)
else:
self.default_models = {}
if regions:
self.regions = dict_name_keys(regions)
else:
self.regions = {}
for obj_dict in (self.models, self.regions):
for obj in obj_dict.values():
setattr(obj, 'proj', self)
def __str__(self):
return 'Project instance "' + self.name + '"'
__repr__ = __str__
| """proj.py: aospy.Proj class for organizing work in single project."""
import time
from .utils import dict_name_keys
class Proj(object):
"""Project parameters: models, regions, directories, etc."""
def __init__(self, name, vars={}, models={}, default_models={}, regions={},
direc_out='', nc_dir_struc=False, verbose=True):
self.verbose = verbose
if self.verbose:
print ("Initializing Project instance: %s (%s)"
% (name, time.ctime()))
self.name = name
self.direc_out = direc_out
self.nc_dir_struc = nc_dir_struc
self.vars = dict_name_keys(vars)
if models:
self.models = dict_name_keys(models)
else:
self.models = {}
if default_models == 'all':
self.default_models = self.models
elif default_models:
self.default_models = dict_name_keys(default_models)
else:
self.default_models = {}
if regions:
self.regions = dict_name_keys(regions)
else:
self.regions = {}
for obj_dict in (self.vars, self.models, self.regions):
for obj in obj_dict.values():
setattr(obj, 'proj', self)
def __str__(self):
return 'Project instance "' + self.name + '"'
__repr__ = __str__
|
Test requests don't have a charset attribute | import json
import functools
from django.conf import settings
from django.test import Client, TestCase
__all__ = ['JsonTestClient', 'JsonTestMixin', 'JsonTestCase']
class JsonTestClient(Client):
def _json_request(self, method, url, data=None, *args, **kwargs):
method_func = getattr(super(JsonTestClient, self), method)
if method == 'get':
encode = lambda x: x
else:
encode = json.dumps
if data is not None:
resp = method_func(url, encode(data), content_type='application/json', *args, **kwargs)
else:
resp = method_func(url, content_type='application/json', *args, **kwargs)
if resp['Content-Type'].startswith('application/json') and resp.content:
charset = resp.charset if hasattr(resp, 'charset') else settings.DEFAULT_CHARSET
resp.json = json.loads(resp.content.decode(charset))
return resp
def __getattribute__(self, attr):
if attr in ('get', 'post', 'put', 'delete', 'trace', 'head', 'patch', 'options'):
return functools.partial(self._json_request, attr)
else:
return super(JsonTestClient, self).__getattribute__(attr)
class JsonTestMixin(object):
client_class = JsonTestClient
class JsonTestCase(JsonTestMixin, TestCase):
pass
| import json
import functools
from django.conf import settings
from django.test import Client, TestCase
__all__ = ['JsonTestClient', 'JsonTestMixin', 'JsonTestCase']
class JsonTestClient(Client):
def _json_request(self, method, url, data=None, *args, **kwargs):
method_func = getattr(super(JsonTestClient, self), method)
if method == 'get':
encode = lambda x: x
else:
encode = json.dumps
if data is not None:
resp = method_func(url, encode(data), content_type='application/json', *args, **kwargs)
else:
resp = method_func(url, content_type='application/json', *args, **kwargs)
if resp['Content-Type'].startswith('application/json') and resp.content:
charset = resp.charset or settings.DEFAULT_CHARSET
resp.json = json.loads(resp.content.decode(charset))
return resp
def __getattribute__(self, attr):
if attr in ('get', 'post', 'put', 'delete', 'trace', 'head', 'patch', 'options'):
return functools.partial(self._json_request, attr)
else:
return super(JsonTestClient, self).__getattribute__(attr)
class JsonTestMixin(object):
client_class = JsonTestClient
class JsonTestCase(JsonTestMixin, TestCase):
pass
|
Fix test to reflect changes to welcome email | import time
from ..utils.log import log, INFO, ERROR, PASS
from ..utils.i_selenium import assert_tab, image_div
from ..tests import TestWithDependency
__all__ = ["welcome_email"]
#####
# Test : Welcome Email Recieved
#####
@TestWithDependency("WELCOME_EMAIL", ["SIGNUP"])
def welcome_email(driver, inbox, GUERRILLAMAIL, WAIT_DUR, **kwargs):
"""Test if the registration confirmation/welcome email is recieved.
- 'driver' should be a Selenium WebDriver.
- 'inbox' should be a GuerrillaInbox object.
- 'GUERRILLAMAIL' is the string URL of GuerrillaMail.
"""
assert_tab(driver, GUERRILLAMAIL)
inbox.wait_for_email(WAIT_DUR)
log(INFO, "GuerrillaMail: Access welcome email in inbox.")
try:
welcome_emails = inbox.get_by_subject("Welcome to Isaac!")
assert len(welcome_emails) == 1, "Expected to recieve a welcome email, recieved %s emails!" % len(welcome_emails)
welcome_email = welcome_emails[0]
log(INFO, "Got welcome email as expected.")
welcome_email.image()
welcome_email.save_html_body()
log(PASS, "Welcome email recieved!")
return True
except AssertionError, e:
image_div(driver, "ERROR_not_isaac_email")
log(ERROR, e.message + " See 'ERROR_not_isaac_email.png'!")
return False
| import time
from ..utils.log import log, INFO, ERROR, PASS
from ..utils.i_selenium import assert_tab, image_div
from ..tests import TestWithDependency
__all__ = ["welcome_email"]
#####
# Test : Welcome Email Recieved
#####
@TestWithDependency("WELCOME_EMAIL", ["SIGNUP"])
def welcome_email(driver, inbox, GUERRILLAMAIL, WAIT_DUR, **kwargs):
"""Test if the registration confirmation/welcome email is recieved.
- 'driver' should be a Selenium WebDriver.
- 'inbox' should be a GuerrillaInbox object.
- 'GUERRILLAMAIL' is the string URL of GuerrillaMail.
"""
assert_tab(driver, GUERRILLAMAIL)
inbox.wait_for_email(WAIT_DUR)
log(INFO, "GuerrillaMail: Access welcome email in inbox.")
try:
welcome_emails = inbox.get_by_subject("Welcome to Isaac Physics!")
assert len(welcome_emails) == 1, "Expected to recieve a welcome email, recieved %s emails!" % len(welcome_emails)
welcome_email = welcome_emails[0]
log(INFO, "Got welcome email as expected.")
welcome_email.image()
welcome_email.save_html_body()
log(PASS, "Welcome email recieved!")
return True
except AssertionError, e:
image_div(driver, "ERROR_not_isaac_email")
log(ERROR, e.message + " See 'ERROR_not_isaac_email.png'!")
return False
|
Allow to disable events persistence at app class | from abc import abstractmethod, ABCMeta
from six import with_metaclass
from eventsourcing.infrastructure.event_store import EventStore
from eventsourcing.infrastructure.persistence_subscriber import PersistenceSubscriber
class EventSourcingApplication(with_metaclass(ABCMeta)):
persist_events = True
def __init__(self, json_encoder_cls=None, json_decoder_cls=None, cipher=None, always_encrypt_stored_events=False):
self.stored_event_repo = self.create_stored_event_repo(json_encoder_cls=json_encoder_cls,
json_decoder_cls=json_decoder_cls,
cipher=cipher,
always_encrypt=always_encrypt_stored_events)
self.event_store = self.create_event_store()
if self.persist_events:
self.persistence_subscriber = self.create_persistence_subscriber()
else:
self.persistence_subscriber = None
@abstractmethod
def create_stored_event_repo(self, **kwargs):
"""Returns an instance of a subclass of StoredEventRepository.
:rtype: StoredEventRepository
"""
def create_event_store(self):
return EventStore(self.stored_event_repo)
def create_persistence_subscriber(self):
return PersistenceSubscriber(self.event_store)
def close(self):
if self.persistence_subscriber:
self.persistence_subscriber.close()
self.stored_event_repo = None
self.event_store = None
self.persistence_subscriber = None
def __enter__(self):
return self
def __exit__(self, *_):
self.close()
| from abc import abstractmethod, ABCMeta
from six import with_metaclass
from eventsourcing.infrastructure.event_store import EventStore
from eventsourcing.infrastructure.persistence_subscriber import PersistenceSubscriber
class EventSourcingApplication(with_metaclass(ABCMeta)):
def __init__(self, json_encoder_cls=None, json_decoder_cls=None, cipher=None, always_encrypt_stored_events=False):
self.stored_event_repo = self.create_stored_event_repo(json_encoder_cls=json_encoder_cls,
json_decoder_cls=json_decoder_cls,
cipher=cipher,
always_encrypt=always_encrypt_stored_events)
self.event_store = self.create_event_store()
self.persistence_subscriber = self.create_persistence_subscriber()
@abstractmethod
def create_stored_event_repo(self, **kwargs):
"""Returns an instance of a subclass of StoredEventRepository.
:rtype: StoredEventRepository
"""
def create_event_store(self):
return EventStore(self.stored_event_repo)
def create_persistence_subscriber(self):
return PersistenceSubscriber(self.event_store)
def close(self):
self.persistence_subscriber.close()
self.stored_event_repo = None
self.event_store = None
self.persistence_subscriber = None
def __enter__(self):
return self
def __exit__(self, *_):
self.close()
|
Use System.get instead of System.import
All of the modules we import should already be loaded, and we don't
want to ever attempt to import them anyway because we do not include a
Promise polyfill. | <!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>{{ $title }}</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1">
<meta name="theme-color" content="{{ $forum->attributes->themePrimaryColor }}">
@foreach ($styles as $file)
<link rel="stylesheet" href="{{ str_replace(public_path(), '', $file) }}">
@endforeach
{!! $head !!}
</head>
<body>
{!! $layout !!}
<div id="modal"></div>
<div id="alerts"></div>
@foreach ($scripts as $file)
<script src="{{ str_replace(public_path(), '', $file) }}"></script>
@endforeach
<script>
try {
var app = System.get('flarum/app').default;
app.preload = {
data: {!! json_encode($data) !!},
document: {!! json_encode($document) !!},
session: {!! json_encode($session) !!}
};
@foreach ($bootstrappers as $bootstrapper)
System.get('{{ $bootstrapper }}');
@endforeach
app.boot();
} catch (e) {
document.write('<div class="container">Something went wrong.</div>');
throw e;
}
</script>
@if ($content)
<noscript>
{!! $content !!}
</noscript>
@endif
{!! $foot !!}
</body>
</html>
| <!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>{{ $title }}</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1">
<meta name="theme-color" content="{{ $forum->attributes->themePrimaryColor }}">
@foreach ($styles as $file)
<link rel="stylesheet" href="{{ str_replace(public_path(), '', $file) }}">
@endforeach
{!! $head !!}
</head>
<body>
{!! $layout !!}
<div id="modal"></div>
<div id="alerts"></div>
@foreach ($scripts as $file)
<script src="{{ str_replace(public_path(), '', $file) }}"></script>
@endforeach
<script>
try {
var app = System.get('flarum/app').default;
app.preload = {
data: {!! json_encode($data) !!},
document: {!! json_encode($document) !!},
session: {!! json_encode($session) !!}
};
@foreach ($bootstrappers as $bootstrapper)
System.import('{{ $bootstrapper }}');
@endforeach
app.boot();
} catch (e) {
document.write('<div class="container">Something went wrong.</div>');
throw e;
}
</script>
@if ($content)
<noscript>
{!! $content !!}
</noscript>
@endif
{!! $foot !!}
</body>
</html>
|
Remove printing of topics in bridge | import zmq
from argparse import ArgumentParser
from pymavlink import mavutil
def main():
parser = ArgumentParser()
parser.add_argument("--device", help="MAVLink device to add to zmq", required=True)
parser.add_argument("--zmq", help="zmq url", required=True)
args = parser.parse_args()
try:
msrc = mavutil.mavlink_connection(args.device, planner_format=False,
notimestamps=True, robust_parsing=True)
except Exception, e:
print 'Could not connect to mavlink device at %s' % args.device
print e
return False
context = zmq.Context()
zmq_socket = context.socket(zmq.PUB)
try:
zmq_socket.connect(args.zmq)
except Exception, e:
print 'Failed to establish connection with zmq gateway'
print e
#send messages from mavlink connection to zmq gateway
try:
while True:
mav_msg = msrc.recv_match()
if mav_msg is not None:
topic = mav_msg.get_type()
zmq_socket.send(topic,zmq.SNDMORE)
zmq_socket.send_pyobj(mav_msg)
except Exception, e:
print 'Bridge failed'
print e
zmq_socket.close()
context.term()
if __name__ == "__main__":
main()
| import zmq
from argparse import ArgumentParser
from pymavlink import mavutil
def main():
parser = ArgumentParser()
parser.add_argument("--device", help="MAVLink device to add to zmq", required=True)
parser.add_argument("--zmq", help="zmq url", required=True)
args = parser.parse_args()
try:
msrc = mavutil.mavlink_connection(args.device, planner_format=False,
notimestamps=True, robust_parsing=True)
except Exception, e:
print 'Could not connect to mavlink device at %s' % args.device
print e
return False
context = zmq.Context()
zmq_socket = context.socket(zmq.PUB)
try:
zmq_socket.connect(args.zmq)
except Exception, e:
print 'Failed to establish connection with zmq gateway'
print e
#send messages from mavlink connection to zmq gateway
try:
while True:
mav_msg = msrc.recv_match()
if mav_msg is not None:
topic = mav_msg.get_type()
print topic
zmq_socket.send(topic,zmq.SNDMORE)
zmq_socket.send_pyobj(mav_msg)
except Exception, e:
print 'Bridge failed'
print e
zmq_socket.close()
context.term()
if __name__ == "__main__":
main()
|
Fix message escaping to be the same as in the init script
This adjustment is done to have the same character escaping as in the PR provided by the TeamCity folks from JetBrains, assuming their encoding code is correct and not the one that was previously used by this plugin. | package nu.studer.teamcity.buildscan.agent.servicemessage;
final class ServiceMessage {
private static final String SERVICE_MESSAGE_START = "##teamcity[";
private static final String SERVICE_MESSAGE_END = "]";
private final String name;
private final String argument;
private ServiceMessage(String name, String argument) {
this.name = name;
this.argument = argument;
}
static ServiceMessage of(String name, String argument) {
return new ServiceMessage(name, argument);
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(SERVICE_MESSAGE_START);
sb.append(name);
sb.append(' ');
sb.append('\'');
sb.append(escape(argument));
sb.append('\'');
sb.append(SERVICE_MESSAGE_END);
return sb.toString();
}
private String escape(String s) {
StringBuilder sb = new StringBuilder();
for (char c : s.toCharArray()) {
sb.append(escape(c));
}
return sb.toString();
}
private String escape(char c) {
String escapeCharacter = "|";
switch (c) {
case '\n':
return escapeCharacter + "n";
case '\r':
return escapeCharacter + "r";
case '|':
return escapeCharacter + "|";
case '\'':
return escapeCharacter + "\'";
case '[':
return escapeCharacter + "[";
case ']':
return escapeCharacter + "]";
default:
return c < 128 ? Character.toString(c) : escapeCharacter + String.format("0x%04x", (int) c);
}
}
}
| package nu.studer.teamcity.buildscan.agent.servicemessage;
final class ServiceMessage {
private static final String SERVICE_MESSAGE_START = "##teamcity[";
private static final String SERVICE_MESSAGE_END = "]";
private final String name;
private final String argument;
private ServiceMessage(String name, String argument) {
this.name = name;
this.argument = argument;
}
static ServiceMessage of(String name, String argument) {
return new ServiceMessage(name, argument);
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(SERVICE_MESSAGE_START);
sb.append(name);
sb.append(' ');
sb.append('\'');
sb.append(escape(argument));
sb.append('\'');
sb.append(SERVICE_MESSAGE_END);
return sb.toString();
}
private String escape(String s) {
StringBuilder sb = new StringBuilder();
for (char c : s.toCharArray()) {
sb.append(escape(c));
}
return sb.toString();
}
private String escape(final char c) {
switch (c) {
case '\n':
return "n";
case '\r':
return "r";
case '|':
return "|";
case '\'':
return "\'";
case '[':
return "[";
case ']':
return "]";
default:
return c < 128 ? Character.toString(c) : String.format("0x%04x", (int) c);
}
}
}
|
Make sure the package is exported by distutils | from distutils.core import setup, Extension
import numpy.distutils.misc_util
module = Extension(
'cnaturalneighbor',
include_dirs=numpy.distutils.misc_util.get_numpy_include_dirs(),
library_dirs=['/usr/local/lib'],
extra_compile_args=['--std=c++11'],
sources=[
'naturalneighbor/cnaturalneighbor.cpp',
],
)
setup(
name='naturalneighbor',
version='0.1.3',
description='Fast, discrete natural neighbor interpolation in 3D on a CPU.',
long_description=open('README.rst', 'r').read(),
author='Reece Stevens',
author_email='[email protected]',
license='MIT',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: Implementation :: CPython',
'Topic :: Scientific/Engineering',
'Topic :: Software Development',
],
keywords='interpolation scipy griddata numpy sibson',
install_requires=[
'numpy>=1.13',
],
url='https://github.com/innolitics/natural-neighbor-interpolation',
ext_modules=[module],
packages=['naturalneighbor'],
)
| from distutils.core import setup, Extension
import numpy.distutils.misc_util
module = Extension(
'cnaturalneighbor',
include_dirs=numpy.distutils.misc_util.get_numpy_include_dirs(),
library_dirs=['/usr/local/lib'],
extra_compile_args=['--std=c++11'],
sources=[
'naturalneighbor/cnaturalneighbor.cpp',
],
)
setup(
name='naturalneighbor',
version='0.1.3',
description='Fast, discrete natural neighbor interpolation in 3D on a CPU.',
long_description=open('README.rst', 'r').read(),
author='Reece Stevens',
author_email='[email protected]',
license='MIT',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: Implementation :: CPython',
'Topic :: Scientific/Engineering',
'Topic :: Software Development',
],
keywords='interpolation scipy griddata numpy sibson',
install_requires=[
'numpy>=1.13',
],
url='https://github.com/innolitics/natural-neighbor-interpolation',
ext_modules=[module],
)
|
Fix existing auto join specification tests. | <?php
namespace spec\RulerZ\Executor\DoctrineQueryBuilder;
use Doctrine\ORM\QueryBuilder;
use Doctrine\ORM\Query\Expr\Join;
use PhpSpec\ObjectBehavior;
use RulerZ\Executor\DoctrineQueryBuilder\AutoJoin;
class AutoJoinSpec extends ObjectBehavior
{
function let(QueryBuilder $target)
{
$this->beConstructedWith($target, [
['group']
]);
}
function it_joins_needed_tables(QueryBuilder $target)
{
$target->getEntityManager()->shouldBeCalled();
$target->getRootEntities()->willReturn([]);
$target->getRootAliases()->willReturn(['root_alias']);
$target->getDQLPart('join')->willReturn([]);
$target->join('root_alias.group', 'rulerz_group')->shouldBeCalled();
$this->getJoinAlias('group')->shouldReturn(AutoJoin::ALIAS_PREFIX . 'group');
}
function it_uses_joined_tables(QueryBuilder $target, Join $join)
{
$target->getEntityManager()->shouldBeCalled();
$target->getRootEntities()->willReturn([]);
$target->getRootAliases()->willReturn(['root_alias']);
$target->getDQLPart('join')->willReturn([
'root_alias' => [$join]
]);
$join->getJoin()->willReturn('root_alias.group');
$join->getAlias()->willReturn('aliased_group');
$target->join('root_alias.group', 'rulerz_aliased_group')->shouldNotBeCalled();
$this->getJoinAlias('aliased_group')->shouldReturn('aliased_group');
}
}
| <?php
namespace spec\RulerZ\Executor\DoctrineQueryBuilder;
use Doctrine\ORM\QueryBuilder;
use Doctrine\ORM\Query\Expr\Join;
use PhpSpec\ObjectBehavior;
use RulerZ\Executor\DoctrineQueryBuilder\AutoJoin;
class AutoJoinSpec extends ObjectBehavior
{
function let(QueryBuilder $target)
{
$this->beConstructedWith($target, [
['group']
]);
}
function it_joins_needed_tables(QueryBuilder $target)
{
$target->getRootAliases()->willReturn(['root_alias']);
$target->getDQLPart('join')->willReturn([]);
$target->join('root_alias.group', 'rulerz_group')->shouldBeCalled();
$this->getJoinAlias('group')->shouldReturn(AutoJoin::ALIAS_PREFIX . 'group');
}
function it_uses_joined_tables(QueryBuilder $target, Join $join)
{
$target->getRootAliases()->willReturn(['root_alias']);
$target->getDQLPart('join')->willReturn([
'root_alias' => [$join]
]);
$join->getJoin()->willReturn('root_alias.group');
$join->getAlias()->willReturn('aliased_group');
$target->join('root_alias.group', 'rulerz_aliased_group')->shouldNotBeCalled();
$this->getJoinAlias('aliased_group')->shouldReturn('aliased_group');
}
}
|
Remove the icon from the title bar on macOS | const {remote} = require('electron');
const Titlebar = React.createClass({
render: function () {
const w = {
min: () => {
const win = remote.getCurrentWindow()
win.minimize()
},
max: () => {
const win = remote.getCurrentWindow()
if (!win.isMaximized()) win.maximize()
else win.unmaximize()
},
quit: () => {
const win = remote.getCurrentWindow()
win.close()
},
}
let titleBarText;
if (this.props.platform === 'darwin') {
titleBarText = (<div className="titlebar--text">YouWatch</div>);
} else {
titleBarText = (
<div className="titlebar--text">
<img className="titlebar--icon" src="images/icon.png" />
YouWatch
</div>
);
}
return (
<div id="titlebar" data-platform={this.props.platform}>
{titleBarText}
<div className="titlebar--controls-wrapper">
<div className="titlebar--controls-minimize" onClick={w.min}>
<span></span>
</div>
<div className="titlebar--controls-maximize" onClick={w.max}>
<span></span>
<span className="bar2"></span>
</div>
<div className="titlebar--controls-close" onClick={w.quit}>
<span></span>
<span className="bar2"></span>
</div>
</div>
</div>
);
}
});
module.exports = Titlebar; | const {remote} = require('electron');
const Titlebar = React.createClass({
render: function () {
const w = {
min: () => {
const win = remote.getCurrentWindow()
win.minimize()
},
max: () => {
const win = remote.getCurrentWindow()
if (!win.isMaximized()) win.maximize()
else win.unmaximize()
},
quit: () => {
const win = remote.getCurrentWindow()
win.close()
},
}
return (
<div id="titlebar" data-platform={this.props.platform}>
<div className="titlebar--text">
<img className="titlebar--icon" src="images/icon.png" />
YouWatch
</div>
<div className="titlebar--controls-wrapper">
<div className="titlebar--controls-minimize" onClick={w.min}>
<span></span>
</div>
<div className="titlebar--controls-maximize" onClick={w.max}>
<span></span>
<span className="bar2"></span>
</div>
<div className="titlebar--controls-close" onClick={w.quit}>
<span></span>
<span className="bar2"></span>
</div>
</div>
</div>
);
}
});
module.exports = Titlebar; |
Add TODO task to security configuration. | package by.triumgroup.recourse.configuration.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
import javax.sql.DataSource;
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
private final DataSource dataSource;
@Autowired
public ResourceServerConfiguration(DataSource dataSource) {
this.dataSource = dataSource;
}
@Bean
public TokenStore tokenStore() {
return new JdbcTokenStore(dataSource);
}
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources
.tokenStore(tokenStore());
resources.stateless(false);
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
// TODO Need to be configured
.antMatchers("/**").permitAll()
.anyRequest().authenticated();
}
}
| package by.triumgroup.recourse.configuration.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
import javax.sql.DataSource;
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
private final DataSource dataSource;
@Autowired
public ResourceServerConfiguration(DataSource dataSource) {
this.dataSource = dataSource;
}
@Bean
public TokenStore tokenStore() {
return new JdbcTokenStore(dataSource);
}
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources
.tokenStore(tokenStore());
resources.stateless(false);
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/**").permitAll()
.anyRequest().authenticated();
}
}
|
Add back the xstyle and dojox svg modules correctly | // saves some loading time by loading most of the commonly-used
// JBrowse modules at the outset
require([
'JBrowse/Browser',
'JBrowse/ConfigAdaptor/JB_json_v1',
// default tracklist view
'JBrowse/View/TrackList/Hierarchical',
// common stores
'JBrowse/Store/Sequence/StaticChunked',
'JBrowse/Store/SeqFeature/NCList',
'JBrowse/Store/TiledImage/Fixed',
'JBrowse/Store/Names/Hash',
'JBrowse/Store/Names/REST',
// common track views
'JBrowse/View/Track/Sequence',
'JBrowse/View/Track/HTMLFeatures',
'JBrowse/View/Track/FixedImage/Wiggle',
'JBrowse/View/Track/Wiggle',
'JBrowse/View/Track/Wiggle/XYPlot',
'JBrowse/View/Track/Wiggle/Density',
'JBrowse/View/Track/Alignments',
'JBrowse/View/Track/Alignments2',
'JBrowse/View/Track/FeatureCoverage',
'JBrowse/View/Track/SNPCoverage',
// track lists
'JBrowse/Store/TrackMetaData',
'xstyle/core/load-css',
'dojox/gfx/svg'
]);
| // saves some loading time by loading most of the commonly-used
// JBrowse modules at the outset
require([
'JBrowse/Browser',
'JBrowse/ConfigAdaptor/JB_json_v1',
// default tracklist view
'JBrowse/View/TrackList/Hierarchical',
// common stores
'JBrowse/Store/Sequence/StaticChunked',
'JBrowse/Store/SeqFeature/NCList',
'JBrowse/Store/TiledImage/Fixed',
'JBrowse/Store/Names/Hash',
'JBrowse/Store/Names/REST',
// common track views
'JBrowse/View/Track/Sequence',
'JBrowse/View/Track/HTMLFeatures',
'JBrowse/View/Track/FixedImage/Wiggle',
'JBrowse/View/Track/Wiggle',
'JBrowse/View/Track/Wiggle/XYPlot',
'JBrowse/View/Track/Wiggle/Density',
'JBrowse/View/Track/Alignments',
'JBrowse/View/Track/Alignments2',
'JBrowse/View/Track/FeatureCoverage',
'JBrowse/View/Track/SNPCoverage',
// track lists
'JBrowse/Store/TrackMetaData'
]);
|
Add TODO about using an enum instead of an unconstrained string | package edu.northwestern.bioinformatics.studycalendar.domain;
import javax.persistence.Entity;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Transient;
/**
* @author Nataliya Shurupova
*/
@Entity
@DiscriminatorValue(value="2")
public class DayOfTheWeek extends Holiday {
// TODO: This ought to be the java.util.Calendar constant for the day, or a custom enum
private String dayOfTheWeek;
@Transient
public String getDisplayName() {
return getDayOfTheWeek();
}
@Transient
public int getDayOfTheWeekInteger() {
return mapDayNameToInteger(getDayOfTheWeek());
}
public String getDayOfTheWeek() {
return this.dayOfTheWeek;
}
public void setDayOfTheWeek(String dayOfTheWeek) {
this.dayOfTheWeek = dayOfTheWeek;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DayOfTheWeek that = (DayOfTheWeek) o;
if (dayOfTheWeek != null ? !dayOfTheWeek.equals(that.dayOfTheWeek) : that.dayOfTheWeek != null)
return false;
return true;
}
@Override
public String toString(){
StringBuffer sb = new StringBuffer();
sb.append("Id = ");
sb.append(getId());
sb.append(" DayOfTheWeek = ");
sb.append(getDayOfTheWeek());
sb.append(super.toString());
return sb.toString();
}
}
| package edu.northwestern.bioinformatics.studycalendar.domain;
import javax.persistence.Entity;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Transient;
/**
* @author Nataliya Shurupova
*/
@Entity
@DiscriminatorValue(value="2")
public class DayOfTheWeek extends Holiday {
private String dayOfTheWeek;
@Transient
public String getDisplayName() {
return getDayOfTheWeek();
}
@Transient
public int getDayOfTheWeekInteger() {
return mapDayNameToInteger(getDayOfTheWeek());
}
public String getDayOfTheWeek() {
return this.dayOfTheWeek;
}
public void setDayOfTheWeek(String dayOfTheWeek) {
this.dayOfTheWeek = dayOfTheWeek;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DayOfTheWeek that = (DayOfTheWeek) o;
if (dayOfTheWeek != null ? !dayOfTheWeek.equals(that.dayOfTheWeek) : that.dayOfTheWeek != null)
return false;
return true;
}
@Override
public String toString(){
StringBuffer sb = new StringBuffer();
sb.append("Id = ");
sb.append(getId());
sb.append(" DayOfTheWeek = ");
sb.append(getDayOfTheWeek());
sb.append(super.toString());
return sb.toString();
}
}
|
Add quick return if no trait entry ids are provided | <?php
namespace AppBundle\API\Details;
use AppBundle\Entity\Data\TraitCategoricalEntry;
use AppBundle\Entity\Data\TraitNumericalEntry;
use AppBundle\Service\DBVersion;
/**
* Web Service.
* Returns Trait Entry information
*/
class TraitEntries
{
private $manager;
private $known_trait_formats;
const ERROR_UNKNOWN_TRAIT_FORMAT = "Error. Unknown trait_format.";
/**
* TraitEntries constructor.
* @param $dbversion
*/
public function __construct(DBVersion $dbversion)
{
$this->manager = $dbversion->getDataEntityManager();
$this->known_trait_formats = array('categorical_free', 'numerical');
}
/**
* @param $traitFormat
* @param $traitEntryIds
* @returns array with details of the requested trait entries
*/
public function execute($traitEntryIds, $traitFormat)
{
if ($traitEntryIds === null || count($traitEntryIds) === 0){
return (array());
}
if (!in_array($traitFormat, $this->known_trait_formats)) {
return (array('error' => TraitEntries::ERROR_UNKNOWN_TRAIT_FORMAT));
}
if ($traitFormat === "categorical_free") {
$result = $this->manager->getRepository(TraitCategoricalEntry::class)->getTraitEntry($traitEntryIds);
} else {
$result = $this->manager->getRepository(TraitNumericalEntry::class)->getTraitEntry($traitEntryIds);
}
return $result;
}
}
| <?php
namespace AppBundle\API\Details;
use AppBundle\Entity\Data\TraitCategoricalEntry;
use AppBundle\Entity\Data\TraitNumericalEntry;
use AppBundle\Service\DBVersion;
/**
* Web Service.
* Returns Trait Entry information
*/
class TraitEntries
{
private $manager;
private $known_trait_formats;
const ERROR_UNKNOWN_TRAIT_FORMAT = "Error. Unknown trait_format.";
/**
* TraitEntries constructor.
* @param $dbversion
*/
public function __construct(DBVersion $dbversion)
{
$this->manager = $dbversion->getDataEntityManager();
$this->known_trait_formats = array('categorical_free', 'numerical');
}
/**
* @param $traitFormat
* @param $traitEntryIds
* @returns array with details of the requested trait entries
*/
public function execute($traitEntryIds, $traitFormat)
{
if (!in_array($traitFormat, $this->known_trait_formats)) {
return (array('error' => TraitEntries::ERROR_UNKNOWN_TRAIT_FORMAT));
}
if ($traitFormat === "categorical_free") {
$result = $this->manager->getRepository(TraitCategoricalEntry::class)->getTraitEntry($traitEntryIds);
} else {
$result = $this->manager->getRepository(TraitNumericalEntry::class)->getTraitEntry($traitEntryIds);
}
return $result;
}
}
|
Remove whitespace, and also add JSON url | from django.conf.urls import patterns, url
from swingtime import views
urlpatterns = patterns('',
url(
r'^(?:calendar/)?$',
views.today_view,
name='swingtime-today'
),
url(
r'^calendar/json/$',
views.CalendarJSONView.as_view(),
name='swingtime-calendar-json'
),
url(
r'^calendar/(?P<year>\d{4})/$',
views.year_view,
name='swingtime-yearly-view'
),
url(
r'^calendar/(\d{4})/(0?[1-9]|1[012])/$',
views.month_view,
name='swingtime-monthly-view'
),
url(
r'^calendar/(\d{4})/(0?[1-9]|1[012])/([0-3]?\d)/$',
views.day_view,
name='swingtime-daily-view'
),
url(
r'^events/$',
views.event_listing,
name='swingtime-events'
),
url(
r'^events/add/$',
views.add_event,
name='swingtime-add-event'
),
url(
r'^events/(\d+)/$',
views.event_view,
name='swingtime-event'
),
url(
r'^events/(\d+)/(\d+)/$',
views.occurrence_view,
name='swingtime-occurrence'
),
)
| from django.conf.urls import patterns, url
from swingtime import views
urlpatterns = patterns('',
url(
r'^(?:calendar/)?$',
views.today_view,
name='swingtime-today'
),
url(
r'^calendar/(?P<year>\d{4})/$',
views.year_view,
name='swingtime-yearly-view'
),
url(
r'^calendar/(\d{4})/(0?[1-9]|1[012])/$',
views.month_view,
name='swingtime-monthly-view'
),
url(
r'^calendar/(\d{4})/(0?[1-9]|1[012])/([0-3]?\d)/$',
views.day_view,
name='swingtime-daily-view'
),
url(
r'^events/$',
views.event_listing,
name='swingtime-events'
),
url(
r'^events/add/$',
views.add_event,
name='swingtime-add-event'
),
url(
r'^events/(\d+)/$',
views.event_view,
name='swingtime-event'
),
url(
r'^events/(\d+)/(\d+)/$',
views.occurrence_view,
name='swingtime-occurrence'
),
)
|
Revert "Fix bug in strategy"
This reverts commit 706d13192eff33a3c71d5279e50a2830fc9d6568.
Conflicts:
src/Engine/Strategy.java | package Engine;
import java.util.HashMap;
public class Strategy {
HashMap<String, Double> hotnessMap;
// bettingFunction is an array of length 5;
<<<<<<< HEAD
<<<<<<< HEAD
public Strategy() {
hotnessMap = new HashMap<String, Double>();
for (int i = 1; i < 14; i++) {
if (i == 1)
hotnessMap.put("A", 1.0);
else if (i == 11)
hotnessMap.put("J", 1.0);
else if (i == 12)
hotnessMap.put("Q", 1.0);
else if (i == 13)
hotnessMap.put("K", 1.0);
else
hotnessMap.put(i + "", 1.0);
}
}
double getHottnessForCard(Card card) {
return hotnessMap.get(card.getRank());
=======
=======
>>>>>>> parent of 706d131... Fix bug in strategy
public Strategy(double[] hotnessMap, int[] bettingFunction) {
this.hotnessMap = hotnessMap;
this.bettingFunction = bettingFunction;
}
double getHottnessForCard(Card card) {
return hotnessMap[card.getValues()[0] - 1];
<<<<<<< HEAD
>>>>>>> parent of 706d131... Fix bug in strategy
=======
>>>>>>> parent of 706d131... Fix bug in strategy
}
double getBetMultiplier(double hotness) {
return 1;
}
}
| package Engine;
import java.util.HashMap;
public class Strategy {
HashMap<String, Double> hotnessMap;
// bettingFunction is an array of length 5;
<<<<<<< HEAD
public Strategy() {
hotnessMap = new HashMap<String, Double>();
for (int i = 1; i < 14; i++) {
if (i == 1)
hotnessMap.put("A", 1.0);
else if (i == 11)
hotnessMap.put("J", 1.0);
else if (i == 12)
hotnessMap.put("Q", 1.0);
else if (i == 13)
hotnessMap.put("K", 1.0);
else
hotnessMap.put(i + "", 1.0);
}
}
double getHottnessForCard(Card card) {
return hotnessMap.get(card.getRank());
=======
public Strategy(double[] hotnessMap, int[] bettingFunction) {
this.hotnessMap = hotnessMap;
this.bettingFunction = bettingFunction;
}
double getHottnessForCard(Card card) {
return hotnessMap[card.getValues()[0] - 1];
>>>>>>> parent of 706d131... Fix bug in strategy
}
double getBetMultiplier(double hotness) {
return 1;
}
}
|
Support custom initializer in links.CRF1d | from chainer.functions.loss import crf1d
from chainer import link
from chainer import variable
class CRF1d(link.Link):
"""Linear-chain conditional random field loss layer.
This link wraps the :func:`~chainer.functions.crf1d` function.
It holds a transition cost matrix as a parameter.
Args:
n_label (int): Number of labels.
.. seealso:: :func:`~chainer.functions.crf1d` for more detail.
Attributes:
cost (~chainer.Variable): Transition cost parameter.
"""
def __init__(self, n_label, initialW=0):
super(CRF1d, self).__init__()
with self.init_scope():
self.cost = variable.Parameter(initializer=initialW,
shape=(n_label, n_label))
def forward(self, xs, ys, reduce='mean'):
return crf1d.crf1d(self.cost, xs, ys, reduce)
def argmax(self, xs):
"""Computes a state that maximizes a joint probability.
Args:
xs (list of Variable): Input vector for each label.
Returns:
tuple: A tuple of :class:`~chainer.Variable` representing each
log-likelihood and a list representing the argmax path.
.. seealso:: See :func:`~chainer.frunctions.crf1d_argmax` for more
detail.
"""
return crf1d.argmax_crf1d(self.cost, xs)
| from chainer.functions.loss import crf1d
from chainer import link
from chainer import variable
class CRF1d(link.Link):
"""Linear-chain conditional random field loss layer.
This link wraps the :func:`~chainer.functions.crf1d` function.
It holds a transition cost matrix as a parameter.
Args:
n_label (int): Number of labels.
.. seealso:: :func:`~chainer.functions.crf1d` for more detail.
Attributes:
cost (~chainer.Variable): Transition cost parameter.
"""
def __init__(self, n_label):
super(CRF1d, self).__init__()
with self.init_scope():
self.cost = variable.Parameter(0, (n_label, n_label))
def forward(self, xs, ys, reduce='mean'):
return crf1d.crf1d(self.cost, xs, ys, reduce)
def argmax(self, xs):
"""Computes a state that maximizes a joint probability.
Args:
xs (list of Variable): Input vector for each label.
Returns:
tuple: A tuple of :class:`~chainer.Variable` representing each
log-likelihood and a list representing the argmax path.
.. seealso:: See :func:`~chainer.frunctions.crf1d_argmax` for more
detail.
"""
return crf1d.argmax_crf1d(self.cost, xs)
|
Check for null exception on getSearchQuery | // Backbone.Collection.search-ajax v0.2
// by Joe Vu - [email protected]
// For all details and documentation:
// https://github.com/homeslicesolutions/backbone-collection-search
!function(_, Backbone){
// Extending out
_.extend(Backbone.Collection.prototype, {
//@ Search for AJAX version
search: function(keyword, attributes) {
// Closure
var that = this;
// Get new data
this.fetch({
parse: false,
data: {
keyword: keyword,
attributes: attributes
},
success: function( collection ){
// Instantiate new Collection
collection._searchQuery = keyword;
collection.getSearchQuery = function() {
return this._searchQuery;
}
// Cache the recently searched metadata
that._searchResults = collection;
// Fire search event with new collection
that.trigger('search', collection );
}
});
},
//@ Get recent search query
getSearchQuery: function() {
return this.getSearchResults() && this.getSearchResults().getSearchQuery();
},
//@ Get recent search results
getSearchResults: function() {
return this._searchResults;
},
//_Cache
_searchResults: null
});
}(_, Backbone);
| // Backbone.Collection.search-ajax v0.2
// by Joe Vu - [email protected]
// For all details and documentation:
// https://github.com/homeslicesolutions/backbone-collection-search
!function(_, Backbone){
// Extending out
_.extend(Backbone.Collection.prototype, {
//@ Search for AJAX version
search: function(keyword, attributes) {
// Closure
var that = this;
// Get new data
this.fetch({
parse: false,
data: {
keyword: keyword,
attributes: attributes
},
success: function( collection ){
// Instantiate new Collection
collection._searchQuery = keyword;
collection.getSearchQuery = function() {
return this._searchQuery;
}
// Cache the recently searched metadata
that._searchResults = collection;
// Fire search event with new collection
that.trigger('search', collection );
}
});
},
//@ Get recent search query
getSearchQuery: function() {
return this.getSearchResults().getSearchQuery();
},
//@ Get recent search results
getSearchResults: function() {
return this._searchResults;
},
//_Cache
_searchResults: null
});
}(_, Backbone); |
Update token renewal due to demo.scitokens.org API update | #!/usr/bin/python3
import os
import json
import time
from urllib import request
# Request payload
payload = {"aud": "ANY",
"ver": "scitokens:2.0",
"scope": "condor:/READ condor:/WRITE",
"exp": int(time.time() + 3600*8),
"sub": "abh3"
}
# Convert the format from dictionary to json string
data = json.dumps({
'payload': payload,
"algorithm": "ES256"
}).encode()
# Headers so that heroku doesn't block us
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3)' +
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36',
'Content-Type': 'application/json'
}
# The actual request
req = request.Request("https://demo.scitokens.org/issue",
data=data,
headers=headers) # this will make the method "POST"
resp = request.urlopen(req).read()
# Convert the "bytes" response to text
token_path = os.environ.get('BEARER_TOKEN', '') or \
f"/tmp/bt_u{os.geteuid()}"
with open(token_path, 'w') as f:
f.write(resp.decode('utf-8'))
| #!/usr/bin/python3
import os
import json
import time
from urllib import request
# Create the requested json
demo_json = {
"payload": {
"aud": "ANY",
"ver": "scitokens:2.0",
"scope": "condor:/READ condor:/WRITE",
"exp": int(time.time() + 3600*8),
"sub": "abh3"
}
}
# Convert the format from dictionary to json string
data = json.dumps({
'payload': json.dumps(demo_json['payload']),
"algorithm": "ES256"
}).encode()
# Headers so that heroku doesn't block us
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3)' +
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36',
'Content-Type': 'application/json'
}
# The actual request
req = request.Request("https://demo.scitokens.org/issue",
data=data,
headers=headers) # this will make the method "POST"
resp = request.urlopen(req).read()
# Convert the "bytes" response to text
token_path = os.environ.get('BEARER_TOKEN', '') or \
f"/tmp/bt_u{os.geteuid()}"
with open(token_path, 'w') as f:
f.write(resp.decode('utf-8'))
|
Make sure not to find the same error twice when comparing errors | const _ = require('lodash');
const chai = require('chai');
chai.use(function(_chai, utils) {
utils.addChainableMethod(chai.Assertion.prototype, 'haveErrors', function(...expectedErrors) {
const obj = utils.flag(this, 'object');
const actualErrors = obj.errors;
new chai.Assertion(actualErrors).to.be.an('array');
_.each(actualErrors, error => {
error.location = error.location.toString();
});
expectedErrors = _.flatten(expectedErrors);
const missingErrors = expectedErrors.slice();
const extraErrors = actualErrors.slice();
_.each(expectedErrors, expectedError => {
const matchingError = _.find(extraErrors, error => _.isEqual(error, expectedError));
if (matchingError) {
extraErrors.splice(extraErrors.indexOf(matchingError), 1);
missingErrors.splice(missingErrors.indexOf(matchingError), 1);
}
});
var messages = [];
if (missingErrors.length) {
messages.push(`The following errors were not found:\n${describeErrors(missingErrors)}`);
}
if (extraErrors.length) {
messages.push(`The following extra errors were found:\n${describeErrors(extraErrors)}`);
}
new chai.Assertion(obj.errors).assert(
_.isEmpty(messages),
`Expected specific errors.\n\n${messages.join('\n\n')}`,
`Expected different errors.\n\n${messages.join('\n\n')}`
);
});
});
function describeErrors(errors) {
return errors.map(error => JSON.stringify(error)).join('\n');
}
| const _ = require('lodash');
const chai = require('chai');
chai.use(function(_chai, utils) {
utils.addChainableMethod(chai.Assertion.prototype, 'haveErrors', function(...expectedErrors) {
const obj = utils.flag(this, 'object');
const actualErrors = obj.errors;
new chai.Assertion(actualErrors).to.be.an('array');
_.each(actualErrors, error => {
error.location = error.location.toString();
});
expectedErrors = _.flatten(expectedErrors);
const missingErrors = expectedErrors.slice();
const extraErrors = actualErrors.slice();
_.each(expectedErrors, expectedError => {
const matchingError = _.find(actualErrors, error => _.isEqual(error, expectedError));
if (matchingError) {
extraErrors.splice(extraErrors.indexOf(matchingError), 1);
missingErrors.splice(missingErrors.indexOf(matchingError), 1);
}
});
var messages = [];
if (missingErrors.length) {
messages.push(`The following errors were not found:\n${describeErrors(missingErrors)}`);
}
if (extraErrors.length) {
messages.push(`The following extra errors were found:\n${describeErrors(extraErrors)}`);
}
new chai.Assertion(obj.errors).assert(
_.isEmpty(messages),
`Expected specific errors.\n\n${messages.join('\n\n')}`,
`Expected different errors.\n\n${messages.join('\n\n')}`
);
});
});
function describeErrors(errors) {
return errors.map(error => JSON.stringify(error)).join('\n');
}
|
Fix nullPointerException on "edit" command | package seedu.task.model.task;
import seedu.task.commons.exceptions.IllegalValueException;
/**
* Represents a Task's name in the task manager.
* Guarantees: immutable; is valid as declared in {@link #isValidName(String)}
*/
public class TaskName {
public static final String MESSAGE_NAME_CONSTRAINTS = "Task names should be spaces or alphanumeric characters";
public static final String NAME_VALIDATION_REGEX = "[\\p{Alnum} ]+";
public final String fullName;
/**
* Validates given name.
*
* @throws IllegalValueException if given name string is invalid.
*/
public TaskName(String name) throws IllegalValueException {
assert name != null ;
if (name != null)
name = name.trim();
if (name == null || !isValidName(name)) {
throw new IllegalValueException(MESSAGE_NAME_CONSTRAINTS);
}
this.fullName = name;
}
/**
* Returns true if a given string is a valid task name.
*/
public static boolean isValidName(String test) {
return test.matches(NAME_VALIDATION_REGEX);
}
@Override
public String toString() {
return fullName;
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof TaskName // instanceof handles nulls
&& this.fullName.equals(((TaskName) other).fullName)); // state check
}
@Override
public int hashCode() {
return fullName.hashCode();
}
}
| package seedu.task.model.task;
import seedu.task.commons.exceptions.IllegalValueException;
/**
* Represents a Task's name in the task manager.
* Guarantees: immutable; is valid as declared in {@link #isValidName(String)}
*/
public class TaskName {
public static final String MESSAGE_NAME_CONSTRAINTS = "Task names should be spaces or alphanumeric characters";
public static final String NAME_VALIDATION_REGEX = "[\\p{Alnum} ]+";
public final String fullName;
/**
* Validates given name.
*
* @throws IllegalValueException if given name string is invalid.
*/
public TaskName(String name) throws IllegalValueException {
assert name != null;
name = name.trim();
if (!isValidName(name)) {
throw new IllegalValueException(MESSAGE_NAME_CONSTRAINTS);
}
this.fullName = name;
}
/**
* Returns true if a given string is a valid task name.
*/
public static boolean isValidName(String test) {
return test.matches(NAME_VALIDATION_REGEX);
}
@Override
public String toString() {
return fullName;
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof TaskName // instanceof handles nulls
&& this.fullName.equals(((TaskName) other).fullName)); // state check
}
@Override
public int hashCode() {
return fullName.hashCode();
}
}
|
Use === to test true | "use strict";
var React = require("react"),
request = require("superagent");
module.exports = React.createClass({
componentDidMount: function() {
request
.get("/api/ping/" + this.props.boardIp)
.end(function(err, res) {
if (err) {
console.log(err);
} else {
var state = null;
if (res.body === true) {
state = React.DOM.i({
className: "fa fa-check"
});
} else {
state = React.DOM.i({
className: "fa fa-times"
});
}
this.setState({
statelayout: state
});
}
}.bind(this));
},
getInitialState: function() {
return {
statelayout: React.DOM.i({
className: "fa fa-refresh fa-spin"
})
};
},
render: function() {
return React.DOM.div(
{
className: "card",
style: {
width: "20rem"
}
},
React.DOM.a(
{
className: "nav-link",
href: this.props.boardIp + "/"
},
React.DOM.div(
{
className: "card-body"
},
React.DOM.h4(
{
className: "card-title"
},
this.props.boardName
),
React.DOM.p(
{
className: "card-text"
},
this.props.boardIp
),
this.state.statelayout
)
)
);
}
});
| "use strict";
var React = require("react"),
request = require("superagent");
module.exports = React.createClass({
componentDidMount: function() {
request
.get("/api/ping/" + this.props.boardIp)
.end(function(err, res) {
if (err) {
console.log(err);
} else {
var state = null;
if (res.body) {
state = React.DOM.i({
className: "fa fa-check"
});
} else {
state = React.DOM.i({
className: "fa fa-times"
});
}
this.setState({
statelayout: state
});
}
}.bind(this));
},
getInitialState: function() {
return {
statelayout: React.DOM.i({
className: "fa fa-refresh fa-spin"
})
};
},
render: function() {
return React.DOM.div(
{
className: "card",
style: {
width: "20rem"
}
},
React.DOM.a(
{
className: "nav-link",
href: this.props.boardIp + "/"
},
React.DOM.div(
{
className: "card-body"
},
React.DOM.h4(
{
className: "card-title"
},
this.props.boardName
),
React.DOM.p(
{
className: "card-text"
},
this.props.boardIp
),
this.state.statelayout
)
)
);
}
});
|
Modify commit count str format | import datetime
from github import Github
from slack.slackbot import SlackerAdapter
from utils.config import Config
from utils.resource import MessageResource
class GithubManager(object):
def __init__(self):
self.config = Config().github
self.username = self.config["USERNAME"]
password = self.config["PASSWORD"]
self.github = Github(self.username, password)
self.slackbot = SlackerAdapter()
def daily_commit_check(self, channel="#personal_assistant"):
today = datetime.datetime.today()
today_date = datetime.datetime(today.year, today.month, today.day)
today_date_ko = today_date - datetime.timedelta(hours=9)
commit_events = []
for event in self.github.get_user(self.username).get_events():
if event.created_at > today_date_ko:
if event.type in ['PushEvent', 'PullRequestEvent']:
commit_events.append(event)
else:
break
if len(commit_events) == 0:
self.slackbot.send_message(channel=channel, text=MessageResource.GITHUB_COMMIT_EMPTY)
else:
self.slackbot.send_message(channel=channel, text=MessageResource.GITHUB_COMMIT_EXIST + str(len(commit_events)))
| import datetime
from github import Github
from slack.slackbot import SlackerAdapter
from utils.config import Config
from utils.resource import MessageResource
class GithubManager(object):
def __init__(self):
self.config = Config().github
self.username = self.config["USERNAME"]
password = self.config["PASSWORD"]
self.github = Github(self.username, password)
self.slackbot = SlackerAdapter()
def daily_commit_check(self, channel="#personal_assistant"):
today = datetime.datetime.today()
today_date = datetime.datetime(today.year, today.month, today.day)
today_date_ko = today_date - datetime.timedelta(hours=9)
commit_events = []
for event in self.github.get_user(self.username).get_events():
if event.created_at > today_date_ko:
if event.type in ['PushEvent', 'PullRequestEvent']:
commit_events.append(event)
else:
break
if len(commit_events) == 0:
self.slackbot.send_message(channel=channel, text=MessageResource.GITHUB_COMMIT_EMPTY)
else:
self.slackbot.send_message(channel=channel, text=MessageResource.GITHUB_COMMIT_EXIST + len(commit_events))
|
[showcase] Support ES7 in live example | /* globals babel */
// Dependencies
const {types} = Focus.component;
const LivePreview = React.createClass({
displayName: 'LivePreview',
propTypes: {
code: types('string'),
style: types('object')
},
style: {
title: {
margin: '15px',
color: '#372B3F'
},
component: {
padding: '5px'
}
},
/**
* Render the component.
* @return {HTML} the rendered component
*/
render() {
const {code, style: mainStyle} = this.props;
const {style} = this;
let content;
try {
/* eslint-disable */
content = eval(babel.transform(`(function(){${code}})()`, {stage: 0}).code);
/* eslint-enable */
} catch (e) {
content = e.toString();
}
return (
<div className='mdl-shadow--2dp' style={mainStyle}>
<h1 style={style.title}>Aperçu du composant</h1>
<hr/>
<div style={style.component}>
{content}
</div>
</div>
);
}
});
module.exports = LivePreview;
| /* globals babel */
// Dependencies
const {types} = Focus.component;
const LivePreview = React.createClass({
displayName: 'LivePreview',
propTypes: {
code: types('string'),
style: types('object')
},
style: {
title: {
margin: '15px',
color: '#372B3F'
},
component: {
padding: '5px'
}
},
/**
* Render the component.
* @return {HTML} the rendered component
*/
render() {
const {code, style: mainStyle} = this.props;
const {style} = this;
let content;
try {
/* eslint-disable */
content = eval(babel.transform(`(function(){${code}})()`).code);
/* eslint-enable */
} catch (e) {
content = e.toString();
}
return (
<div className='mdl-shadow--2dp' style={mainStyle}>
<h1 style={style.title}>Aperçu du composant</h1>
<hr/>
<div style={style.component}>
{content}
</div>
</div>
);
}
});
module.exports = LivePreview;
|
Add update method, remove getters..
This makes the osmNote work a bit more like other osm objects in iD.
- When working with the osm objects, we'll treat them as immutable.
So all modifications will be through the update method:
e.g. can do this in a repl, like chrome devtools console:
> n = iD.osmNote()
osmNote { id: -1 }
> n = n.update({ foo: 'bar' });
osmNote { foo: "bar", id: -1, v: 1 }
- none of the other osm objects have getters, and in JavaScript all the
properties are public anyway | import _extend from 'lodash-es/extend';
import { geoExtent } from '../geo';
export function osmNote() {
if (!(this instanceof osmNote)) {
return (new osmNote()).initialize(arguments);
} else if (arguments.length) {
this.initialize(arguments);
}
}
osmNote.id = function() {
return osmNote.id.next--;
};
osmNote.id.next = -1;
_extend(osmNote.prototype, {
type: 'note',
initialize: function(sources) {
for (var i = 0; i < sources.length; ++i) {
var source = sources[i];
for (var prop in source) {
if (Object.prototype.hasOwnProperty.call(source, prop)) {
if (source[prop] === undefined) {
delete this[prop];
} else {
this[prop] = source[prop];
}
}
}
}
if (!this.id) {
this.id = osmNote.id();
}
return this;
},
extent: function() {
return new geoExtent(this.loc);
},
update: function(attrs) {
return osmNote(this, attrs, {v: 1 + (this.v || 0)});
}
});
| import _extend from 'lodash-es/extend';
import { geoExtent } from '../geo';
export function osmNote() {
if (!(this instanceof osmNote)) {
return (new osmNote()).initialize(arguments);
} else if (arguments.length) {
this.initialize(arguments);
}
}
osmNote.id = function() {
return osmNote.id.next--;
};
osmNote.id.next = -1;
_extend(osmNote.prototype, {
type: 'note',
initialize: function(sources) {
for (var i = 0; i < sources.length; ++i) {
var source = sources[i];
for (var prop in source) {
if (Object.prototype.hasOwnProperty.call(source, prop)) {
if (source[prop] === undefined) {
delete this[prop];
} else {
this[prop] = source[prop];
}
}
}
}
if (!this.id) {
this.id = osmNote.id();
}
return this;
},
extent: function() {
return new geoExtent(this.loc);
},
getID: function() {
return this.id;
},
getType: function() {
return this.type;
},
getComments: function() {
return this.comments;
}
});
|
Add cassette and failed request as properties of thrown CannotOverwriteCassetteException | class CannotOverwriteExistingCassetteException(Exception):
def __init__(self, *args, **kwargs):
self.cassette = kwargs["cassette"]
self.failed_request = kwargs["failed_request"]
message = self._get_message(kwargs["cassette"], kwargs["failed_request"])
super(CannotOverwriteExistingCassetteException, self).__init__(message)
def _get_message(self, cassette, failed_request):
"""Get the final message related to the exception"""
# Get the similar requests in the cassette that
# have match the most with the request.
best_matches = cassette.find_requests_with_most_matches(failed_request)
# Build a comprehensible message to put in the exception.
best_matches_msg = ""
for best_match in best_matches:
request, _, failed_matchers_assertion_msgs = best_match
best_matches_msg += "Similar request found : (%r).\n" % request
for failed_matcher, assertion_msg in failed_matchers_assertion_msgs:
best_matches_msg += "Matcher failed : %s\n" "%s\n" % (
failed_matcher,
assertion_msg,
)
return (
"Can't overwrite existing cassette (%r) in "
"your current record mode (%r).\n"
"No match for the request (%r) was found.\n"
"%s"
% (cassette._path, cassette.record_mode, failed_request, best_matches_msg)
)
class UnhandledHTTPRequestError(KeyError):
"""Raised when a cassette does not contain the request we want."""
pass
| class CannotOverwriteExistingCassetteException(Exception):
def __init__(self, *args, **kwargs):
message = self._get_message(kwargs["cassette"], kwargs["failed_request"])
super(CannotOverwriteExistingCassetteException, self).__init__(message)
def _get_message(self, cassette, failed_request):
"""Get the final message related to the exception"""
# Get the similar requests in the cassette that
# have match the most with the request.
best_matches = cassette.find_requests_with_most_matches(failed_request)
# Build a comprehensible message to put in the exception.
best_matches_msg = ""
for best_match in best_matches:
request, _, failed_matchers_assertion_msgs = best_match
best_matches_msg += "Similar request found : (%r).\n" % request
for failed_matcher, assertion_msg in failed_matchers_assertion_msgs:
best_matches_msg += "Matcher failed : %s\n" "%s\n" % (
failed_matcher,
assertion_msg,
)
return (
"Can't overwrite existing cassette (%r) in "
"your current record mode (%r).\n"
"No match for the request (%r) was found.\n"
"%s"
% (cassette._path, cassette.record_mode, failed_request, best_matches_msg)
)
class UnhandledHTTPRequestError(KeyError):
"""Raised when a cassette does not contain the request we want."""
pass
|
Mark pre-selected topics on form |
from django.db import transaction
from django.shortcuts import render, redirect
from preferences.views import _mark_selected
from bills.utils import get_all_subjects, get_all_locations
from opencivicdata.models import Bill
def bill_list(request):
subjects = get_all_subjects()
if request.POST.getlist('bill_subjects'):
filter_subjects = request.POST.getlist('bill_subjects')
all_bills = Bill.objects.filter(subject__contains=filter_subjects)
else:
filter_subjects = []
all_bills = Bill.objects.all()
subjects = _mark_selected(subjects, filter_subjects)
details = []
for bill in all_bills:
bill_detail = {}
bill_detail['title'] = bill.title
bill_detail['from_organization'] = bill.from_organization.name
bill_detail['actions'] = []
bill_detail['sponsorships'] = []
for action in bill.actions.all():
bill_detail['actions'].append({'description': action.description, 'date': action.date})
for sponsorship in bill.sponsorships.all():
bill_detail['sponsorships'].append({
'sponsor': sponsorship.name,
'id': sponsorship.id,
'primary': sponsorship.primary
})
details.append(bill_detail)
return render(
request,
'bills/all.html',
{'bills': details, 'subjects': subjects}
)
|
from django.shortcuts import render, redirect
from bills.utils import get_all_subjects, get_all_locations
from opencivicdata.models import Bill
def bill_list(request):
subjects = get_all_subjects()
if request.POST.getlist('bill_subjects'):
filter_subjects = request.POST.getlist('bill_subjects')
all_bills = Bill.objects.filter(subject__in=filter_subjects)
else:
all_bills = Bill.objects.all()
details = []
for bill in all_bills:
bill_detail = {}
bill_detail['title'] = bill.title
bill_detail['from_organization'] = bill.from_organization.name
bill_detail['actions'] = []
bill_detail['sponsorships'] = []
for action in bill.actions.all():
bill_detail['actions'].append({'description': action.description, 'date': action.date})
for sponsorship in bill.sponsorships.all():
bill_detail['sponsorships'].append({
'sponsor': sponsorship.name,
'id': sponsorship.id,
'primary': sponsorship.primary
})
details.append(bill_detail)
if request.method == 'POST':
with transaction.atomic():
filter_subjects = request.POST.getlist('bill_subjects')
return redirect('.')
return render(
request,
'bills/all.html',
{'bills': details, 'subjects': subjects}
)
|
Remove double binding in custom view example. | package com.example.zipper.customview;
import com.example.zipper.R;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import se.snylt.zipper.annotations.BindToView;
import se.snylt.zipper.viewbinder.Binding;
import se.snylt.zipper.viewbinder.Zipper;
public class CustomViewFragment extends Fragment {
private Binding binding;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.custom_view_fragment, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
CustomViewModel model = new CustomViewModel("@BindView\nid = R.id.123, view = CustomView.class, set = \"property\"");
binding = Zipper.bind(model, view);
}
@Override
public void onDestroyView() {
super.onDestroyView();
binding.unBind();
}
public static class CustomViewModel {
@BindToView(id=R.id.custom_view_fragment_custom_view, view = CustomView.class, set = "myData")
public final String data;
public CustomViewModel(String data) {
this.data = data;
}
}
}
| package com.example.zipper.customview;
import com.example.zipper.R;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import se.snylt.zipper.annotations.BindToView;
import se.snylt.zipper.viewbinder.Binding;
import se.snylt.zipper.viewbinder.Zipper;
public class CustomViewFragment extends Fragment {
private Binding binding;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.custom_view_fragment, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
CustomViewModel model = new CustomViewModel("@BindView\nid = R.id.123, view = CustomView.class, set = \"property\"");
binding = Zipper.bind(model, view);
binding = Zipper.bind(model, view);
}
@Override
public void onDestroyView() {
super.onDestroyView();
binding.unBind();
}
public static class CustomViewModel {
@BindToView(id=R.id.custom_view_fragment_custom_view, view = CustomView.class, set = "myData")
public final String data;
public CustomViewModel(String data) {
this.data = data;
}
}
}
|
Fix indentation in the text-fill directive. | /*global angular*/
(function () {
'use strict';
// min-font-size attribute = minimum font size in pixels
// max-font-size attribute = maximum font size in pixels
// Directive must be used on the parent of an element with the .text-fill class
angular.module('core').directive('textFill', ["$timeout", function ($timeout) {
return {
link: function postLink(scope, element, attrs) {
if ($(element).find('.text-fill').length === 0) {
return;
}
var minFontSize = parseFloat(attrs.minFontSize);
var maxFontSize = parseFloat(attrs.maxFontSize);
if (!minFontSize || !maxFontSize) {
return;
}
var applyTextFill = function() {
$(element).textfill({
minFontPixels: minFontSize,
maxFontPixels: maxFontSize,
innerTag: '.text-fill'
});
}
scope.$on('updateSlideContentPart', function (event, content, member, slidePartId) {
if (member === attrs.member) {
applyTextFill();
}
});
$timeout(applyTextFill, 100);
}
};
}]);
}());
| /*global angular*/
(function () {
'use strict';
// min-font-size attribute = minimum font size in pixels
// max-font-size attribute = maximum font size in pixels
// Directive must be used on the parent of an element with the .text-fill class
angular.module('core').directive('textFill', ["$timeout", function ($timeout) {
return {
link: function postLink(scope, element, attrs) {
if ($(element).find('.text-fill').length === 0) {
return;
}
var minFontSize = parseFloat(attrs.minFontSize);
var maxFontSize = parseFloat(attrs.maxFontSize);
if (!minFontSize || !maxFontSize) {
return;
}
var applyTextFill = function() {
$(element).textfill({
minFontPixels: minFontSize,
maxFontPixels: maxFontSize,
innerTag: '.text-fill'
});
}
scope.$on('updateSlideContentPart', function (event, content, member, slidePartId) {
if (member === attrs.member) {
applyTextFill();
}
});
$timeout(applyTextFill, 100);
}
};
}]);
}());
|
Allow more discourse hostnames to fix CSP error | csp = {
'default-src': '\'self\'',
'style-src': [
'\'self\'',
'\'unsafe-inline\''
],
'script-src': [
'\'self\'',
'cdn.httparchive.org',
'www.google-analytics.com',
'use.fontawesome.com',
'cdn.speedcurve.com',
'spdcrv.global.ssl.fastly.net',
'lux.speedcurve.com'
],
'font-src': [
'\'self\''
],
'connect-src': [
'\'self\'',
'cdn.httparchive.org',
'discuss.httparchive.org',
'dev.to',
'cdn.rawgit.com',
'www.webpagetest.org',
'www.google-analytics.com',
'stats.g.doubleclick.net'
],
'img-src': [
'\'self\'',
'lux.speedcurve.com',
'almanac.httparchive.org',
'discuss.httparchive.org',
'avatars.discourse.org',
'www.google-analytics.com',
'www.google.com',
's.g.doubleclick.net',
'stats.g.doubleclick.net',
'*.discourse-cdn.com',
'res.cloudinary.com'
]
}
| csp = {
'default-src': '\'self\'',
'style-src': [
'\'self\'',
'\'unsafe-inline\''
],
'script-src': [
'\'self\'',
'cdn.httparchive.org',
'www.google-analytics.com',
'use.fontawesome.com',
'cdn.speedcurve.com',
'spdcrv.global.ssl.fastly.net',
'lux.speedcurve.com'
],
'font-src': [
'\'self\''
],
'connect-src': [
'\'self\'',
'cdn.httparchive.org',
'discuss.httparchive.org',
'dev.to',
'cdn.rawgit.com',
'www.webpagetest.org',
'www.google-analytics.com',
'stats.g.doubleclick.net'
],
'img-src': [
'\'self\'',
'lux.speedcurve.com',
'almanac.httparchive.org',
'discuss.httparchive.org',
'avatars.discourse.org',
'www.google-analytics.com',
'www.google.com',
's.g.doubleclick.net',
'stats.g.doubleclick.net',
'sjc3.discourse-cdn.com',
'res.cloudinary.com'
]
}
|
Fix templates and add newlines | export function CORDOVA_ASSET_TEMPLATE(assetType, platform, {src, d, w, h} = {}) {
return `<${assetType} src="${src}" platform="${platform}"${d?` density="${d}"`:``}${w?` width="${w}"`:``}${h?` height="${h}"`:``} />`;
}
export function PGBUILD_ASSET_TEMPLATE(assetType, platform, {src, d, w, h} = {}) {
return `<${assetType} src="${src}" gap:platform="${platform}"${d?` gap:qualifier="${d}"`:``}${w?` width="${w}"`:``}${h?` height="${h}"`:``} />`;
}
/**
* Create a list of icons or splash screens
* @param assetType {string} icon | splash
* @param assetTemplate {function} one of the above templates
* @param cordova {*}
*/
export function transformCordovaAssets(assetType, assetTemplate, {cordova} = {cordova: {platforms: [], assets: {}}} ) {
let {platforms} = cordova,
assets = cordova[assetType];
if (platforms instanceof Array && assets instanceof Object) {
return platforms.map( platform => {
let assetList = assets[platform];
if (assetList instanceof Array) {
return assetList.map(assetTemplate.bind(undefined, assetType, platform)).join("\n ");
} else {
return "";
}
}).join("\n ");
} else {
return "";
}
}
| export function CORDOVA_ASSET_TEMPLATE(assetType, platform, {src, d, w, h} = {}) {
return `<${assetType} src="${src}" platform="${platform}"${d?` density="${d}"`:``}${w?` width="${w}"`:``}${h?` height="${h}`:``}" />`;
}
export function PGBUILD_ASSET_TEMPLATE(assetType, platform, {src, d, w, h} = {}) {
return `<${assetType} src="${src}" gap:platform="${platform}"${d?` gap:qualifier="${d}"`:``}${w?` width="${w}"`:``}${h?` height="${h}`:``}" />`;
}
/**
* Create a list of icons or splash screens
* @param assetType {string} icon | splash
* @param assetTemplate {function} one of the above templates
* @param cordova {*}
*/
export function transformCordovaAssets(assetType, assetTemplate, {cordova} = {cordova: {platforms: [], assets: {}}} ) {
let {platforms} = cordova,
assets = cordova[assetType];
if (platforms instanceof Array && assets instanceof Object) {
return platforms.map( platform => {
let assetList = assets[platform];
if (assetList instanceof Array) {
return assetList.map(assetTemplate.bind(undefined, assetType, platform));
} else {
return "";
}
}).join("\n ");
} else {
return "";
}
}
|
Remove Java 8 string join method | package org.commonmark.ext.heading.anchor.internal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.commonmark.html.AttributeProvider;
import org.commonmark.node.AbstractVisitor;
import org.commonmark.node.Code;
import org.commonmark.node.Heading;
import org.commonmark.node.Node;
import org.commonmark.node.Text;
import org.commonmark.ext.heading.anchor.UniqueIdentifierProvider;
public class HeadingIdAttributeProvider implements AttributeProvider {
private final UniqueIdentifierProvider idProvider;
private HeadingIdAttributeProvider() {
idProvider = new UniqueIdentifierProvider("heading");
}
public static HeadingIdAttributeProvider create() {
return new HeadingIdAttributeProvider();
}
@Override
public void setAttributes(Node node, final Map<String, String> attributes) {
if (node instanceof Heading) {
final List<String> wordList = new ArrayList<>();
node.accept(new AbstractVisitor() {
@Override
public void visit(Text text) {
wordList.add(text.getLiteral());
}
@Override
public void visit(Code code) {
wordList.add(code.getLiteral());
}
});
String finalString = "";
for (String word : wordList) {
finalString += word + " ";
}
finalString = finalString.trim().toLowerCase();
attributes.put("id", idProvider.getUniqueIdentifier(finalString));
}
}
}
| package org.commonmark.ext.heading.anchor.internal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.commonmark.html.AttributeProvider;
import org.commonmark.node.AbstractVisitor;
import org.commonmark.node.Code;
import org.commonmark.node.Heading;
import org.commonmark.node.Node;
import org.commonmark.node.Text;
import org.commonmark.ext.heading.anchor.UniqueIdentifierProvider;
public class HeadingIdAttributeProvider implements AttributeProvider {
private final UniqueIdentifierProvider idProvider;
private HeadingIdAttributeProvider() {
idProvider = new UniqueIdentifierProvider("heading");
}
public static HeadingIdAttributeProvider create() {
return new HeadingIdAttributeProvider();
}
@Override
public void setAttributes(Node node, final Map<String, String> attributes) {
if (node instanceof Heading) {
final List<String> wordList = new ArrayList<>();
node.accept(new AbstractVisitor() {
@Override
public void visit(Text text) {
wordList.add(text.getLiteral());
}
@Override
public void visit(Code code) {
wordList.add(code.getLiteral());
}
});
attributes.put("id", idProvider.getUniqueIdentifier(String.join("", wordList)).toLowerCase());
}
}
}
|
Use collections instead of models for tags | "use strict";
define(['jquery',
'underscore',
'backbone',
'jquery.tagsinput'
], function ($, _, Backbone, TagsInput) {
var Recipe = Backbone.Model.extend({
urlRoot: '/',
defaults: {
ingredients: [],
method: ''
}
});
var Recipes = Backbone.Collection.extend({
model: Recipe,
urlRoot: '/'
});
var SearchTag = Backbone.Model.extend({
defaults: {
value: ''
}
});
var SearchTags = Backbone.Collection.extend({
model: SearchTag
});
var App = Backbone.View.extend({
el: '#container',
initialize: function () {
_.bindAll(this, 'tagAdded', 'tagRemoved');
var self = this;
this.recipeCollection = new Recipes;
this.searchTags = new SearchTags;
this.$el.find('.search-input').tagsInput({
'defaultText': 'Search',
'width': '99%',
'height': '100%',
'delimiter': [',',';'],
'onAddTag': self.tagAdded,
'onRemoveTag': self.tagRemoved
});
},
tagAdded: function (tag) {
this.searchTags.add({tag: tag});
},
tagRemoved: function (tag) {
this.searchTags.remove(this.searchTags.where({tag: tag}));
}
});
return App;
});
| "use strict";
define(['jquery',
'underscore',
'backbone',
'jquery.tagsinput'
], function ($, _, Backbone, TagsInput) {
var Recipe = Backbone.Model.extend({
urlRoot: '/',
defaults: {
ingredients: [],
method: ''
}
});
var Recipes = Backbone.Collection.extend({
model: Recipe,
urlRoot: '/'
});
var SearchTags = Backbone.Model.extend({
defaults: {
tags: []
}
});
var App = Backbone.View.extend({
el: '#container',
initialize: function () {
_.bindAll(this, 'tagAdded', 'tagRemoved');
var self = this;
this.recipeCollection = new Recipes;
this.searchTags = new SearchTags;
this.$el.find('.search-input').tagsInput({
'defaultText': 'Search',
'width': '99%',
'height': '100%',
'delimiter': [',',';'],
'onAddTag': self.tagAdded,
'onRemoveTag': self.tagRemoved
});
},
tagAdded: function (tag) {
this.searchTags.attributes.tags.push(tag);
},
tagRemoved: function (tag) {
this.searchTags.attributes.tags.pop();
},
render: function () {
console.log('bar');
}
});
return App;
});
|
test: Use generator for IAM template names
See also: #208 | """Test IAM Policy templates are valid JSON."""
import jinja2
from foremast.iam.construct_policy import render_policy_template
from foremast.utils.templates import LOCAL_TEMPLATES
def iam_templates():
"""Generate list of IAM templates."""
jinjaenv = jinja2.Environment(loader=jinja2.FileSystemLoader([LOCAL_TEMPLATES]))
iam_template_names = jinjaenv.list_templates(filter_func=lambda x: all([
x.startswith('infrastructure/iam/'),
'trust' not in x,
'wrapper' not in x, ]))
for iam_template_name in iam_template_names:
yield iam_template_name
items = ['resource1', 'resource2']
if service == 'rds-db':
items = {
'resource1': 'user1',
'resource2': 'user2',
}
rendered = render_policy_template(
account_number='',
app='coreforrest',
env='dev',
group='forrest',
items=items,
pipeline_settings={
'lambda': {
'vpc_enabled': False,
},
},
region='us-east-1',
service=service)
assert isinstance(rendered, list)
| """Test IAM Policy templates are valid JSON."""
import jinja2
from foremast.iam.construct_policy import render_policy_template
from foremast.utils.templates import LOCAL_TEMPLATES
def test_all_iam_templates():
"""Verify all IAM templates render as proper JSON."""
jinjaenv = jinja2.Environment(loader=jinja2.FileSystemLoader([LOCAL_TEMPLATES]))
iam_templates = jinjaenv.list_templates(filter_func=lambda x: all([
x.startswith('infrastructure/iam/'),
'trust' not in x,
'wrapper' not in x, ]))
for template in iam_templates:
*_, service_json = template.split('/')
service, *_ = service_json.split('.')
items = ['resource1', 'resource2']
if service == 'rds-db':
items = {
'resource1': 'user1',
'resource2': 'user2',
}
rendered = render_policy_template(
account_number='',
app='coreforrest',
env='dev',
group='forrest',
items=items,
pipeline_settings={
'lambda': {
'vpc_enabled': False,
},
},
region='us-east-1',
service=service)
assert isinstance(rendered, list)
|
Add in new Kazuto Kirigia spam | import BaseWatcher from './BaseWatcher';
import config from '../config';
/**
* This checks for people spamming text stuff.
*/
class TextSpamWatcher extends BaseWatcher {
usesBypassRules = true;
/**
* The method this watcher should listen on.
*
* @type {string[]}
*/
method = [
'message',
'messageUpdate'
];
async action(method, message, updatedMessage) {
let messageToActUpon = message;
if (method === 'messageUpdate') {
messageToActUpon = updatedMessage;
}
const rulesChannel = this.bot.channels.find((channel) => (channel.name === config.rules_channel));
const cleanMessage = messageToActUpon.cleanContent.toLowerCase();
if (
cleanMessage.indexOf('this is cooldog') !== -1 ||
cleanMessage.indexOf('this is memedog') !== -1 ||
cleanMessage.indexOf('chrisopeer davies') !== -1 ||
cleanMessage.indexOf('jessica davies') !== -1 ||
cleanMessage.indexOf('DMing inappropriate photos of underage children') !== -1 ||
cleanMessage.indexOf('bots are joining servers and sending mass') !== -1 ||
cleanMessage.indexOf('kazuto kirigia') !== -1
) {
const warningMessage = await messageToActUpon.reply(
`Please read the ${rulesChannel} channel. Spamming or encouraging spamming is not allowed.`
);
this.addWarningToUser(messageToActUpon);
messageToActUpon.delete();
warningMessage.delete(60000);
}
}
}
export default TextSpamWatcher;
| import BaseWatcher from './BaseWatcher';
import config from '../config';
/**
* This checks for people spamming text stuff.
*/
class TextSpamWatcher extends BaseWatcher {
usesBypassRules = true;
/**
* The method this watcher should listen on.
*
* @type {string[]}
*/
method = [
'message',
'messageUpdate'
];
async action(method, message, updatedMessage) {
let messageToActUpon = message;
if (method === 'messageUpdate') {
messageToActUpon = updatedMessage;
}
const rulesChannel = this.bot.channels.find((channel) => (channel.name === config.rules_channel));
const cleanMessage = messageToActUpon.cleanContent.toLowerCase();
if (
cleanMessage.indexOf('this is cooldog') !== -1 ||
cleanMessage.indexOf('this is memedog') !== -1 ||
cleanMessage.indexOf('chrisopeer davies') !== -1 ||
cleanMessage.indexOf('jessica davies') !== -1 ||
cleanMessage.indexOf('DMing inappropriate photos of underage children') !== -1 ||
cleanMessage.indexOf('bots are joining servers and sending mass') !== -1
) {
const warningMessage = await messageToActUpon.reply(
`Please read the ${rulesChannel} channel. Spamming or encouraging spamming is not allowed.`
);
this.addWarningToUser(messageToActUpon);
messageToActUpon.delete();
warningMessage.delete(60000);
}
}
}
export default TextSpamWatcher;
|
Change namespace image app, use opps image | # -*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from opps.core.models import Article
from opps.image.models import Image
from opps.core.models import Source
class Post(Article):
images = models.ManyToManyField(Image, null=True, blank=True,
related_name='post_images', through='PostImage')
class PostImage(models.Model):
post = models.ForeignKey(Post, verbose_name=_(u'Post'), null=True,
blank=True, related_name='postimage_post',
on_delete=models.SET_NULL)
image = models.ForeignKey(Image, verbose_name=_(u'Image'), null=True,
blank=True, related_name='postimage_image',
on_delete=models.SET_NULL)
order = models.PositiveIntegerField(_(u'Order'), default=1)
def __unicode__(self):
return self.image.title
class PostSource(models.Model):
post = models.ForeignKey(Post, verbose_name=_(u'Post'), null=True,
blank=True, related_name='postsource_post',
on_delete=models.SET_NULL)
source = models.ForeignKey(Source, verbose_name=_(u'Source'), null=True,
blank=True, related_name='postsource_source',
on_delete=models.SET_NULL)
order = models.PositiveIntegerField(_(u'Order'), default=1)
def __unicode__(self):
return self.source.slug
| # -*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from opps.core.models import Article
from opps.core.models.image import Image
from opps.core.models import Source
class Post(Article):
images = models.ManyToManyField(Image, null=True, blank=True,
related_name='post_images', through='PostImage')
class PostImage(models.Model):
post = models.ForeignKey(Post, verbose_name=_(u'Post'), null=True,
blank=True, related_name='postimage_post',
on_delete=models.SET_NULL)
image = models.ForeignKey(Image, verbose_name=_(u'Image'), null=True,
blank=True, related_name='postimage_image',
on_delete=models.SET_NULL)
order = models.PositiveIntegerField(_(u'Order'), default=1)
def __unicode__(self):
return self.image.title
class PostSource(models.Model):
post = models.ForeignKey(Post, verbose_name=_(u'Post'), null=True,
blank=True, related_name='postsource_post',
on_delete=models.SET_NULL)
source = models.ForeignKey(Source, verbose_name=_(u'Source'), null=True,
blank=True, related_name='postsource_source',
on_delete=models.SET_NULL)
order = models.PositiveIntegerField(_(u'Order'), default=1)
def __unicode__(self):
return self.source.slug
|
Clean up ACL code for axo 20483 | <?php
namespace Rcm\Api\Acl;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ServerRequestInterface;
use Rcm\Acl\AclActions;
use Rcm\Acl\AssertIsAllowed;
use Rcm\Acl\NotAllowedException;
use Rcm\Acl\ResourceName;
use Rcm\Acl2\SecurityPropertyConstants;
use Rcm\Api\GetPsrRequest;
use Rcm\Entity\Site;
use RcmUser\Api\Acl\IsAllowed;
class IsAllowedSiteAdminBasic implements IsAllowedSiteAdmin
{
protected $assertIsAllowed;
public function __construct(
ContainerInterface $requestContext
) {
$this->assertIsAllowed = $requestContext->get(AssertIsAllowed::class);
}
/**
* @param ServerRequestInterface $request
* @param Site $site
*
* @return bool
*/
public function __invoke(
ServerRequestInterface $request,
Site $site
): bool {
/** @oldAclAccessCheckReplaced */
try {
$this->assertIsAllowed->__invoke(
AclActions::UPDATE,
[
'type' => SecurityPropertyConstants::TYPE_CONTENT,
SecurityPropertyConstants::CONTENT_TYPE_KEY
=> SecurityPropertyConstants::CONTENT_TYPE_SITE,
'country' => $site->getCountryIso3()
]
);
} catch (NotAllowedException $e) {
return false;
}
return true;
}
}
| <?php
namespace Rcm\Api\Acl;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ServerRequestInterface;
use Rcm\Acl\AclActions;
use Rcm\Acl\AssertIsAllowed;
use Rcm\Acl\NotAllowedException;
use Rcm\Acl\ResourceName;
use Rcm\Acl2\SecurityPropertyConstants;
use Rcm\Api\GetPsrRequest;
use Rcm\Entity\Site;
use RcmUser\Api\Acl\IsAllowed;
class IsAllowedSiteAdminBasic implements IsAllowedSiteAdmin
{
protected $assertIsAllowed;
public function __construct(
ContainerInterface $requestContext
) {
$this->assertIsAllowed = $requestContext->get(AssertIsAllowed::class);
}
/**
* @param ServerRequestInterface $request
* @param Site $site
*
* @return bool
*/
public function __invoke(
ServerRequestInterface $request,
Site $site
): bool {
/** @oldAclAccessCheckReplaced */
try {
$this->assertIsAllowed->__invoke(
AclActions::UPDATE,
[
'type' => SecurityPropertyConstants::TYPE_CONTENT,
SecurityPropertyConstants::CONTENT_TYPE_KEY
=> SecurityPropertyConstants::CONTENT_TYPE_SITE,
'country' => $site->getCountryIso3()
]
);
} catch (NotAllowedException $e) {
return false;
}
return true;
}
}
|
Remove extension of webservice class and update parameters of execute function | <?php
namespace AppBundle\API\Listing;
use AppBundle\API\Webservice;
use AppBundle\Entity\WebuserData;
use AppBundle\Entity\FennecUser;
use Doctrine\Common\Collections\Collection;
use Symfony\Component\HttpFoundation\ParameterBag;
/**
* Web Service.
* Returns information of all users projects
*/
class Projects
{
/**
* @inheritdoc
* @returns array $result
* <code>
* array(array('project_id','import_date','OTUs','sample size'));
* </code>
*/
public function execute(FennecUser $user = null)
{
$result = array('data' => array());
if ($user == null) {
$result['error'] = Webservice::ERROR_NOT_LOGGED_IN;
} else {
$projects = $user->getData();
foreach ($projects as $p) {
/** @var WebuserData $p */
$project = array();
$project['internal_project_id'] = $p->getWebuserDataId();
$data = $p->getProject();
$project['id'] = $data['id'];
$project['import_date'] = $p->getImportDate()->format('Y-m-d H:i:s');
$project['rows'] = $data['shape'][0];
$project['columns'] = $data['shape'][1];
$project['import_filename'] = $p->getImportFilename();
$result['data'][] = $project;
}
}
return $result;
}
}
| <?php
namespace AppBundle\API\Listing;
use AppBundle\API\Webservice;
use AppBundle\Entity\WebuserData;
use AppBundle\Entity\FennecUser;
use Doctrine\Common\Collections\Collection;
use Symfony\Component\HttpFoundation\ParameterBag;
/**
* Web Service.
* Returns information of all users projects
*/
class Projects extends Webservice
{
/**
* @inheritdoc
* @returns array $result
* <code>
* array(array('project_id','import_date','OTUs','sample size'));
* </code>
*/
public function execute(ParameterBag $query, FennecUser $user = null)
{
$result = array('data' => array());
if ($user == null) {
$result['error'] = Webservice::ERROR_NOT_LOGGED_IN;
} else {
$projects = $user->getData();
foreach ($projects as $p) {
/** @var WebuserData $p */
$project = array();
$project['internal_project_id'] = $p->getWebuserDataId();
$data = $p->getProject();
$project['id'] = $data['id'];
$project['import_date'] = $p->getImportDate()->format('Y-m-d H:i:s');
$project['rows'] = $data['shape'][0];
$project['columns'] = $data['shape'][1];
$project['import_filename'] = $p->getImportFilename();
$result['data'][] = $project;
}
}
return $result;
}
}
|
Move emmity config to upper level | import gulp from "gulp";
import plumber from "gulp-plumber";
import pug from "gulp-pug";
import posthtml from "gulp-posthtml";
import prettify from "gulp-prettify";
import gulpIf from "gulp-if";
import { setup as emittySetup } from "emitty";
import getJsonData from "../util/getJsonData";
import { plumberConfig, posthtmlConfig, htmlPrettifyConfig } from "../config";
import data from "./data";
export const pages = () => {
const pugConfig = {
locals: getJsonData("./tmp/data.json")
};
const emittyPug = emittySetup("source/pages", "pug");
return new Promise((resolve, reject) => {
return emittyPug
.scan(global.emittyChangedFile)
.then(() => {
gulp
.src(["**/*.pug", "!**/_*.pug"], { cwd: "source/pages" })
.pipe(plumber(plumberConfig))
.pipe(
gulpIf(global.watch, emittyPug.filter(global.emittyChangedFile))
)
.pipe(pug(pugConfig))
.pipe(posthtml(posthtmlConfig.plugins, posthtmlConfig.options))
.pipe(prettify(htmlPrettifyConfig))
.pipe(gulp.dest("dest"))
.on("end", resolve)
.on("error", reject);
})
.catch(err => console.log(err));
});
};
export const html = gulp.series(data, pages);
| import gulp from "gulp";
import plumber from "gulp-plumber";
import pug from "gulp-pug";
import posthtml from "gulp-posthtml";
import prettify from "gulp-prettify";
import gulpIf from "gulp-if";
import { setup as emittySetup } from "emitty";
import getJsonData from "../util/getJsonData";
import { plumberConfig, posthtmlConfig, htmlPrettifyConfig } from "../config";
import data from "./data";
export const pages = () => {
const pugConfig = {
locals: getJsonData("./tmp/data.json")
};
return new Promise((resolve, reject) => {
const emittyPug = emittySetup("source/pages", "pug");
return emittyPug
.scan(global.emittyChangedFile)
.then(() => {
gulp
.src(["**/*.pug", "!**/_*.pug"], { cwd: "source/pages" })
.pipe(plumber(plumberConfig))
.pipe(
gulpIf(global.watch, emittyPug.filter(global.emittyChangedFile))
)
.pipe(pug(pugConfig))
.pipe(posthtml(posthtmlConfig.plugins, posthtmlConfig.options))
.pipe(prettify(htmlPrettifyConfig))
.pipe(gulp.dest("dest"))
.on("end", resolve)
.on("error", reject);
})
.catch(err => console.log(err));
});
};
export const html = gulp.series(data, pages);
|
Move unit tests data in setUp
When unit testing the various methods of cat2cohort,
we need some example data (input and expected output).
It makes sense to share it among testing methods through
the setUp method mechanism. | """Unit tests for cat2cohort."""
import unittest
from wm_metrics.cat2cohort import api_url, _make_CSV_line, _userlist_to_CSV_cohort
class TestCat2Cohort(unittest.TestCase):
"""Test methods from Cat2Cohort."""
def setUp(self):
"""Set up the tests."""
self.userlist = [('Toto', 'fr'), ('Titi', 'en')]
self.csvlines = ['Toto, frwiki', 'Titi, enwiki']
def test_api_url(self):
"""Test api_url."""
values = [
('fr', 'https://fr.wikipedia.org/w/api.php'),
('en', 'https://en.wikipedia.org/w/api.php'),
]
for value, expected in values:
self.assertEqual(api_url(value), expected)
def test_make_CSV_line(self):
"""Test _make_CSV_line."""
for value, expected in zip(self.userlist, self.csvlines):
self.assertEqual(_make_CSV_line(*value), expected)
def test_userlist_to_CSV_cohort(self):
"""Test _userlist_to_CSV_cohort."""
expected = '\n'.join(self.csvlines)
self.assertEqual(_userlist_to_CSV_cohort(self.userlist),
expected)
| """Unit tests for cat2cohort."""
import unittest
from wm_metrics.cat2cohort import api_url, _make_CSV_line, _userlist_to_CSV_cohort
class TestCat2Cohort(unittest.TestCase):
"""Test methods from Cat2Cohort."""
def test_api_url(self):
"""Test api_url."""
values = [
('fr', 'https://fr.wikipedia.org/w/api.php'),
('en', 'https://en.wikipedia.org/w/api.php'),
]
for value, expected in values:
self.assertEqual(api_url(value), expected)
def test_make_CSV_line(self):
"""Test _make_CSV_line."""
values = [
(('Toto', 'fr'), 'Toto, frwiki'),
(('Titi', 'en'), 'Titi, enwiki'),
]
for value, expected in values:
self.assertEqual(_make_CSV_line(*value), expected)
def test_userlist_to_CSV_cohort(self):
"""Test _userlist_to_CSV_cohort."""
expected = '\n'.join(self.csvlines)
self.assertEqual(_userlist_to_CSV_cohort(self.userlist),
expected)
|
Remove console.debug from jshint spec | // Thanks to Brandon Keepers -
describe('JSHint', function () {
var options = {curly: true, white: false, indent: 2},
files = /^\/public\/javascripts\/(models|collections|views)|.*spec\.js$/;
function get(path) {
path = path + "?" + new Date().getTime();
var xhr;
try {
xhr = new jasmine.XmlHttpRequest();
xhr.open("GET", path, false);
xhr.send(null);
} catch (e) {
throw new Error("couldn't fetch " + path + ": " + e);
}
if (xhr.status < 200 || xhr.status > 299) {
throw new Error("Could not load '" + path + "'.");
}
return xhr.responseText;
}
_.each(document.getElementsByTagName('script'), function (element) {
var script = element.getAttribute('src');
if (!files.test(script)) {
return;
}
it(script, function () {
var self = this;
var source = get(script);
var result = JSHINT(source, options);
_.each(JSHINT.errors, function (error) {
self.addMatcherResult(new jasmine.ExpectationResult({
passed: false,
message: "line " + error.line + ' - ' + error.reason + ' - ' + error.evidence
}));
});
expect(true).toBe(true); // force spec to show up if there are no errors
});
});
});
| // Thanks to Brandon Keepers -
describe('JSHint', function () {
var options = {curly: true, white: false, indent: 2},
files = /^\/public\/javascripts\/(models|collections|views)|.*spec\.js$/;
function get(path) {
path = path + "?" + new Date().getTime();
var xhr;
try {
xhr = new jasmine.XmlHttpRequest();
xhr.open("GET", path, false);
xhr.send(null);
} catch (e) {
throw new Error("couldn't fetch " + path + ": " + e);
}
if (xhr.status < 200 || xhr.status > 299) {
throw new Error("Could not load '" + path + "'.");
}
return xhr.responseText;
}
_.each(document.getElementsByTagName('script'), function (element) {
var script = element.getAttribute('src');
if (!files.test(script)) {
return;
}
console.debug(script);
it(script, function () {
var self = this;
var source = get(script);
var result = JSHINT(source, options);
_.each(JSHINT.errors, function (error) {
self.addMatcherResult(new jasmine.ExpectationResult({
passed: false,
message: "line " + error.line + ' - ' + error.reason + ' - ' + error.evidence
}));
});
expect(true).toBe(true); // force spec to show up if there are no errors
});
});
});
|
Make sure client gets update after a refresh | var WebSocketServer = require('ws').Server
, http = require('http')
, express = require('express')
, app = express()
, port = process.env.PORT || 5000;
app.use(express.static(__dirname + '/'));
var server = http.createServer(app);
server.listen(port);
console.log('http server listening on %d', port);
var mapper = require('./server/mapper.js');
var wss = new WebSocketServer({server: server});
console.log('websocket server created');
wss.on('connection', function(ws) {
function newClient() {
var numberOfUpdatesMade = 0;
function getEmailsAndUpdateClients() {
numberOfUpdatesMade ++;
if (numberOfUpdatesMade < 20) {
console.log('checking for updates (' + numberOfUpdatesMade + ')');
var currentData = mapper.readEmail(function(emailData, changes) {
if(changes || numberOfUpdatesMade <= 2) {
console.log('CHANGES!');
ws.send(JSON.stringify(emailData), function() { });
} else {
console.log('no changes');
}
});
}
}
getEmailsAndUpdateClients();
var id = setInterval(getEmailsAndUpdateClients, 5000);
return id;
}
var clientId = newClient();
console.log('websocket connection open');
ws.on('close', function() {
console.log('websocket connection close');
clearInterval(clientId);
});
});
| var WebSocketServer = require('ws').Server
, http = require('http')
, express = require('express')
, app = express()
, port = process.env.PORT || 5000;
app.use(express.static(__dirname + '/'));
var server = http.createServer(app);
server.listen(port);
console.log('http server listening on %d', port);
var mapper = require('./server/mapper.js');
var wss = new WebSocketServer({server: server});
console.log('websocket server created');
wss.on('connection', function(ws) {
function newClient() {
var numberOfUpdatesMade = 0;
function getEmailsAndUpdateClients() {
numberOfUpdatesMade ++;
if (numberOfUpdatesMade < 20) {
console.log('checking for updates (' + numberOfUpdatesMade + ')');
var currentData = mapper.readEmail(function(emailData, changes) {
if(changes || numberOfUpdatesMade === 1) {
console.log('CHANGES!');
ws.send(JSON.stringify(emailData), function() { });
} else {
console.log('no changes');
}
});
}
}
getEmailsAndUpdateClients();
var id = setInterval(getEmailsAndUpdateClients, 5000);
return id;
}
var clientId = newClient();
console.log('websocket connection open');
ws.on('close', function() {
console.log('websocket connection close');
clearInterval(clientId);
});
});
|
Fix getMatchAllQuery to return according to pageNumber | var Appbase = require('appbase-js');
module.exports = {
getRequestObject: function (config, fieldName, boundingBoxCoordinates, streaming) {
var geo_bounding_box = JSON.parse(`{"${fieldName}":` + JSON.stringify(boundingBoxCoordinates) + '}');
var _source = !streaming ? `${fieldName}` : null;
return ({
type: config.appbase.type,
body: {
"size": 100,
"_source": [_source],
"query": {
"filtered": {
"query": {
"match_all": {}
},
"filter": {
geo_bounding_box
}
}
}
}
});
},
getMatchAllQuery: function(config, fieldName, pageNumber, size, streaming){
var _source = !streaming ? `${fieldName}` : null;
return ({
type: config.appbase.type,
body: {
"size": size,
"from": pageNumber*size,
"_source": [_source],
"query": {
"filtered": {
"query": {
"match_all": {}
}
}
}
}
});
},
getAppbaseRef: function (config) {
return (
new Appbase({
url: 'https://scalr.api.appbase.io',
appname: config.appbase.appname,
username: config.appbase.username,
password: config.appbase.password
})
);
},
}; | var Appbase = require('appbase-js');
module.exports = {
getRequestObject: function (config, fieldName, boundingBoxCoordinates, streaming) {
var geo_bounding_box = JSON.parse(`{"${fieldName}":` + JSON.stringify(boundingBoxCoordinates) + '}');
var _source = !streaming ? `${fieldName}` : null;
return ({
type: config.appbase.type,
body: {
"size": 100,
"_source": [_source],
"query": {
"filtered": {
"query": {
"match_all": {}
},
"filter": {
geo_bounding_box
}
}
}
}
});
},
getMatchAllQuery: function(config, fieldName, page, streaming){
var _source = !streaming ? `${fieldName}` : null;
return ({
type: config.appbase.type,
body: {
"size": 100,
"_source": [_source],
"query": {
"filtered": {
"query": {
"match_all": {}
}
}
}
}
});
},
getAppbaseRef: function (config) {
return (
new Appbase({
url: 'https://scalr.api.appbase.io',
appname: config.appbase.appname,
username: config.appbase.username,
password: config.appbase.password
})
);
},
}; |
BAP-9269: Fix unit tests after doctrine/cache package was update | <?php
namespace Oro\Bundle\EntityExtendBundle\Tests\Unit\Mapping;
use Doctrine\Common\Cache\ArrayCache;
use Doctrine\ORM\Mapping\ClassMetadata;
use Oro\Bundle\EntityExtendBundle\Mapping\ExtendClassMetadataFactory;
class ExtendClassMetadataFactoryTest extends \PHPUnit_Framework_TestCase
{
/**
* @var ExtendClassMetadataFactory
*/
private $cmf;
protected function setUp()
{
parent::setUp();
$driver = $this->getMock('Doctrine\Common\Persistence\Mapping\Driver\MappingDriver');
$metadata = $this->getMock('Doctrine\Common\Persistence\Mapping\ClassMetadata');
$this->cmf = new ExtendClassMetadataFactory($driver, $metadata);
}
public function testSetMetadataFor()
{
$cache = new ArrayCache();
$this->cmf->setCacheDriver($cache);
$metadata = new ClassMetadata('Oro\Bundle\UserBundle\Entity\User');
$this->cmf->setMetadataFor(
'Oro\Bundle\UserBundle\Entity\User',
$metadata
);
$cacheSalt = '$CLASSMETADATA';
$this->assertAttributeSame(
[
'[Oro\Bundle\UserBundle\Entity\User'.$cacheSalt .'][1]' => $metadata
],
'data',
$this->cmf->getCacheDriver()
);
}
}
| <?php
namespace Oro\Bundle\EntityExtendBundle\Tests\Unit\Mapping;
use Doctrine\Common\Cache\ArrayCache;
use Doctrine\ORM\Mapping\ClassMetadata;
use Oro\Bundle\EntityExtendBundle\Mapping\ExtendClassMetadataFactory;
class ExtendClassMetadataFactoryTest extends \PHPUnit_Framework_TestCase
{
/**
* @var ExtendClassMetadataFactory
*/
private $cmf;
protected function setUp()
{
parent::setUp();
$driver = $this->getMock('Doctrine\Common\Persistence\Mapping\Driver\MappingDriver');
$metadata = $this->getMock('Doctrine\Common\Persistence\Mapping\ClassMetadata');
$this->cmf = new ExtendClassMetadataFactory($driver, $metadata);
}
public function testSetMetadataFor()
{
$cache = new ArrayCache();
$this->cmf->setCacheDriver($cache);
$metadata = new ClassMetadata('Oro\Bundle\UserBundle\Entity\User');
$this->cmf->setMetadataFor(
'Oro\Bundle\UserBundle\Entity\User',
$metadata
);
$cacheSalt = '$CLASSMETADATA';
$this->assertAttributeSame(
[
'DoctrineNamespaceCacheKey[]' => 1,
'[Oro\Bundle\UserBundle\Entity\User'.$cacheSalt .'][1]' => $metadata
],
'data',
$this->cmf->getCacheDriver()
);
}
}
|
REFACTOR : Changed the name of step name from 'name' to 'step_name' to avoid clashing with a potential use of the word 'name' in kwargs. | from hitchdoc.database import Database
from hitchdoc import exceptions
import pickle
import base64
class Recorder(object):
def __init__(self, story, sqlite_filename):
self._story = story
self._db = Database(sqlite_filename)
if self._db.Recording.filter(name=story.name).first() is not None:
self._db.Recording.filter(name=story.name).first().delete_instance(
recursive=True
)
self._model = self._db.Recording(
name=story.name,
filename=story.filename,
slug=story.slug,
properties=base64.b64encode(pickle.dumps(story.properties))
)
self._model.save(force_insert=True)
def step(self, step_name, **kwargs):
for key, value in kwargs.items():
assert type(key) is str
try:
pickle.dumps(value)
except TypeError:
raise exceptions.VarMustBePickleable(
"Can't use non-pickleable objects as vars."
)
new_step = self._db.Step(
recording=self._model,
step_name=step_name,
kwargs=base64.b64encode(pickle.dumps(kwargs))
)
new_step.save()
| from hitchdoc.database import Database
from hitchdoc import exceptions
import pickle
import base64
class Recorder(object):
def __init__(self, story, sqlite_filename):
self._story = story
self._db = Database(sqlite_filename)
if self._db.Recording.filter(name=story.name).first() is not None:
self._db.Recording.filter(name=story.name).first().delete_instance(
recursive=True
)
self._model = self._db.Recording(
name=story.name,
filename=story.filename,
slug=story.slug,
properties=base64.b64encode(pickle.dumps(story.properties))
)
self._model.save(force_insert=True)
def step(self, name, **kwargs):
for key, value in kwargs.items():
assert type(key) is str
try:
pickle.dumps(value)
except TypeError:
raise exceptions.VarMustBePickleable(
"Can't use non-pickleable objects as vars."
)
new_step = self._db.Step(
recording=self._model,
name=name,
kwargs=base64.b64encode(pickle.dumps(kwargs))
)
new_step.save()
|
Fix broken content rendered by PhJS | # Copyright (C) Ivan Kravets <[email protected]>
# See LICENSE for details.
from subprocess import check_output, CalledProcessError
from urllib import unquote
def application(env, start_response):
status = "200 OK"
response = ""
qs = env.get("QUERY_STRING", None)
if not qs or not qs.startswith("_escaped_fragment_="):
status = "500 Internal Server Error"
else:
url = "http://platformio.org/#!" + unquote(qs[19:])
try:
response = get_webcontent(url)
if "404 Not Found" in response:
status = "404 Not Found"
except Exception:
status = "500 Internal Server Error"
start_response(status, [("Content-Type", "text/html"),
("Content-Length", str(len(response)))])
return response
def get_webcontent(url):
retrynums = 0
while retrynums < 5:
try:
response = check_output([
"phantomjs", "--disk-cache=true", "--load-images=false",
"crawler.js", url
])
if 'class="ng-scope"' not in response:
raise CalledProcessError()
return response
except CalledProcessError:
retrynums += 1
raise Exception("Could not retrieve content from %s" % url)
| # Copyright (C) Ivan Kravets <[email protected]>
# See LICENSE for details.
from subprocess import check_output, CalledProcessError
from urllib import unquote
def application(env, start_response):
status = "200 OK"
response = ""
qs = env.get("QUERY_STRING", None)
if not qs or not qs.startswith("_escaped_fragment_="):
status = "500 Internal Server Error"
else:
url = "http://platformio.org/#!" + unquote(qs[19:])
try:
response = get_webcontent(url)
if "404 Not Found" in response:
status = "404 Not Found"
except Exception:
status = "500 Internal Server Error"
start_response(status, [("Content-Type", "text/html"),
("Content-Length", str(len(response)))])
return response
def get_webcontent(url):
retrynums = 0
while retrynums < 3:
try:
response = check_output([
"phantomjs", "--disk-cache=true", "--load-images=false",
"crawler.js", url
])
return response
except CalledProcessError:
retrynums += 1
raise Exception("Could not retrieve content from %s" % url)
|
Remove unused argument to internal destroyInstance | import { select, local } from "d3-selection";
var instanceLocal = local(),
noop = function (){};
export default function (tagName, className){
var create = noop,
render = noop,
destroy = noop,
createInstance = function (){
var instance = instanceLocal.set(this, {
selection: select(this),
state: {},
render: noop
});
create(instance.selection, function setState(state){
Object.assign(instance.state, state);
instance.render();
});
instance.render = function (){
render(instance.selection, instance.props, instance.state);
};
},
renderInstance = function (props){
var instance = instanceLocal.get(this);
instance.props = props || {};
instance.render();
},
destroyInstance = function (){
destroy(instanceLocal.get(this).state);
},
selector = className ? "." + className : tagName;
function component(selection, props){
var instances = selection.selectAll(selector)
.data(Array.isArray(props) ? props : [props]);
instances
.enter().append(tagName)
.attr("class", className)
.each(createInstance)
.merge(instances)
.each(renderInstance);
instances
.exit()
.each(destroyInstance)
.remove();
}
component.render = function(_) { return (render = _, component); };
component.create = function(_) { return (create = _, component); };
component.destroy = function(_) { return (destroy = _, component); };
return component;
};
| import { select, local } from "d3-selection";
var instanceLocal = local(),
noop = function (){};
export default function (tagName, className){
var create = noop,
render = noop,
destroy = noop,
createInstance = function (){
var instance = instanceLocal.set(this, {
selection: select(this),
state: {},
render: noop
});
create(instance.selection, function setState(state){
Object.assign(instance.state, state);
instance.render();
});
instance.render = function (){
render(instance.selection, instance.props, instance.state);
};
},
renderInstance = function (props){
var instance = instanceLocal.get(this);
instance.props = props || {};
instance.render();
},
destroyInstance = function (props){
destroy(instanceLocal.get(this).state);
},
selector = className ? "." + className : tagName;
function component(selection, props){
var instances = selection.selectAll(selector)
.data(Array.isArray(props) ? props : [props]);
instances
.enter().append(tagName)
.attr("class", className)
.each(createInstance)
.merge(instances)
.each(renderInstance);
instances
.exit()
.each(destroyInstance)
.remove();
}
component.render = function(_) { return (render = _, component); };
component.create = function(_) { return (create = _, component); };
component.destroy = function(_) { return (destroy = _, component); };
return component;
};
|
Sort by name, fix vacancy (values in api are occupancy) | from irc3.plugins.command import command
from bytebot_config import BYTEBOT_PLUGIN_CONFIG
from irc3 import asyncio
import aiohttp
import xml.etree.ElementTree as ET
@command(permission="view")
@asyncio.coroutine
def parking(bot, mask, target, args):
"""Show the current parking lot status
%%parking
"""
config = BYTEBOT_PLUGIN_CONFIG['parking']
if config['url'] == "parking_url":
return "I don't have your parking url!"
bot.privmsg(target, 'Parkhausbelegung:')
with aiohttp.Timeout(10):
with aiohttp.ClientSession(loop=bot.loop) as session:
resp = yield from session.get(config['url'])
if resp.status != 200:
bot.privmsg(target, "Error while retrieving parking data")
raise Exception()
r = yield from resp.read()
root = ET.fromstring(r)
"""Sort XML by element longname"""
root[:] = sorted(root, key=lambda key: key.findtext("longname"))
for lot in root.findall('ph'):
bot.privmsg(
target,
" {name:32}{use:3} von {max:3} frei".format(
name=lot.find('longname').text,
use=(
int(lot.find('kapazitaet').text) -
int(lot.find('belegung').text)
),
max=int(lot.find('kapazitaet').text)
)
)
| from irc3.plugins.command import command
from bytebot_config import BYTEBOT_PLUGIN_CONFIG
from irc3 import asyncio
import aiohttp
import xml.etree.ElementTree as ET
@command(permission="view")
@asyncio.coroutine
def parking(bot, mask, target, args):
"""Show the current parking lot status
%%parking
"""
config = BYTEBOT_PLUGIN_CONFIG['parking']
if config['url'] == "parking_url":
return "I don't have your parking url!"
bot.privmsg(target, 'Parkhausbelegung:')
with aiohttp.Timeout(10):
with aiohttp.ClientSession(loop=bot.loop) as session:
resp = yield from session.get(config['url'])
if resp.status != 200:
bot.privmsg(target, "Error while retrieving parking data")
raise Exception()
r = yield from resp.read()
root = ET.fromstring(r)
for lot in root.findall('ph'):
bot.privmsg(target,
" {name:32}{use:3} von {max:3} frei".format(
name=lot.find('longname').text,
use=int(lot.find('belegung').text),
max=int(lot.find('kapazitaet').text)
))
|
Update RandomSampler to use the new Sampler abc | """
RandomSampler
-------------
A random sampler that can be used for unit testing and debugging.
"""
import numpy as np
from dimod.core.sampler import Sampler
from dimod.response import Response, SampleView
__all__ = ['RandomSampler']
class RandomSampler(Sampler):
"""Gives random samples.
Note that this sampler is intended for testing.
"""
properties = None
parameters = None
def __init__(self):
self.parameters = {'num_reads': []}
self.properties = {}
def sample(self, bqm, num_reads=10):
"""Gives random samples.
Args:
todo
Returns:
:obj:`.Response`: The vartype will match the given binary quadratic model.
Notes:
For each variable in each sample, the value is chosen by a coin flip.
"""
values = np.asarray(list(bqm.vartype.value), dtype='int8')
samples = np.random.choice(values, (num_reads, len(bqm)))
variable_labels = list(bqm.linear)
label_to_idx = {v: idx for idx, v in enumerate(variable_labels)}
energies = [bqm.energy(SampleView(idx, samples, label_to_idx)) for idx in range(num_reads)]
return Response.from_matrix(samples, {'energy': energies},
vartype=bqm.vartype, variable_labels=variable_labels)
| """
RandomSampler
-------------
A random sampler that can be used for unit testing and debugging.
"""
import numpy as np
from dimod.core.sampler import Sampler
from dimod.response import Response, SampleView
__all__ = ['RandomSampler']
class RandomSampler(Sampler):
"""Gives random samples.
Note that this sampler is intended for testing.
"""
def __init__(self):
Sampler.__init__(self)
self.sample_kwargs = {'num_reads': []}
def sample(self, bqm, num_reads=10):
"""Gives random samples.
Args:
todo
Returns:
:obj:`.Response`: The vartype will match the given binary quadratic model.
Notes:
For each variable in each sample, the value is chosen by a coin flip.
"""
values = np.asarray(list(bqm.vartype.value), dtype='int8')
samples = np.random.choice(values, (num_reads, len(bqm)))
variable_labels = list(bqm.linear)
label_to_idx = {v: idx for idx, v in enumerate(variable_labels)}
energies = [bqm.energy(SampleView(idx, samples, label_to_idx)) for idx in range(num_reads)]
return Response.from_matrix(samples, {'energy': energies},
vartype=bqm.vartype, variable_labels=variable_labels)
|
Use creation date of mining activity, not update date. | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\MiningActivity;
use App\Payment;
use Illuminate\Support\Facades\DB;
class ReportsController extends Controller
{
/**
* Default report view. Show a table of dates with amount mined per day.
*/
public function main()
{
$daily_mining = MiningActivity::select(DB::raw('SUM(quantity) AS quantity, DAY(created_at) AS order_day, MONTH(created_at) AS order_month, YEAR(created_at) AS order_year'))
->groupBy('order_day', 'order_month', 'order_year')
->orderBy('order_year', 'desc')
->orderBy('order_month', 'desc')
->orderBy('order_day', 'desc')
->get();
$daily_income = Payment::select(DB::raw('SUM(amount_received) AS amount, DAY(updated_at) AS order_day, MONTH(updated_at) AS order_month, YEAR(updated_at) AS order_year'))
->groupBy('order_day', 'order_month', 'order_year')
->orderBy('order_year', 'desc')
->orderBy('order_month', 'desc')
->orderBy('order_day', 'desc')
->get();
return view('reports.main', [
'daily_mining' => $daily_mining,
'daily_income' => $daily_income,
]);
}
}
| <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\MiningActivity;
use App\Payment;
use Illuminate\Support\Facades\DB;
class ReportsController extends Controller
{
/**
* Default report view. Show a table of dates with amount mined per day.
*/
public function main()
{
$daily_mining = MiningActivity::select(DB::raw('SUM(quantity) AS quantity, DAY(updated_at) AS order_day, MONTH(updated_at) AS order_month, YEAR(updated_at) AS order_year'))
->groupBy('order_day', 'order_month', 'order_year')
->orderBy('order_year', 'desc')
->orderBy('order_month', 'desc')
->orderBy('order_day', 'desc')
->get();
$daily_income = Payment::select(DB::raw('SUM(amount_received) AS amount, DAY(updated_at) AS order_day, MONTH(updated_at) AS order_month, YEAR(updated_at) AS order_year'))
->groupBy('order_day', 'order_month', 'order_year')
->orderBy('order_year', 'desc')
->orderBy('order_month', 'desc')
->orderBy('order_day', 'desc')
->get();
return view('reports.main', [
'daily_mining' => $daily_mining,
'daily_income' => $daily_income,
]);
}
}
|
Revert "rollback change after [byte_sequence -> byteSeq]" | import { generateGame } from "./";
import PlayerModel from "../../model/player_model";
describe(`generator:: Game`, () => {
describe(`::generate`, () => {
[0, 1, 2, 10].forEach((v) => {
it(`expected ${v} battlefields`, () => {
const model = generateGame(v, 0);
expect(model.getBattlefields().length).toBe(v);
});
});
[1, 2, 10].forEach(v => {
it(`expected last player of ${v} to be market as Human Controlled`, () => {
const model = generateGame(v, 0);
model.getBattlefields().forEach((bf, index) => {
const expectedSeq = index === (v - 1) ? PlayerModel.getHumanFlag() : 0;
expect(bf.getPlayer().byteSeq).toBe(expectedSeq);
});
});
});
[0, 1, 2, 10].forEach(size => {
const expectedCellAmount = size ** 2;
it(`expected 2 battlefields with size ${size} attached [expected ${expectedCellAmount} cells]`, () => {
const model = generateGame(2, size);
/** @param {BattlefieldModel} battlefieldModel */
for (const battlefieldModel of model.getBattlefields()) {
const cells = battlefieldModel.getCellsIndexedByCoordinate();
expect(Object.keys(cells).length).toBe(expectedCellAmount);
}
});
});
});
});
| import { generateGame } from "./";
import PlayerModel from "../../model/player_model";
describe(`generator:: Game`, () => {
describe(`::generate`, () => {
[0, 1, 2, 10].forEach((v) => {
it(`expected ${v} battlefields`, () => {
const model = generateGame(v, 0);
expect(model.getBattlefields().length).toBe(v);
});
});
[1, 2, 10].forEach(v => {
it(`expected last player of ${v} to be market as Human Controlled`, () => {
const model = generateGame(v, 0);
model.getBattlefields().forEach((bf, index) => {
const expectedSeq = index === (v - 1) ? PlayerModel.getHumanFlag() : 0;
expect(bf.getPlayer().byte_sequence).toBe(expectedSeq);
});
});
});
[0, 1, 2, 10].forEach(size => {
const expectedCellAmount = size ** 2;
it(`expected 2 battlefields with size ${size} attached [expected ${expectedCellAmount} cells]`, () => {
const model = generateGame(2, size);
/** @param {BattlefieldModel} battlefieldModel */
for (const battlefieldModel of model.getBattlefields()) {
const cells = battlefieldModel.getCellsIndexedByCoordinate();
expect(Object.keys(cells).length).toBe(expectedCellAmount);
}
});
});
});
});
|
Check SHAP Model call type | import numpy as np
from .._serializable import Serializable, Serializer, Deserializer
from torch import Tensor
class Model(Serializable):
""" This is the superclass of all models.
"""
def __init__(self, model=None):
""" Wrap a callable model as a SHAP Model object.
"""
if isinstance(model, Model):
self.inner_model = model.inner_model
else:
self.inner_model = model
if hasattr(model, "output_names"):
self.output_names = model.output_names
def __call__(self, *args):
out = self.inner_model(*args)
out = out.cpu().detach().numpy() if isinstance(out, Tensor) else np.array(out)
return out
def save(self, out_file):
""" Save the model to the given file stream.
"""
super().save(out_file)
with Serializer(out_file, "shap.Model", version=0) as s:
s.save("model", self.inner_model)
@classmethod
def load(cls, in_file, instantiate=True):
if instantiate:
return cls._instantiated_load(in_file)
kwargs = super().load(in_file, instantiate=False)
with Deserializer(in_file, "shap.Model", min_version=0, max_version=0) as s:
kwargs["model"] = s.load("model")
return kwargs
| import numpy as np
from .._serializable import Serializable, Serializer, Deserializer
class Model(Serializable):
""" This is the superclass of all models.
"""
def __init__(self, model=None):
""" Wrap a callable model as a SHAP Model object.
"""
if isinstance(model, Model):
self.inner_model = model.inner_model
else:
self.inner_model = model
if hasattr(model, "output_names"):
self.output_names = model.output_names
def __call__(self, *args):
return np.array(self.inner_model(*args))
def save(self, out_file):
""" Save the model to the given file stream.
"""
super().save(out_file)
with Serializer(out_file, "shap.Model", version=0) as s:
s.save("model", self.inner_model)
@classmethod
def load(cls, in_file, instantiate=True):
if instantiate:
return cls._instantiated_load(in_file)
kwargs = super().load(in_file, instantiate=False)
with Deserializer(in_file, "shap.Model", min_version=0, max_version=0) as s:
kwargs["model"] = s.load("model")
return kwargs
|
CUDA: Reorder FloatModel checks in ascending order | from llvmlite import ir
from numba.core.datamodel.registry import register_default
from numba.core.extending import register_model, models
from numba.core import types
from numba.cuda.types import Dim3, GridGroup, CUDADispatcher
@register_model(Dim3)
class Dim3Model(models.StructModel):
def __init__(self, dmm, fe_type):
members = [
('x', types.int32),
('y', types.int32),
('z', types.int32)
]
super().__init__(dmm, fe_type, members)
@register_model(GridGroup)
class GridGroupModel(models.PrimitiveModel):
def __init__(self, dmm, fe_type):
be_type = ir.IntType(64)
super().__init__(dmm, fe_type, be_type)
@register_default(types.Float)
class FloatModel(models.PrimitiveModel):
def __init__(self, dmm, fe_type):
if fe_type == types.float16:
be_type = ir.IntType(16)
elif fe_type == types.float32:
be_type = ir.FloatType()
elif fe_type == types.float64:
be_type = ir.DoubleType()
else:
raise NotImplementedError(fe_type)
super(FloatModel, self).__init__(dmm, fe_type, be_type)
register_model(CUDADispatcher)(models.OpaqueModel)
| from llvmlite import ir
from numba.core.datamodel.registry import register_default
from numba.core.extending import register_model, models
from numba.core import types
from numba.cuda.types import Dim3, GridGroup, CUDADispatcher
@register_model(Dim3)
class Dim3Model(models.StructModel):
def __init__(self, dmm, fe_type):
members = [
('x', types.int32),
('y', types.int32),
('z', types.int32)
]
super().__init__(dmm, fe_type, members)
@register_model(GridGroup)
class GridGroupModel(models.PrimitiveModel):
def __init__(self, dmm, fe_type):
be_type = ir.IntType(64)
super().__init__(dmm, fe_type, be_type)
@register_default(types.Float)
class FloatModel(models.PrimitiveModel):
def __init__(self, dmm, fe_type):
if fe_type == types.float32:
be_type = ir.FloatType()
elif fe_type == types.float16:
be_type = ir.IntType(16)
elif fe_type == types.float64:
be_type = ir.DoubleType()
else:
raise NotImplementedError(fe_type)
super(FloatModel, self).__init__(dmm, fe_type, be_type)
register_model(CUDADispatcher)(models.OpaqueModel)
|
Remove static var from side effect | import React, { Component } from 'react'
import { getDisplayName } from './utils'
const canUseDOM = typeof window !== 'undefined'
export default function withSideEffect (reduceComponentsToState, handleStateChangeOnClient) {
return function wrap (WrappedComponent) {
let mountedInstances = []
let state
function emitChange (component) {
state = reduceComponentsToState(mountedInstances)
if (canUseDOM) {
handleStateChangeOnClient.call(component, state)
}
}
class SideEffect extends Component {
// Try to use displayName of wrapped component
static displayName = `SideEffect(${getDisplayName(WrappedComponent)})`
static peek () {
return state
}
static rewind () {
if (process.env.NODE_ENV !== 'production' && canUseDOM) {
throw new Error('You may only call rewind() on the server. Call peek() to read the current state.')
}
const recordedState = state
state = undefined
mountedInstances = []
return recordedState
}
componentWillMount () {
mountedInstances.push(this)
emitChange(this)
}
componentDidUpdate () {
emitChange(this)
}
componentWillUnmount () {
const index = mountedInstances.indexOf(this)
if (index >= 0) {
mountedInstances.splice(index, 1)
}
emitChange(this)
}
render () {
return <WrappedComponent>{ this.props.children }</WrappedComponent>
}
}
return SideEffect
}
}
| import React, { Component } from 'react'
import { getDisplayName } from './utils'
export default function withSideEffect (reduceComponentsToState, handleStateChangeOnClient) {
return function wrap (WrappedComponent) {
let mountedInstances = []
let state
function emitChange (component) {
state = reduceComponentsToState(mountedInstances)
if (SideEffect.canUseDOM) {
handleStateChangeOnClient.call(component, state)
}
}
class SideEffect extends Component {
// Try to use displayName of wrapped component
static displayName = `SideEffect(${getDisplayName(WrappedComponent)})`
// Expose canUseDOM so tests can monkeypatch it
static canUseDOM = typeof window !== 'undefined'
static peek () {
return state
}
static rewind () {
if (process.env.NODE_ENV !== 'production' && SideEffect.canUseDOM) {
throw new Error('You may only call rewind() on the server. Call peek() to read the current state.')
}
const recordedState = state
state = undefined
mountedInstances = []
return recordedState
}
componentWillMount () {
mountedInstances.push(this)
emitChange(this)
}
componentDidUpdate () {
emitChange(this)
}
componentWillUnmount () {
const index = mountedInstances.indexOf(this)
if (index >= 0) {
mountedInstances.splice(index, 1)
}
emitChange(this)
}
render () {
return <WrappedComponent>{ this.props.children }</WrappedComponent>
}
}
return SideEffect
}
}
|
Add in a way to specify the utmp file path for unit testing | # coding=utf-8
"""
Collects the number of users logged in and shells per user
#### Dependencies
* [pyutmp](http://software.clapper.org/pyutmp/)
"""
import diamond.collector
from pyutmp import UtmpFile
class UsersCollector(diamond.collector.Collector):
def get_default_config_help(self):
"""
Returns the default collector help text
"""
config_help = super(UsersCollector, self).get_default_config_help()
config_help.update({
})
return config_help
def get_default_config(self):
"""
Returns the default collector settings
"""
config = super(UsersCollector, self).get_default_config()
config.update({
'path': 'users',
'method': 'Threaded',
'utmp': None,
})
return config
def collect(self):
metrics = {}
metrics['total'] = 0
for utmp in UtmpFile(path=self.config['utmp']):
if utmp.ut_user_process:
metrics[utmp.ut_user] = metrics.get(utmp.ut_user, 0)+1
metrics['total'] = metrics['total']+1
for metric_name in metrics.keys():
self.publish(metric_name, metrics[metric_name])
return True
| # coding=utf-8
"""
Collects the number of users logged in and shells per user
#### Dependencies
* [pyutmp](http://software.clapper.org/pyutmp/)
"""
import diamond.collector
from pyutmp import UtmpFile
class UsersCollector(diamond.collector.Collector):
def get_default_config_help(self):
"""
Returns the default collector help text
"""
config_help = super(UsersCollector, self).get_default_config_help()
config_help.update({
})
return config_help
def get_default_config(self):
"""
Returns the default collector settings
"""
config = super(UsersCollector, self).get_default_config()
config.update({
'path': 'users',
'method': 'Threaded',
})
return config
def collect(self):
metrics = {}
metrics['total'] = 0
for utmp in UtmpFile():
if utmp.ut_user_process:
metrics[utmp.ut_user] = metrics.get(utmp.ut_user, 0)+1
metrics['total'] = metrics['total']+1
for metric_name in metrics.keys():
self.publish(metric_name, metrics[metric_name])
return True
|
Fix ComponentBuilder order in registry | /*
* Copyright 2014 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Eclipse Public License version 1.0, available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.jboss.forge.plugin.idea.ui.component;
import org.jboss.forge.addon.ui.input.InputComponent;
/**
* A factory for {@link ComponentBuilder} instances.
*
* @author <a href="mailto:[email protected]">George Gastaldi</a>
*/
public enum ComponentBuilderRegistry
{
INSTANCE;
private ComponentBuilder[] componentBuilders = {
new CheckboxComponentBuilder(),
new ComboComponentBuilder(),
new RadioComponentBuilder(),
new TextBoxComponentBuilder(),
new PasswordComponentBuilder(),
new TextAreaComponentBuilder(),
new FileChooserComponentBuilder(),
new DirectoryChooserComponentBuilder(),
new JavaClassChooserComponentBuilder(),
new JavaPackageChooserComponentBuilder(),
new FallbackTextBoxComponentBuilder()};
public ComponentBuilder getBuilderFor(InputComponent<?, ?> input)
{
for (ComponentBuilder builder : componentBuilders)
{
if (builder.handles(input))
{
return builder;
}
}
throw new IllegalArgumentException(
"No UI component found for input type of "
+ input.getValueType()
);
}
}
| /*
* Copyright 2014 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Eclipse Public License version 1.0, available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.jboss.forge.plugin.idea.ui.component;
import org.jboss.forge.addon.ui.input.InputComponent;
/**
* A factory for {@link ComponentBuilder} instances.
*
* @author <a href="mailto:[email protected]">George Gastaldi</a>
*/
public enum ComponentBuilderRegistry
{
INSTANCE;
private ComponentBuilder[] componentBuilders = {
new CheckboxComponentBuilder(),
new ComboComponentBuilder(),
new RadioComponentBuilder(),
new FileChooserComponentBuilder(),
new DirectoryChooserComponentBuilder(),
new JavaClassChooserComponentBuilder(),
new JavaPackageChooserComponentBuilder(),
new TextBoxComponentBuilder(),
new PasswordComponentBuilder(),
new TextAreaComponentBuilder(),
new FallbackTextBoxComponentBuilder()};
public ComponentBuilder getBuilderFor(InputComponent<?, ?> input)
{
for (ComponentBuilder builder : componentBuilders)
{
if (builder.handles(input))
{
return builder;
}
}
throw new IllegalArgumentException(
"No UI component found for input type of "
+ input.getValueType()
);
}
}
|
Add get dice roll function | import random
class Die(object):
def __init__(self, sides = 6):
self.sides = sides
self.held = False
self.die_face = 1
def change_held(self, held):
self.held = held
def roll_die(self):
if (self.held == False):
self.die_face = random.randint(1, self.sides)
else:
pass
def get_die_face(self):
return self.die_face
class DiceBag(object):
def __init__(self):
self.dice = []
self.dice_roll = []
def add_die_obj(self, die_obj):
self.dice.append(die_obj)
def remove_die(self, die_obj):
self.dice.remove(die_obj)
def remove_die_index(self, index):
del self.dice[index]
def add_die_notation(self, standard_die_notation):
lst_notation = standard_die_notation.split("d")
for i in int(lst_notation[0]):
die1 = Die(int(lst_notation[1]))
self.dice.append(die1)
def roll_all(self):
for obj in self.dice:
obj.roll_die()
self.dice_roll.append(obj.get_die_face())
def get_dice_roll(self):
return self.dice_roll
| import random
class Die(object):
def __init__(self, sides = 6):
self.sides = sides
self.held = False
self.die_face = 1
def change_held(self, held):
self.held = held
def roll_die(self):
if (self.held == False):
self.die_face = random.randint(1, self.sides)
else:
pass
def get_die_face(self):
return self.die_face
class DiceBag(object):
def __init__(self):
self.dice = []
self.dice_roll = []
def add_die_obj(self, die_obj):
self.dice.append(die_obj)
def remove_die(self, die_obj):
self.dice.remove(die_obj)
def remove_die_index(self, index):
del self.dice[index]
def add_die_notation(self, standard_die_notation):
lst_notation = standard_die_notation.split("d")
for i in int(lst_notation[0]):
die1 = Die(int(lst_notation[1]))
self.dice.append(die1)
def roll_all(self):
for obj in self.dice:
obj.roll_die()
self.dice_roll.append(obj.get_die_face())
|
Exclude more unneeded files from default plan
This patch exludes more file types from the tarball uploaded to swift as
the default deployment plan.
Change-Id: I8b6d8de8d7662604cdb871fa6a4fb872c7937e25
Closes-Bug: #1613286 | # Copyright 2016 Red Hat, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import logging
from oslo_concurrency import processutils
LOG = logging.getLogger(__name__)
def create_tarball(directory, filename, options='-czf'):
"""Create a tarball of a directory."""
LOG.debug('Creating tarball of %s at location %s' % (directory, filename))
processutils.execute('/usr/bin/tar', '-C', directory, options, filename,
'--exclude', '.git', '--exclude', '.tox',
'--exclude', '*.pyc', '--exclude', '*.pyo', '.')
def tarball_extract_to_swift_container(object_client, filename, container):
LOG.debug('Uploading filename %s to Swift container %s' % (filename,
container))
with open(filename, 'r') as f:
object_client.put_object(
container=container,
obj='',
contents=f,
query_string='extract-archive=tar.gz',
headers={'X-Detect-Content-Type': 'true'}
)
| # Copyright 2016 Red Hat, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import logging
from oslo_concurrency import processutils
LOG = logging.getLogger(__name__)
def create_tarball(directory, filename, options='-czf'):
"""Create a tarball of a directory."""
LOG.debug('Creating tarball of %s at location %s' % (directory, filename))
processutils.execute('/usr/bin/tar', '-C', directory, options, filename,
'--exclude', '.git', '--exclude', '.tox', '.')
def tarball_extract_to_swift_container(object_client, filename, container):
LOG.debug('Uploading filename %s to Swift container %s' % (filename,
container))
with open(filename, 'r') as f:
object_client.put_object(
container=container,
obj='',
contents=f,
query_string='extract-archive=tar.gz',
headers={'X-Detect-Content-Type': 'true'}
)
|
Include minified file in grunt bump-commit | module.exports = function (grunt) {
'use strict';
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
all: [
'./src/paginate-anything.js', '*.json', './test/*.js'
],
options: {
jshintrc: '.jshintrc'
}
},
karma: {
travis: {
configFile: 'karma.conf.js',
singleRun: true,
browsers: ['PhantomJS']
}
},
bump: {
options: {
files: ['package.json', 'bower.json'],
commitFiles: ['package.json', 'bower.json', 'src/paginate-anything.min.js'],
pushTo: 'origin'
}
},
uglify: {
options: {
banner: '// <%= pkg.name %> - v<%= pkg.version %>\n'
},
dist: {
files: {
'src/paginate-anything.min.js': ['src/paginate-anything.js']
}
}
}
});
grunt.loadNpmTasks('grunt-bump');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-karma');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.registerTask('test', ['jshint', 'karma:travis']);
};
| module.exports = function (grunt) {
'use strict';
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
all: [
'./src/paginate-anything.js', '*.json', './test/*.js'
],
options: {
jshintrc: '.jshintrc'
}
},
karma: {
travis: {
configFile: 'karma.conf.js',
singleRun: true,
browsers: ['PhantomJS']
}
},
bump: {
options: {
files: ['package.json', 'bower.json'],
commitFiles: ['package.json', 'bower.json'],
pushTo: 'origin'
}
},
uglify: {
options: {
banner: '// <%= pkg.name %> - v<%= pkg.version %>\n'
},
dist: {
files: {
'src/paginate-anything.min.js': ['src/paginate-anything.js']
}
}
}
});
grunt.loadNpmTasks('grunt-bump');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-karma');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.registerTask('test', ['jshint', 'karma:travis']);
};
|
Increase theme zip file upload limit to 10MB | <?php
declare(strict_types=1);
/*
* This file is part of the Superdesk Web Publisher Core Bundle.
*
* Copyright 2017 Sourcefabric z.ú. and contributors.
*
* For the full copyright and license information, please see the
* AUTHORS and LICENSE files distributed with this source code.
*
* @copyright 2017 Sourcefabric z.ú
* @license http://www.superdesk.org/license
*/
namespace SWP\Bundle\CoreBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\File;
final class ThemeUploadType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('file', FileType::class, [
'required' => true,
'constraints' => [
new File([
'maxSize' => '10240k',
'mimeTypes' => [
'application/zip',
],
]),
],
])
;
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(['csrf_protection' => false]);
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return 'theme_upload';
}
}
| <?php
declare(strict_types=1);
/*
* This file is part of the Superdesk Web Publisher Core Bundle.
*
* Copyright 2017 Sourcefabric z.ú. and contributors.
*
* For the full copyright and license information, please see the
* AUTHORS and LICENSE files distributed with this source code.
*
* @copyright 2017 Sourcefabric z.ú
* @license http://www.superdesk.org/license
*/
namespace SWP\Bundle\CoreBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\File;
final class ThemeUploadType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('file', FileType::class, [
'required' => true,
'constraints' => [
new File([
'maxSize' => '5120k',
'mimeTypes' => [
'application/zip',
],
]),
],
])
;
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(['csrf_protection' => false]);
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return 'theme_upload';
}
}
|
Allow to overwrite the pipeline processor return value | import functools
def coroutine(fn):
def wrapper(*args, **kwargs):
generator = fn(*args, **kwargs)
next(generator)
return generator
return wrapper
class CollectionPipelineProcessor:
sink = None
start_source = None
receiver = None
def process(self, item):
raise NotImplementedError
def on_done(self):
if self.receiver:
self.receiver.close()
def source(self, start_source):
self.start_source = start_source
def return_value(self):
"""Processor return value when used with __or__ operator.
Returns:
CollectionPipelineProcessor: when processor is to be chained
with other processors.
any: any other value when processor is used as an output and is
meant to return value. In this way we can assign
the output result to python variable.
"""
return self
@coroutine
def make_generator(self):
while True:
try:
item = yield
self.process(item)
except GeneratorExit:
self.on_done()
break
def __or__(self, other):
"""Overwrites the '|' operator.
Args:
other (CollectionPipelineProcessor)
Returns:
whatever other.return_value() returns.
"""
self.sink = other
def exec():
self.receiver = self.sink.make_generator()
self.start_source()
other.source(exec)
return other.return_value()
class CollectionPipelineOutput(CollectionPipelineProcessor):
"""Pipeline processor that ends the chain and starts outputing stream.
Output processor immediately starts consuming from the source.
Thus triggering the whole pipeline start.
"""
def source(self, start_source):
start_source()
| import functools
def coroutine(fn):
def wrapper(*args, **kwargs):
generator = fn(*args, **kwargs)
next(generator)
return generator
return wrapper
class CollectionPipelineProcessor:
sink = None
start_source = None
receiver = None
def process(self, item):
raise NotImplementedError
def on_done(self):
if self.receiver:
self.receiver.close()
def source(self, start_source):
self.start_source = start_source
@coroutine
def make_generator(self):
while True:
try:
item = yield
self.process(item)
except GeneratorExit:
self.on_done()
break
def __or__(self, other):
self.sink = other
def exec():
self.receiver = self.sink.make_generator()
self.start_source()
other.source(exec)
return other
class CollectionPipelineOutput(CollectionPipelineProcessor):
"""Pipeline processor that ends the chain and starts outputing stream.
Output processor immediately starts consuming from the source.
Thus triggering the whole pipeline start.
"""
def source(self, start_source):
start_source()
|
Remove double slashes in the Redis commands urls | #!/usr/bin/python
# -*- coding: utf-8 -*-
import lxml.etree, lxml.html
import re
url = "http://redis.io"
output = "output.txt"
f = open(output, "w");
tree = lxml.html.parse("download/raw.dat").getroot()
commands = tree.find_class("command")
data = {}
for command in commands:
for row in command.findall('a'):
command_url = "%s%s" % (url, row.get('href'))
for sibling in command.itersiblings():
usage = ""
for command_args in command.findall('span'):
usage = "Usage: %s %s" % (row.text, command_args.text.replace(' ', '').replace('\n', ' ').strip())
summary = "%s<br>%s" % (sibling.text, usage)
data[command_url] = (row.text, summary)
for command_url in data.keys():
command, summary = data[command_url]
summary = unicode(summary).encode("utf-8")
f.write("\t".join([str(command), # title
"", # namespace
command_url, # url
summary, # description
"", # synopsis
"", # details
"", # type
"" # lang
])
)
f.write("\n")
f.close()
| #!/usr/bin/python
# -*- coding: utf-8 -*-
import lxml.etree, lxml.html
import re
url = "http://redis.io"
output = "output.txt"
f = open(output, "w");
tree = lxml.html.parse("download/raw.dat").getroot()
commands = tree.find_class("command")
data = {}
for command in commands:
for row in command.findall('a'):
command_url = "%s/%s" % (url, row.get('href'))
for sibling in command.itersiblings():
usage = ""
for command_args in command.findall('span'):
usage = "Usage: %s %s" % (row.text, command_args.text.replace(' ', '').replace('\n', ' ').strip())
summary = "%s<br>%s" % (sibling.text, usage)
data[command_url] = (row.text, summary)
for command_url in data.keys():
command, summary = data[command_url]
summary = unicode(summary).encode("utf-8")
f.write("\t".join([str(command), # title
"", # namespace
command_url, # url
summary, # description
"", # synopsis
"", # details
"", # type
"" # lang
])
)
f.write("\n")
f.close()
|
Move health check route first, otherwise it gets shadowed | <?php
// Health check
$app->get('/health', function() {
return 'OK';
});
// Shows the dashboard, if enabled
$app->get('/', [
'middleware' => \Nord\ImageManipulationService\Http\Middleware\DashboardPageEnabledMiddleware::class,
'uses' => 'DashboardController@dashboard',
]);
// Shows the upload page, if enabled
$app->get('/upload', [
'middleware' => \Nord\ImageManipulationService\Http\Middleware\UploadPageEnabledMiddleware::class,
'uses' => 'ImageController@index',
]);
// Serves an image
$app->get('/{path:.*}', [
'as' => 'serveImage',
'middleware' => \Nord\ImageManipulationService\Http\Middleware\ServeImageAuthenticationMiddleware::class,
'uses' => 'ImageController@serveImage',
]);
// Stores an uploaded image to the source filesystem, then returns the path to it
$app->post('/upload', [
'middleware' => [
\Nord\ImageManipulationService\Http\Middleware\UploadAuthenticationMiddleware::class,
\Nord\ImageManipulationService\Http\Middleware\ImageUploadFromFileValidatorMiddleware::class,
],
'uses' => 'ImageController@uploadImageFromFile',
]);
$app->post('/uploadFromUrl', [
'middleware' => [
\Nord\ImageManipulationService\Http\Middleware\UploadAuthenticationMiddleware::class,
\Nord\ImageManipulationService\Http\Middleware\ImageUploadFromUrlValidatorMiddleware::class,
],
'uses' => 'ImageController@uploadImageFromUrl',
]);
| <?php
// Shows the dashboard, if enabled
$app->get('/', [
'middleware' => \Nord\ImageManipulationService\Http\Middleware\DashboardPageEnabledMiddleware::class,
'uses' => 'DashboardController@dashboard',
]);
// Shows the upload page, if enabled
$app->get('/upload', [
'middleware' => \Nord\ImageManipulationService\Http\Middleware\UploadPageEnabledMiddleware::class,
'uses' => 'ImageController@index',
]);
// Serves an image
$app->get('/{path:.*}', [
'as' => 'serveImage',
'middleware' => \Nord\ImageManipulationService\Http\Middleware\ServeImageAuthenticationMiddleware::class,
'uses' => 'ImageController@serveImage',
]);
// Health check
$app->get('/health', function() {
return 'OK';
});
// Stores an uploaded image to the source filesystem, then returns the path to it
$app->post('/upload', [
'middleware' => [
\Nord\ImageManipulationService\Http\Middleware\UploadAuthenticationMiddleware::class,
\Nord\ImageManipulationService\Http\Middleware\ImageUploadFromFileValidatorMiddleware::class,
],
'uses' => 'ImageController@uploadImageFromFile',
]);
$app->post('/uploadFromUrl', [
'middleware' => [
\Nord\ImageManipulationService\Http\Middleware\UploadAuthenticationMiddleware::class,
\Nord\ImageManipulationService\Http\Middleware\ImageUploadFromUrlValidatorMiddleware::class,
],
'uses' => 'ImageController@uploadImageFromUrl',
]);
|
Use correct method name. [rev: matthew.gordon2] | /**
* @module js-utils/js/repeater
*/
define([
'underscore'
], function () {
/**
* @name module:js-utils/js/repeater.Repeater
* @desc Wrapper around setTimeout that allows for the control of the timeout
* @param {function} f The function to be called
* @param {number} interval The number of milliseconds between invocations of f
* @constructor
*/
function Repeater(f, interval) {
this.f = f;
this.interval = interval;
this.timeout = null;
this.update = _.bind(this.update, this);
}
_.extend(Repeater.prototype, /** @lends module:js-utils/js/repeater.Repeater.prototype */{
/**
* @desc Stops the timeout
* @returns {Repeater} this
*/
stop: function () {
if (this.timeout !== null) {
clearTimeout(this.timeout);
this.timeout = null;
}
return this;
},
/**
* @desc Starts the timeout. If it has already started, this will reset the timeout
* @returns {Repeater} this
*/
start: function () {
this.stop();
this.timeout = _.delay(this.update, this.interval);
return this;
},
/**
* @desc Calls the provided function
* @returns {Repeater} this
*/
update: function () {
this.f();
if (this.timeout !== null) {
this.start();
}
return this;
}
});
return Repeater;
}); | /**
* @module js-utils/js/repeater
*/
define([
'underscore'
], function () {
/**
* @name module:js-utils/js/repeater.Repeater
* @desc Wrapper around setTimeout that allows for the control of the timeout
* @param {function} f The function to be called
* @param {number} interval The number of milliseconds between invocations of f
* @constructor
*/
function Repeater(f, interval) {
this.f = f;
this.interval = interval;
this.timeout = null;
this.update = _.bind(this.update, this);
}
_.extends(Repeater.prototype, /** @lends module:js-utils/js/repeater.Repeater.prototype */{
/**
* @desc Stops the timeout
* @returns {Repeater} this
*/
stop: function () {
if (this.timeout !== null) {
clearTimeout(this.timeout);
this.timeout = null;
}
return this;
},
/**
* @desc Starts the timeout. If it has already started, this will reset the timeout
* @returns {Repeater} this
*/
start: function () {
this.stop();
this.timeout = _.delay(this.update, this.interval);
return this;
},
/**
* @desc Calls the provided function
* @returns {Repeater} this
*/
update: function () {
this.f();
if (this.timeout !== null) {
this.start();
}
return this;
}
});
return Repeater;
}); |
Fix leave that returns callback. | var slice = [].slice
function Vestibule () {
this._waiting = []
this.occupied = false
this.open = null
}
Vestibule.prototype.enter = function (timeout, callback) {
if (callback == null) {
callback = timeout
timeout = null
}
if (this.open == null) {
if (timeout != null) {
timeout = setTimeout(this.notify.bind(this), timeout)
}
var cookie = {}
this.occupied = true
this._waiting.push({
cookie: cookie,
callback: callback,
timeout: timeout
})
return cookie
}
callback.apply(null, this.open)
return null
}
Vestibule.prototype.leave = function (cookie) {
var left = null
for (var i = 0, I = this._waiting.length; i < I; i++) {
if (this._waiting[i].cookie === cookie) {
left = this._waiting.splice(i, 1).shift().callback
break
}
}
this.occupied = this._waiting.length != 0
return left
}
Vestibule.prototype.notify = function () {
var vargs = slice.call(arguments)
this.occupied = false
this._waiting.splice(0, this._waiting.length).forEach(function (waiting) {
if (waiting.timeout) {
clearTimeout(waiting.timeout)
}
waiting.callback.apply(null, vargs)
})
}
module.exports = Vestibule
| var slice = [].slice
function Vestibule () {
this._waiting = []
this.occupied = false
this.open = null
}
Vestibule.prototype.enter = function (timeout, callback) {
if (callback == null) {
callback = timeout
timeout = null
}
if (this.open == null) {
if (timeout != null) {
timeout = setTimeout(this.notify.bind(this), timeout)
}
var cookie = {}
this.occupied = true
this._waiting.push({
cookie: cookie,
callback: callback,
timeout: timeout
})
return cookie
}
callback.apply(null, this.open)
return null
}
Vestibule.prototype.leave = function (cookie) {
var left = null
for (var i = 0, I = this._waiting.length; i < I; i++) {
if (this._waiting[i].cookie === cookie) {
left = this._waiting.splice(i, 1).shift()
break
}
}
this.occupied = this._waiting.length != 0
return left
}
Vestibule.prototype.notify = function () {
var vargs = slice.call(arguments)
this.occupied = false
this._waiting.splice(0, this._waiting.length).forEach(function (waiting) {
if (waiting.timeout) {
clearTimeout(waiting.timeout)
}
waiting.callback.apply(null, vargs)
})
}
module.exports = Vestibule
|
Add encoding to README read | import os
from pathlib import Path
from setuptools import Extension, find_packages, setup
PROJECT_ROOT = Path(__file__).parent
long_description = (PROJECT_ROOT / "README.md").read_text(encoding="utf8")
setup(
name="pyinstrument",
packages=find_packages(include=["pyinstrument", "pyinstrument.*"]),
version="4.1.1",
ext_modules=[
Extension(
"pyinstrument.low_level.stat_profile",
sources=["pyinstrument/low_level/stat_profile.c"],
)
],
description="Call stack profiler for Python. Shows you why your code is slow!",
long_description=long_description,
long_description_content_type="text/markdown",
author="Joe Rickerby",
author_email="[email protected]",
url="https://github.com/joerick/pyinstrument",
keywords=["profiling", "profile", "profiler", "cpu", "time", "sampling"],
install_requires=[],
extras_require={"jupyter": ["ipython"]},
include_package_data=True,
python_requires=">=3.7",
entry_points={"console_scripts": ["pyinstrument = pyinstrument.__main__:main"]},
zip_safe=False,
classifiers=[
"Environment :: Console",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: MacOS",
"Operating System :: Microsoft :: Windows",
"Operating System :: POSIX",
"Topic :: Software Development :: Debuggers",
"Topic :: Software Development :: Testing",
],
)
| import os
from setuptools import Extension, find_packages, setup
with open(os.path.join(os.path.dirname(__file__), "README.md")) as f:
long_description = f.read()
setup(
name="pyinstrument",
packages=find_packages(include=["pyinstrument", "pyinstrument.*"]),
version="4.1.1",
ext_modules=[
Extension(
"pyinstrument.low_level.stat_profile",
sources=["pyinstrument/low_level/stat_profile.c"],
)
],
description="Call stack profiler for Python. Shows you why your code is slow!",
long_description=long_description,
long_description_content_type="text/markdown",
author="Joe Rickerby",
author_email="[email protected]",
url="https://github.com/joerick/pyinstrument",
keywords=["profiling", "profile", "profiler", "cpu", "time", "sampling"],
install_requires=[],
extras_require={"jupyter": ["ipython"]},
include_package_data=True,
python_requires=">=3.7",
entry_points={"console_scripts": ["pyinstrument = pyinstrument.__main__:main"]},
zip_safe=False,
classifiers=[
"Environment :: Console",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: MacOS",
"Operating System :: Microsoft :: Windows",
"Operating System :: POSIX",
"Topic :: Software Development :: Debuggers",
"Topic :: Software Development :: Testing",
],
)
|
Disable antialias for GL drawing lines | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
import numpy as np
from vispy.visuals.line.arrow import ARROW_TYPES
from vispy.scene import visuals, transforms
from vispy.testing import (requires_application, TestingCanvas,
run_tests_if_main, raises)
from vispy.testing.image_tester import assert_image_approved
@requires_application()
def test_line_draw():
"""Test drawing arrows without transforms"""
vertices = np.array([
[25, 25],
[25, 75],
[50, 25],
[50, 75],
[75, 25],
[75, 75]
]).astype('f32')
arrows = np.array([
vertices[:2],
vertices[3:1:-1],
vertices[4:],
vertices[-1:-3:-1]
]).reshape((4, 4))
with TestingCanvas() as c:
for arrow_type in ARROW_TYPES:
arrow = visuals.Arrow(pos=vertices, arrow_type=arrow_type,
arrows=arrows, arrow_size=10, color='red',
connect="segments", parent=c.scene)
assert_image_approved(c.render(), 'visuals/arrow_type_%s.png' %
arrow_type)
arrow.parent = None
run_tests_if_main()
| # -*- coding: utf-8 -*-
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
import numpy as np
from vispy.visuals.line.arrow import ARROW_TYPES
from vispy.scene import visuals, transforms
from vispy.testing import (requires_application, TestingCanvas,
run_tests_if_main, raises)
from vispy.testing.image_tester import assert_image_approved
@requires_application()
def test_line_draw():
"""Test drawing arrows without transforms"""
vertices = np.array([
[25, 25],
[25, 75],
[50, 25],
[50, 75],
[75, 25],
[75, 75]
]).astype('f32')
arrows = np.array([
vertices[:2],
vertices[3:1:-1],
vertices[4:],
vertices[-1:-3:-1]
]).reshape((4, 4))
with TestingCanvas() as c:
for arrow_type in ARROW_TYPES:
arrow = visuals.Arrow(pos=vertices, arrow_type=arrow_type,
arrows=arrows, arrow_size=10, color='red',
connect="segments", antialias=True,
parent=c.scene)
assert_image_approved(c.render(), 'visuals/arrow_type_%s.png' %
arrow_type)
arrow.parent = None
run_tests_if_main()
|
Add a <reviewer, revision> key to the reviewers table
Summary:
Ref T10967. I'm not 100% sure we need this, but the old edge table had it and I recall an issue long ago where not having this key left us with a bad query plan.
Our data doesn't really provide a way to test this key (we have many revisions and few reviewers, so the query planner always uses revision keys), and building a convincing test case would take a while (lipsum needs some improvements to add reviewers). But in the worst case this key is mostly useless and wastes a few MB of disk space, which isn't a big deal.
So I can't conclusively prove that this key does anything to the dashboard query, but the migration removed it and I'm more comfortable keeping it so I'm not worried about breaking stuff.
At the very least, MySQL does select this key in the query plan when I do a "Reviewers:" query explicitly so it isn't //useless//.
Test Plan: Ran `bin/storage upgrade`, ran dashboard query, the query plan didn't get any worse.
Reviewers: chad
Reviewed By: chad
Maniphest Tasks: T10967
Differential Revision: https://secure.phabricator.com/D17532 | <?php
final class DifferentialReviewer
extends DifferentialDAO {
protected $revisionPHID;
protected $reviewerPHID;
protected $reviewerStatus;
protected $lastActionDiffPHID;
protected $lastCommentDiffPHID;
private $authority = array();
protected function getConfiguration() {
return array(
self::CONFIG_COLUMN_SCHEMA => array(
'reviewerStatus' => 'text64',
'lastActionDiffPHID' => 'phid?',
'lastCommentDiffPHID' => 'phid?',
),
self::CONFIG_KEY_SCHEMA => array(
'key_revision' => array(
'columns' => array('revisionPHID', 'reviewerPHID'),
'unique' => true,
),
'key_reviewer' => array(
'columns' => array('reviewerPHID', 'revisionPHID'),
),
),
) + parent::getConfiguration();
}
public function isUser() {
$user_type = PhabricatorPeopleUserPHIDType::TYPECONST;
return (phid_get_type($this->getReviewerPHID()) == $user_type);
}
public function attachAuthority(PhabricatorUser $user, $has_authority) {
$this->authority[$user->getCacheFragment()] = $has_authority;
return $this;
}
public function hasAuthority(PhabricatorUser $viewer) {
$cache_fragment = $viewer->getCacheFragment();
return $this->assertAttachedKey($this->authority, $cache_fragment);
}
public function isResigned() {
$status_resigned = DifferentialReviewerStatus::STATUS_RESIGNED;
return ($this->getReviewerStatus() == $status_resigned);
}
}
| <?php
final class DifferentialReviewer
extends DifferentialDAO {
protected $revisionPHID;
protected $reviewerPHID;
protected $reviewerStatus;
protected $lastActionDiffPHID;
protected $lastCommentDiffPHID;
private $authority = array();
protected function getConfiguration() {
return array(
self::CONFIG_COLUMN_SCHEMA => array(
'reviewerStatus' => 'text64',
'lastActionDiffPHID' => 'phid?',
'lastCommentDiffPHID' => 'phid?',
),
self::CONFIG_KEY_SCHEMA => array(
'key_revision' => array(
'columns' => array('revisionPHID', 'reviewerPHID'),
'unique' => true,
),
),
) + parent::getConfiguration();
}
public function isUser() {
$user_type = PhabricatorPeopleUserPHIDType::TYPECONST;
return (phid_get_type($this->getReviewerPHID()) == $user_type);
}
public function attachAuthority(PhabricatorUser $user, $has_authority) {
$this->authority[$user->getCacheFragment()] = $has_authority;
return $this;
}
public function hasAuthority(PhabricatorUser $viewer) {
$cache_fragment = $viewer->getCacheFragment();
return $this->assertAttachedKey($this->authority, $cache_fragment);
}
public function isResigned() {
$status_resigned = DifferentialReviewerStatus::STATUS_RESIGNED;
return ($this->getReviewerStatus() == $status_resigned);
}
}
|
Include tiles in menu response | /*global FormplayerFrontend, Util */
FormplayerFrontend.module("Menus.Collections", function (Collections, FormplayerFrontend, Backbone, Marionette, $) {
Collections.MenuSelect = Backbone.Collection.extend({
model: FormplayerFrontend.Menus.Models.MenuSelect,
commonProperties: [
'title',
'type',
'clearSession',
'notification',
'breadcrumbs',
'appVersion',
'appId',
'persistentCaseTile',
'tiles',
],
entityProperties: [
'action',
'styles',
'headers',
'currentPage',
'pageCount',
'titles',
'numEntitiesPerRow',
'maxWidth',
'maxHeight',
],
parse: function (response, request) {
_.extend(this, _.pick(response, this.commonProperties));
if (response.commands) {
return response.commands;
} else if (response.entities) {
_.extend(this, _.pick(response, this.entityProperties));
return response.entities;
} else if (response.type === "query") {
return response.displays;
} else if (response.details) {
return response.details;
} else if (response.tree){
// form entry time, doggy
FormplayerFrontend.trigger('startForm', response, this.app_id);
}
},
sync: function (method, model, options) {
Util.setCrossDomainAjaxOptions(options);
return Backbone.Collection.prototype.sync.call(this, 'create', model, options);
},
});
});
| /*global FormplayerFrontend, Util */
FormplayerFrontend.module("Menus.Collections", function (Collections, FormplayerFrontend, Backbone, Marionette, $) {
Collections.MenuSelect = Backbone.Collection.extend({
model: FormplayerFrontend.Menus.Models.MenuSelect,
commonProperties: [
'title',
'type',
'clearSession',
'notification',
'breadcrumbs',
'appVersion',
'appId',
'persistentCaseTile',
],
entityProperties: [
'action',
'styles',
'headers',
'currentPage',
'pageCount',
'titles',
'numEntitiesPerRow',
'maxWidth',
'maxHeight',
],
parse: function (response, request) {
_.extend(this, _.pick(response, this.commonProperties));
if (response.commands) {
return response.commands;
} else if (response.entities) {
_.extend(this, _.pick(response, this.entityProperties));
return response.entities;
} else if (response.type === "query") {
return response.displays;
} else if (response.details) {
return response.details;
} else if (response.tree){
// form entry time, doggy
FormplayerFrontend.trigger('startForm', response, this.app_id);
}
},
sync: function (method, model, options) {
Util.setCrossDomainAjaxOptions(options);
return Backbone.Collection.prototype.sync.call(this, 'create', model, options);
},
});
});
|
Use Pager.Item instead of PageItem. | import React from 'react';
import PropTypes from 'prop-types';
import {Pager} from 'react-bootstrap';
const Paging = ({pending, paging, onSelect}) => {
let newer, older;
if (!paging) {
return null;
}
if (paging.before !== undefined) {
newer = (
<Pager.Item previous disabled={pending}
eventKey={paging.before}>
← Newer
</Pager.Item>
);
}
if (paging.after !== undefined) {
older = (
<Pager.Item next disabled={pending}
eventKey={paging.after}>
Older →
</Pager.Item>
);
}
if (!newer && !older) {
return null;
}
return (
<Pager onSelect={onSelect}>
{newer}
{older}
</Pager>
);
};
Paging.propTypes = {
pending: PropTypes.bool,
paging: PropTypes.shape({
before: PropTypes.number,
after: PropTypes.number
}),
onSelect: PropTypes.func
};
Paging.defaultProps = {
pending: false,
paging: {}
};
export default Paging; | import React from 'react';
import PropTypes from 'prop-types';
import {Pager} from 'react-bootstrap';
const Paging = ({pending, paging, onSelect}) => {
let newer, older;
if (!paging) {
return null;
}
if (paging.before !== undefined) {
newer = (
<PageItem previous disabled={pending}
eventKey={paging.before}>
← Newer
</PageItem>
);
}
if (paging.after !== undefined) {
older = (
<Pager.Item next disabled={pending}
eventKey={paging.after}>
Older →
</Pager.Item>
);
}
if (!newer && !older) {
return null;
}
return (
<Pager onSelect={onSelect}>
{newer}
{older}
</Pager>
);
};
Paging.propTypes = {
pending: PropTypes.bool,
paging: PropTypes.shape({
before: PropTypes.number,
after: PropTypes.number
}),
onSelect: PropTypes.func
};
Paging.defaultProps = {
pending: false,
paging: {}
};
export default Paging; |
Fix syntax for python 2.6 | from . import TestCase
from llvmlite import binding as llvm
from llvmlite.binding import dylib
import platform
from ctypes.util import find_library
import unittest
@unittest.skipUnless(platform.system() in ["Linux", "Darwin"], "Unsupport test for current OS")
class TestDylib(TestCase):
def setUp(self):
llvm.initialize()
llvm.initialize_native_target()
llvm.initialize_native_asmprinter()
self.system = platform.system()
def test_bad_library(self):
with self.assertRaises(Exception) as context:
dylib.load_library_permanently("zzzasdkf;jasd;l")
if self.system == "Linux":
self.assertTrue('zzzasdkf;jasd;l: cannot open shared object file: No such file or directory'
in str(context.exception))
elif self.system == "Darwin":
self.assertTrue('dlopen(zzzasdkf;jasd;l, 9): image not found'
in str(context.exception))
def test_libm(self):
try:
if self.system == "Linux":
libm = find_library("m")
elif self.system == "Darwin":
libm = find_library("libm")
dylib.load_library_permanently(libm)
except Exception:
self.fail("Valid call to link library should not fail.")
| from . import TestCase
from llvmlite import binding as llvm
from llvmlite.binding import dylib
import platform
from ctypes.util import find_library
import unittest
@unittest.skipUnless(platform.system() in {"Linux", "Darwin"}, "Unsupport test for current OS")
class TestDylib(TestCase):
def setUp(self):
llvm.initialize()
llvm.initialize_native_target()
llvm.initialize_native_asmprinter()
self.system = platform.system()
def test_bad_library(self):
with self.assertRaises(Exception) as context:
dylib.load_library_permanently("zzzasdkf;jasd;l")
if self.system == "Linux":
self.assertTrue('zzzasdkf;jasd;l: cannot open shared object file: No such file or directory'
in str(context.exception))
elif self.system == "Darwin":
self.assertTrue('dlopen(zzzasdkf;jasd;l, 9): image not found'
in str(context.exception))
def test_libm(self):
try:
if self.system == "Linux":
libm = find_library("m")
elif self.system == "Darwin":
libm = find_library("libm")
dylib.load_library_permanently(libm)
except Exception:
self.fail("Valid call to link library should not fail.")
|
Set up console script for main | import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = "{{cookiecutter.repo_name}}",
version = "{{cookiecutter.version}}",
author = "{{cookiecutter.full_name}}",
author_email = "{{cookiecutter.email}}",
description = "{{cookiecutter.short_description}}",
license = "MIT",
keywords=(
"Python, cookiecutter, kivy, buildozer, pytest, projects, project "
"templates, example, documentation, tutorial, setup.py, package, "
"android, touch, mobile, NUI"
),
url = "https://github.com/{{cookiecutter.github_username}}/{{cookiecutter.repo_name}}",
packages=find_packages(),
long_description=read('README.rst'),
install_requires = ['kivy>=1.8.0'],
package_data={
'{{cookiecutter.repo_name}}': ['*.kv*']
},
entry_points={
'console_scripts': [
'{{cookiecutter.repo_name}}={{cookiecutter.repo_name}}.main:main'
]
},
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Environment :: X11 Applications',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Topic :: Artistic Software',
'Topic :: Multimedia :: Graphics :: Presentation',
'Topic :: Software Development :: User Interfaces',
],
)
| import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = "{{cookiecutter.repo_name}}",
version = "{{cookiecutter.version}}",
author = "{{cookiecutter.full_name}}",
author_email = "{{cookiecutter.email}}",
description = "{{cookiecutter.short_description}}",
license = "MIT",
keywords=(
"Python, cookiecutter, kivy, buildozer, pytest, projects, project "
"templates, example, documentation, tutorial, setup.py, package, "
"android, touch, mobile, NUI"
),
url = "https://github.com/{{cookiecutter.github_username}}/{{cookiecutter.repo_name}}",
packages=find_packages(),
long_description=read('README.rst'),
install_requires = ['kivy>=1.8.0'],
package_data={
'{{cookiecutter.repo_name}}': ['*.kv*']
},
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Environment :: X11 Applications',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Topic :: Artistic Software',
'Topic :: Multimedia :: Graphics :: Presentation',
'Topic :: Software Development :: User Interfaces',
],
)
|
Update registrar to dynamically fetch registered `_User` subclass | <?php
namespace LaraParse\Auth;
use Illuminate\Contracts\Auth\Registrar as RegistrarContract;
use Illuminate\Contracts\Validation\Factory as ValidationFactory;
use LaraParse\Subclasses\User;
use Parse\ParseObject;
class Registrar implements RegistrarContract
{
/**
* @var \Illuminate\Contracts\Validation\Factory
*/
private $validator;
/**
* @param \Illuminate\Contracts\Validation\Factory $validator
*/
public function __construct(ValidationFactory $validator)
{
$this->validator = $validator;
}
/**
* Get a validator for an incoming registration request.
*
* @param array $data
*
* @return \Illuminate\Contracts\Validation\Validator
*/
public function validator(array $data)
{
$messages = [
'parse_user_unique' => 'Testing message.',
];
$rules = [
'email' => ['required', 'email', 'max:255', 'parse_user_unique'],
'password' => ['required', 'confirmed', 'min:6'],
];
return $this->validator->make($data, $rules, $messages);
}
/**
* Create a new user instance after a valid registration.
*
* @param array $data
*
* @return User
*/
public function create(array $data)
{
$userSubclass = ParseObject::getRegisteredSubclass('_User');
$user = new $userSubclass;
$user->username = $data['email'];
$user->password = $data['password'];
$user->signUp();
return $user;
}
}
| <?php
namespace LaraParse\Auth;
use Illuminate\Contracts\Auth\Registrar as RegistrarContract;
use Illuminate\Contracts\Validation\Factory as ValidationFactory;
use Illuminate\Support\MessageBag;
use LaraParse\Subclasses\User;
use Parse\ParseException;
class Registrar implements RegistrarContract
{
/**
* @var \Illuminate\Contracts\Validation\Factory
*/
private $validator;
/**
* @param \Illuminate\Contracts\Validation\Factory $validator
*/
public function __construct(ValidationFactory $validator)
{
$this->validator = $validator;
}
/**
* Get a validator for an incoming registration request.
*
* @param array $data
*
* @return \Illuminate\Contracts\Validation\Validator
*/
public function validator(array $data)
{
$messages = [
'parse_user_unique' => 'Testing message.',
];
$rules = [
'email' => ['required', 'email', 'max:255', 'parse_user_unique'],
'password' => ['required', 'confirmed', 'min:6'],
];
return $this->validator->make($data, $rules, $messages);
}
/**
* Create a new user instance after a valid registration.
*
* @param array $data
*
* @return User
*/
public function create(array $data)
{
$user = new User;
$user->username = $data['email'];
$user->password = $data['password'];
$user->signUp();
return $user;
}
}
|
Drop threads down to limit memory consumption | from __future__ import absolute_import, division, print_function, unicode_literals
import sys
import requests
from gratipay.utils import markdown
from gratipay.utils.threaded_map import threaded_map
from threading import Lock
log_lock = Lock()
def log(*a, **kw):
with log_lock:
print(*a, file=sys.stderr, **kw)
def http_fetch(package_name):
r = requests.get('https://registry.npmjs.com/' + package_name)
if r.status_code != 200:
log(r.status_code, 'for', package_name)
return None
return r.json()
def Syncer(db):
def sync(dirty, fetch=http_fetch):
"""Update all info for one package.
"""
log(dirty.name)
full = fetch(dirty.name)
if not full:
return # try again later
assert full['name'] == dirty.name
db.run('''
UPDATE packages
SET readme=%s
, readme_raw=%s
, readme_type=%s
WHERE package_manager=%s
AND name=%s
''', ( markdown.marky(full['readme'])
, full['readme']
, 'x-markdown/npm'
, dirty.package_manager
, dirty.name
))
return sync
def sync_all(db):
dirty = db.all('SELECT package_manager, name FROM packages WHERE readme_raw IS NULL '
'ORDER BY package_manager DESC, name DESC')
threaded_map(Syncer(db), dirty, 4)
| from __future__ import absolute_import, division, print_function, unicode_literals
import sys
import requests
from gratipay.utils import markdown
from gratipay.utils.threaded_map import threaded_map
from threading import Lock
log_lock = Lock()
def log(*a, **kw):
with log_lock:
print(*a, file=sys.stderr, **kw)
def http_fetch(package_name):
r = requests.get('https://registry.npmjs.com/' + package_name)
if r.status_code != 200:
log(r.status_code, 'for', package_name)
return None
return r.json()
def Syncer(db):
def sync(dirty, fetch=http_fetch):
"""Update all info for one package.
"""
log(dirty.name)
full = fetch(dirty.name)
if not full:
return # try again later
assert full['name'] == dirty.name
db.run('''
UPDATE packages
SET readme=%s
, readme_raw=%s
, readme_type=%s
WHERE package_manager=%s
AND name=%s
''', ( markdown.marky(full['readme'])
, full['readme']
, 'x-markdown/npm'
, dirty.package_manager
, dirty.name
))
return sync
def sync_all(db):
dirty = db.all('SELECT package_manager, name FROM packages WHERE readme_raw IS NULL '
'ORDER BY package_manager DESC, name DESC')
threaded_map(Syncer(db), dirty, 10)
|
Move export to a background process | from itertools import chain
from corehq.apps.reports.datatables import DataTablesColumn, DataTablesHeader
from corehq.apps.reports.generic import GenericTabularReport
from corehq.apps.reports.standard import CustomProjectReport, DatespanMixin
class MultiTabularReport(DatespanMixin, CustomProjectReport, GenericTabularReport):
report_template_path = 'inddex/multi_report.html'
exportable = True
exportable_all = True
export_only = False
@property
def data_providers(self):
# data providers should supply a title, slug, headers, and rows
return []
@property
def report_context(self):
context = {
'name': self.name,
'export_only': self.export_only
}
if not self.needs_filters:
context['data_providers'] = [{
'title': data_provider.title,
'slug': data_provider.slug,
'headers': DataTablesHeader(
*(DataTablesColumn(header) for header in data_provider.headers),
),
'rows': data_provider.rows,
} for data_provider in self.data_providers]
return context
@property
def export_table(self):
return [
[dp.slug, chain([dp.headers], dp.rows)]
for dp in self.data_providers
]
| from corehq.apps.reports.datatables import DataTablesColumn, DataTablesHeader
from corehq.apps.reports.generic import GenericTabularReport
from corehq.apps.reports.standard import CustomProjectReport, DatespanMixin
class MultiTabularReport(DatespanMixin, CustomProjectReport, GenericTabularReport):
report_template_path = 'inddex/multi_report.html'
exportable = True
export_only = False
@property
def data_providers(self):
# data providers should supply a title, slug, headers, and rows
return []
@property
def report_context(self):
context = {
'name': self.name,
'export_only': self.export_only
}
if not self.needs_filters:
context['data_providers'] = [{
'title': data_provider.title,
'slug': data_provider.slug,
'headers': DataTablesHeader(
*(DataTablesColumn(header) for header in data_provider.headers),
),
'rows': data_provider.rows,
} for data_provider in self.data_providers]
return context
@property
def export_table(self):
return [
[dp.slug, [dp.headers] + dp.rows]
for dp in self.data_providers
]
|
Add custom success and faluire messages | /*
* grunt-perl-tidy
* https://github.com/rabrooks/grunt-perl-tidy
*
* Copyright (c) 2014 Aaron Brooks
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Please see the Grunt documentation for more information regarding task
// creation: http://gruntjs.com/creating-tasks
grunt.registerMultiTask('perl_tidy', 'Run perl tidy on perl files.', function() {
// Merge task-specific and/or target-specific options with these defaults.
var options = this.options({
punctuation: '.',
separator: ', '
});
// Iterate over all specified file groups.
this.files.forEach(function(f) {
// Concat specified files.
var src = f.src.filter(function(filepath) {
// Warn on and remove invalid source files (if nonull was set).
if (!grunt.file.exists(filepath)) {
grunt.log.warn('Source file "' + filepath + '" not found.');
return false;
} else {
return true;
}
}).map(function(filepath) {
// Read file source.
return grunt.file.read(filepath);
}).join(grunt.util.normalizelf(options.separator));
// Handle options.
src += options.punctuation;
// Write the destination file.
grunt.file.write(f.dest, src);
// Print a success message.
grunt.log.writeln('File "' + f.dest + '" is now all tidy.');
});
});
};
| /*
* grunt-perl-tidy
* https://github.com/rabrooks/grunt-perl-tidy
*
* Copyright (c) 2014 Aaron Brooks
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Please see the Grunt documentation for more information regarding task
// creation: http://gruntjs.com/creating-tasks
grunt.registerMultiTask('perl_tidy', 'Run perl tidy on perl files.', function() {
// Merge task-specific and/or target-specific options with these defaults.
var options = this.options({
punctuation: '.',
separator: ', '
});
// Iterate over all specified file groups.
this.files.forEach(function(f) {
// Concat specified files.
var src = f.src.filter(function(filepath) {
// Warn on and remove invalid source files (if nonull was set).
if (!grunt.file.exists(filepath)) {
grunt.log.warn('Source file "' + filepath + '" not found.');
return false;
} else {
return true;
}
}).map(function(filepath) {
// Read file source.
return grunt.file.read(filepath);
}).join(grunt.util.normalizelf(options.separator));
// Handle options.
src += options.punctuation;
// Write the destination file.
grunt.file.write(f.dest, src);
// Print a success message.
grunt.log.writeln('File "' + f.dest + '" created.');
});
});
};
|
Add is_active() method to the Baro class | from datetime import datetime
import utils
class Baro:
"""This class contains info about the Void Trader and is initialized with
data in JSON format
"""
def __init__(self, data):
self.config = data['Config']
self.start = datetime.fromtimestamp(data['Activation']['sec'])
self.end = datetime.fromtimestamp(data['Expiry']['sec'])
self.location = data['Node']
self.manifest = data['Manifest']
def __str__(self):
"""Returns a string with all the information about Baro's offers
"""
baroItemString = ""
if datetime.now() < self.start:
return "None"
else:
for item in self.manifest:
baroItemString += ('== '+ str(item["ItemType"]) +' ==\n'
'- price: '+ str(item["PrimePrice"]) +' ducats + '+ str(item["RegularPrice"]) +'cr -\n\n' )
return baroItemString
def is_active(self):
"""Returns True if the Void Trader is currently active, False otherwise
"""
return (self.start < datetime.now() and self.end > datetime.now())
def get_end_string(self):
"""Returns a string containing Baro's departure time
"""
return timedelta_to_string(self.end - datetime.now())
def get_start_string(self):
"""Returns a string containing Baro's arrival time
"""
return timedelta_to_string(self.start - datetime.now())
| from datetime import datetime
import utils
class Baro:
"""This class contains info about the Void Trader and is initialized with
data in JSON format
"""
def __init__(self, data):
self.config = data['Config']
self.start = datetime.fromtimestamp(data['Activation']['sec'])
self.end = datetime.fromtimestamp(data['Expiry']['sec'])
self.location = data['Node']
self.manifest = data['Manifest']
def __str__(self):
"""Returns a string with all the information about Baro's offers
"""
baroItemString = ""
if datetime.now() < self.start:
return "None"
else:
for item in self.manifest:
baroItemString += ('== '+ str(item["ItemType"]) +' ==\n'
'- price: '+ str(item["PrimePrice"]) +' ducats + '+ str(item["RegularPrice"]) +'cr -\n\n' )
return baroItemString
def get_end_string(self):
"""Returns a string containing Baro's departure time
"""
return timedelta_to_string(self.end - datetime.now())
def get_start_string(self):
"""Returns a string containing Baro's arrival time
"""
return timedelta_to_string(self.start - datetime.now())
|
Check if the remote_repo was updated or not and log error | import json
from django.core.management.base import BaseCommand
from readthedocs.oauth.models import RemoteRepository
class Command(BaseCommand):
help = "Load Project and RemoteRepository Relationship from JSON file"
def add_arguments(self, parser):
# File path of the json file containing relationship data
parser.add_argument(
'--file',
required=True,
nargs=1,
type=str,
help='File path of the json file containing relationship data.',
)
def handle(self, *args, **options):
file = options.get('file')[0]
try:
# Load data from the json file
with open(file, 'r') as f:
data = json.load(f)
except Exception as e:
self.stdout.write(
self.style.ERROR(
f'Exception occurred while trying to load the file "{file}". '
f'Exception: {e}.'
)
)
return
for item in data:
try:
update_count = RemoteRepository.objects.filter(
remote_id=item['remote_id']
).update(project_id=item['project_id'])
if update_count < 1:
self.stdout.write(
self.style.ERROR(
f"Could not update {item['slug']}'s "
f"relationship with {item['html_url']}, "
f"remote_id {item['remote_id']}, "
f"username: {item['username']}."
)
)
except Exception as e:
self.stdout.write(
self.style.ERROR(
f"Exception occurred while trying to update {item['slug']}'s "
f"relationship with {item['html_url']}, "
f"username: {item['username']}, Exception: {e}."
)
)
| import json
from django.core.management.base import BaseCommand
from readthedocs.oauth.models import RemoteRepository
class Command(BaseCommand):
help = "Load Project and RemoteRepository Relationship from JSON file"
def add_arguments(self, parser):
# File path of the json file containing relationship data
parser.add_argument(
'--file',
required=True,
nargs=1,
type=str,
help='File path of the json file containing relationship data.',
)
def handle(self, *args, **options):
file = options.get('file')[0]
try:
# Load data from the json file
with open(file, 'r') as f:
data = json.load(f)
except Exception as e:
self.stdout.write(
self.style.ERROR(
f'Exception occurred while trying to load the file "{file}". '
f'Exception: {e}.'
)
)
return
for item in data:
try:
RemoteRepository.objects.filter(
remote_id=item['remote_id']
).update(project_id=item['project_id'])
except Exception as e:
self.stdout.write(
self.style.ERROR(
f"Exception occurred while trying to update {item['slug']}'s "
f"relationship with {item['html_url']}, "
f"username: {item['username']}, Exception: {e}."
)
)
|
Use a name param instead of a boolean value | 'use strict';
var Node = require('../node');
var debug = require('../../util/debug')('analysis:line-to-single-point');
var TYPE = 'line-to-single-point';
var PARAMS = {
source: Node.PARAM.NODE(Node.GEOMETRY.POINT),
destination_longitude: Node.PARAM.NUMBER(),
destination_latitude: Node.PARAM.NUMBER(),
};
var LineToSinglePoint = Node.create(TYPE, PARAMS);
module.exports = LineToSinglePoint;
module.exports.TYPE = TYPE;
module.exports.PARAMS = PARAMS;
LineToSinglePoint.prototype.sql = function() {
var skipTheGeoms = true;
var sql = lineToSinglePointQueryTemplate({
source: this.source.getQuery(),
columns: this.source.getColumns(skipTheGeoms).join(', '),
destination_longitude: this.destination_longitude,
destination_latitude: this.destination_latitude
});
debug(sql);
return sql;
};
var lineToSinglePointQueryTemplate = Node.template([
'SELECT',
' ST_MakeLine(',
' the_geom,',
' ST_SetSRID(',
' ST_MakePoint(',
' {{=it.destination_longitude}},',
' {{=it.destination_latitude}}',
' ),',
' 4326',
' )',
' ) AS the_geom,',
' {{=it.columns}}',
'FROM ({{=it.source}}) _cdb_analysis_source_points',
].join('\n'));
| 'use strict';
var Node = require('../node');
var debug = require('../../util/debug')('analysis:line-to-single-point');
var TYPE = 'line-to-single-point';
var PARAMS = {
source: Node.PARAM.NODE(Node.GEOMETRY.POINT),
destination_longitude: Node.PARAM.NUMBER(),
destination_latitude: Node.PARAM.NUMBER(),
};
var LineToSinglePoint = Node.create(TYPE, PARAMS);
module.exports = LineToSinglePoint;
module.exports.TYPE = TYPE;
module.exports.PARAMS = PARAMS;
LineToSinglePoint.prototype.sql = function() {
var sql = lineToSinglePointQueryTemplate({
source: this.source.getQuery(),
columns: this.source.getColumns(true).join(', '),
destination_longitude: this.destination_longitude,
destination_latitude: this.destination_latitude
});
debug(sql);
return sql;
};
var lineToSinglePointQueryTemplate = Node.template([
'SELECT',
' ST_MakeLine(',
' the_geom,',
' ST_SetSRID(',
' ST_MakePoint(',
' {{=it.destination_longitude}},',
' {{=it.destination_latitude}}',
' ),',
' 4326',
' )',
' ) AS the_geom,',
' {{=it.columns}}',
'FROM ({{=it.source}}) _cdb_analysis_source_points',
].join('\n'));
|
Set a unique id to each Trackable Brand | package cgeo.geocaching.connector.trackable;
import cgeo.geocaching.CgeoApplication;
import cgeo.geocaching.R;
import org.eclipse.jdt.annotation.NonNull;
public enum TrackableBrand {
TRAVELBUG(1, R.drawable.trackable_travelbug, R.string.trackable_travelbug),
GEOKRETY(2, R.drawable.trackable_geokrety, R.string.trackable_geokrety),
SWAGGIE(3, R.drawable.trackable_swaggie, R.string.trackable_swaggie),
UNKNOWN(0, R.drawable.trackable_all, R.string.trackable_unknown); // Trackable not initialized yet
private final int id;
private final int stringId;
private final int markerId;
TrackableBrand(final int id, final int markerId, final int stringId) {
this.id = id;
this.markerId = markerId;
this.stringId = stringId;
}
public int getId() {
return id;
}
public int getIconResource() {
return markerId;
}
public String getLabel() {
return CgeoApplication.getInstance().getString(stringId);
}
@NonNull
public static TrackableBrand getById(final int id) {
for (final TrackableBrand brand : values()) {
if (brand.id == id) {
return brand;
}
}
return UNKNOWN;
}
} | package cgeo.geocaching.connector.trackable;
import cgeo.geocaching.CgeoApplication;
import cgeo.geocaching.R;
import org.eclipse.jdt.annotation.NonNull;
public enum TrackableBrand {
TRAVELBUG(1, R.drawable.trackable_travelbug, R.string.trackable_travelbug),
GEOKRETY(2, R.drawable.trackable_geokrety, R.string.trackable_geokrety),
SWAGGIE(2, R.drawable.trackable_swaggie, R.string.trackable_swaggie),
UNKNOWN(0, R.drawable.trackable_all, R.string.trackable_unknown); // Trackable not initialized yet
private final int id;
private final int stringId;
private final int markerId;
TrackableBrand(final int id, final int markerId, final int stringId) {
this.id = id;
this.markerId = markerId;
this.stringId = stringId;
}
public int getId() {
return id;
}
public int getIconResource() {
return markerId;
}
public String getLabel() {
return CgeoApplication.getInstance().getString(stringId);
}
@NonNull
public static TrackableBrand getById(final int id) {
for (final TrackableBrand brand : values()) {
if (brand.id == id) {
return brand;
}
}
return UNKNOWN;
}
} |
Use encodeURIComponent() on selected text variable; move result url to variable. | var { Hotkey } = require("sdk/hotkeys");
var { ActionButton } = require("sdk/ui/button/action");
var Request = require("sdk/request").Request;
var tabs = require("sdk/tabs");
var selection = require("sdk/selection");
var notifications = require("sdk/notifications");
var notifyImg = "./icon-32-white.png";
var apiKey = "";
var selectedText = '';
function textSelection(event){
if (selection.isContiguous) {
selectedText = selection.text;
}
}
selection.on('select', textSelection);
var button = ActionButton({
id: "hot-translator",
label: "Hot Translator",
icon: {
"16": "./icon-16.png",
"32": "./icon-32.png",
"64": "./icon-64.png"
},
onClick: function(state) {
tabs.open("https://translate.yandex.ru/?text=" + selectedText);
}
});
var HotKeyPress = Hotkey({
combo: "alt-q",
onPress: function() {
var canSelectedText = encodeURIComponent(selectedText);
var resultUrl = "https://translate.yandex.net/api/v1.5/tr.json/translate?key=" + apiKey + "&lang=ru&text=" + canSelectedText;
Request({
url: resultUrl,
onComplete: function (response) {
var translated = response.json.text[0];
notifications.notify({
text: translated,
iconURL: notifyImg
});
}
}).get();
}
});
| var { Hotkey } = require("sdk/hotkeys");
var { ActionButton } = require("sdk/ui/button/action");
var Request = require("sdk/request").Request;
var tabs = require("sdk/tabs");
var selection = require("sdk/selection");
var notifications = require("sdk/notifications");
var notifyImg = "./icon-32-white.png";
var apiKey = "";
var selectedText = '';
function textSelection(event){
if (selection.isContiguous) {
selectedText = selection.text;
}
}
selection.on('select', textSelection);
var button = ActionButton({
id: "hot-translator",
label: "Hot Translator",
icon: {
"16": "./icon-16.png",
"32": "./icon-32.png",
"64": "./icon-64.png"
},
onClick: function(state) {
tabs.open("https://translate.yandex.ru/?text=" + selectedText);
}
});
var HotKeyPress = Hotkey({
combo: "alt-q",
onPress: function() {
Request({
url: "https://translate.yandex.net/api/v1.5/tr.json/translate?key=" + apiKey + "&lang=ru&text=" + selectedText,
onComplete: function (response) {
var translated = response.json.text[0];
notifications.notify({
text: translated,
iconURL: notifyImg
});
}
}).get();
}
});
|
Address review comment: More standard assertions. | # Copyright ClusterHQ Inc. See LICENSE file for details.
"""
Test validation of keys generated by flocker-ca.
"""
from twisted.trial.unittest import SynchronousTestCase
from .. import amp_server_context_factory, rest_api_context_factory
from ..testtools import get_credential_sets
class ClientValidationContextFactoryTests(SynchronousTestCase):
"""
Tests for implementation details of the context factory used by the
control service.
"""
def test_amp_new_context_each_time(self):
"""
Each call to the AMP server's context factory ``getContext`` returns a
new instance, to prevent issues with global shared state.
"""
ca_set, _ = get_credential_sets()
context_factory = amp_server_context_factory(
ca_set.root.credential.certificate, ca_set.control)
self.assertIsNot(context_factory.getContext(),
context_factory.getContext())
def test_rest_new_context_each_time(self):
"""
Each call to the REST API server's context factory ``getContext``
returns a new instance, to prevent issues with global shared
state.
"""
ca_set, _ = get_credential_sets()
context_factory = rest_api_context_factory(
ca_set.root.credential.certificate, ca_set.control)
self.assertIsNot(context_factory.getContext(),
context_factory.getContext())
| # Copyright ClusterHQ Inc. See LICENSE file for details.
"""
Test validation of keys generated by flocker-ca.
"""
from twisted.trial.unittest import SynchronousTestCase
from .. import amp_server_context_factory, rest_api_context_factory
from ..testtools import get_credential_sets
class ClientValidationContextFactoryTests(SynchronousTestCase):
"""
Tests for implementation details of the context factory used by the
control service.
"""
def test_amp_new_context_each_time(self):
"""
Each call to the AMP server's context factory ``getContext`` returns a
new instance, to prevent issues with global shared state.
"""
ca_set, _ = get_credential_sets()
context_factory = amp_server_context_factory(
ca_set.root.credential.certificate, ca_set.control)
self.assertNotIdentical(context_factory.getContext(),
context_factory.getContext())
def test_rest_new_context_each_time(self):
"""
Each call to the REST API server's context factory ``getContext``
returns a new instance, to prevent issues with global shared
state.
"""
ca_set, _ = get_credential_sets()
context_factory = rest_api_context_factory(
ca_set.root.credential.certificate, ca_set.control)
self.assertNotIdentical(context_factory.getContext(),
context_factory.getContext())
|
Check is object to avoid error on search express entities | <?php
namespace Concrete\Core\Express\Search\Column;
use Concrete\Core\Entity\Express\Association;
use Concrete\Core\Search\Column\Column;
use Concrete\Core\Search\Result\Result;
class AssociationColumn extends Column
{
protected $association = false;
protected $associationID;
public function __construct(Association $association)
{
$this->association = $association;
$this->associationID = $association->getId();
}
public function getColumnKey()
{
if (is_object($this->association)) {
return 'association_' . $this->association->getId();
}
}
public function getColumnName()
{
if (is_object($this->association)) {
return $this->association->getTargetEntity()->getName();
}
}
public function getAssociation()
{
return $this->association;
}
public function getColumnValue($obj)
{
if (is_object($this->association)) {
$entryAssociation = $obj->getEntryAssociation($this->association);
if ($entryAssociation) {
$entries = [];
foreach($entryAssociation->getSelectedEntries() as $entry) {
$entries[] = $entry->getLabel();
}
return implode('<br/>', $entries);
}
}
}
public function __sleep()
{
return ['associationID'];
}
/**
* Initialize the instance once it has been deserialized.
*/
public function __wakeup()
{
$em = \Database::connection()->getEntityManager();
$this->association = $em->find('Concrete\Core\Entity\Express\Association', $this->associationID);
}
}
| <?php
namespace Concrete\Core\Express\Search\Column;
use Concrete\Core\Entity\Express\Association;
use Concrete\Core\Search\Column\Column;
use Concrete\Core\Search\Result\Result;
class AssociationColumn extends Column
{
protected $association = false;
protected $associationID;
public function __construct(Association $association)
{
$this->association = $association;
$this->associationID = $association->getId();
}
public function getColumnKey()
{
return 'association_' . $this->association->getId();
}
public function getColumnName()
{
return $this->association->getTargetEntity()->getName();
}
public function getAssociation()
{
return $this->association;
}
public function getColumnValue($obj)
{
if (is_object($this->association)) {
$entryAssociation = $obj->getEntryAssociation($this->association);
if ($entryAssociation) {
$entries = [];
foreach($entryAssociation->getSelectedEntries() as $entry) {
$entries[] = $entry->getLabel();
}
return implode('<br/>', $entries);
}
}
}
public function __sleep()
{
return ['associationID'];
}
/**
* Initialize the instance once it has been deserialized.
*/
public function __wakeup()
{
$em = \Database::connection()->getEntityManager();
$this->association = $em->find('Concrete\Core\Entity\Express\Association', $this->associationID);
}
}
|
Fix ancestor next sibling test for DOMIterator. | <?php
namespace ComplexPie;
class DOMIterator implements \Iterator
{
private $root;
private $node;
private $position = 0;
public function __construct(\DOMNode $root)
{
$this->root = $root;
$this->rewind();
}
public function rewind()
{
$this->position = 0;
$this->node = $this->root;
}
public function current()
{
return $this->node;
}
public function key()
{
return $this->position;
}
public function next()
{
$this->position++;
if ($this->node->firstChild)
{
$this->node = $this->node->firstChild;
}
elseif ($this->node->nextSibling)
{
$this->node = $this->node->nextSibling;
}
else
{
$parent = $this->node;
while (($parent = $parent->parentNode) &&
$parent !== $this->root)
{
if ($parent->nextSibling)
{
$this->node = $parent->nextSibling;
return;
}
}
$this->node = null;
}
}
public function valid()
{
return $this->node;
}
}
| <?php
namespace ComplexPie;
class DOMIterator implements \Iterator
{
private $root;
private $node;
private $position = 0;
public function __construct(\DOMNode $root)
{
$this->root = $root;
$this->rewind();
}
public function rewind()
{
$this->position = 0;
$this->node = $this->root;
}
public function current()
{
return $this->node;
}
public function key()
{
return $this->position;
}
public function next()
{
$this->position++;
if ($this->node->firstChild)
{
$this->node = $this->node->firstChild;
}
elseif ($this->node->nextSibling)
{
$this->node = $this->node->nextSibling;
}
elseif ($this->node->parentNode &&
$this->node->parentNode !== $this->root &&
$this->node->parentNode->nextSibling)
{
$this->node = $this->node->parentNode->nextSibling;
}
else
{
$this->node = null;
}
}
public function valid()
{
return $this->node;
}
}
|
Fix the example that seemed to simply not work.. | <?php
namespace spec\MageTest\MagentoExtension\Context\Initializer;
use PHPSpec2\Specification;
class MagentoAwareInitializer implements Specification
{
function described_with($bootstrap, $app, $config, $cache, $factory)
{
$bootstrap->isAMockOf('MageTest\MagentoExtension\Service\Bootstrap');
$app->isAMockOf('Mage_Core_Model_App');
$bootstrap->app()->willReturn($app);
$cache->isAMockOf('MageTest\MagentoExtension\Service\CacheManager');
$config->isAMockOf('MageTest\MagentoExtension\Service\ConfigManager');
$factory->isAMockOf('MageTest\MagentoExtension\Fixture\FixtureFactory');
$this->magentoAwareInitializer->isAnInstanceOf(
'MageTest\MagentoExtension\Context\Initializer\MagentoAwareInitializer',
array($bootstrap, $cache, $config, $factory)
);
}
/**
* @param Prophet $context mock of MageTest\MagentoExtension\Context\MagentoContext
*/
function it_initialises_the_context($context, $app, $config, $cache, $factory)
{
$context->setApp($app)->shouldBeCalled();
$context->setConfigManager($config)->shouldBeCalled();
$context->setCacheManager($cache)->shouldBeCalled();
$context->setFixtureFactory($factory)->shouldBeCalled();
$this->magentoAwareInitializer->initialize($context);
}
} | <?php
namespace spec\MageTest\MagentoExtension\Context\Initializer;
use PHPSpec2\Specification;
class MagentoAwareInitializer implements Specification
{
function described_with($bootstrap, $app, $config, $cache, $factory)
{
$bootstrap->isAMockOf('MageTest\MagentoExtension\Service\Bootstrap');
$app->isAMockOf('Mage_Core_Model_App');
$bootstrap->app()->willReturn($app);
$cache->isAMockOf('MageTest\MagentoExtension\Service\CacheManager');
$config->isAMockOf('MageTest\MagentoExtension\Service\ConfigManager');
$factory->isAMockOf('MageTest\MagentoExtension\Fixture\FixtureFactory');
$this->magentoAwareInitializer->isAnInstanceOf(
'MageTest\MagentoExtension\Context\Initializer\MagentoAwareInitializer',
array($bootstrap, $cache, $config, $factory)
);
}
/**
* @param Prophet $context mock of MageTest\MagentoExtension\Context\MagentoContext
*/
function it_initialises_the_context($context, $app, $config, $cache, $factory)
{
// $context->setApp($app)->shouldBeCalled();
// $context->setConfigManager($config)->shouldBeCalled();
// $context->setCacheManager($cache)->shouldBeCalled();
// $context->setFixtureFactory($factory)->shouldBeCalled();
// $this->magentoAwareInitializer->initialize($context);
}
} |
Use from django.conf import settings | from django.http import HttpResponseBadRequest, HttpResponseForbidden
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
def one_or_zero(arg):
"""Typecast to 1 or 0"""
if arg == '1':
return 1
elif arg == '0':
return 0
raise ValueError("not one or zero")
def private_api(**required_params):
"""
Filter incoming private API requests, and perform parameter validation and
extraction
"""
def outer(some_view):
@csrf_exempt
def inner(request, *args, **kwargs):
if request.method != 'POST':
return HttpResponseBadRequest("Only POST is allowed")
if 'secret' not in request.POST.keys():
return HttpResponseBadRequest(
"You must query this endpoint with a secret.")
if request.POST['secret'] not in settings.STATUS_SECRETS:
message = 'Bad secret {} is not in the allowed list'.format(
request.POST['secret'])
return HttpResponseForbidden(message)
params = {}
for name, typecast in required_params.items():
if name not in request.POST.keys():
return HttpResponseBadRequest(
"Parameter %s is required" % name)
try:
params[name] = typecast(request.POST[name])
except ValueError:
return HttpResponseBadRequest(
"Did not understood %s=%s" % (name, request.POST[name]))
return some_view(request, **params)
return inner
return outer
| from django.http import HttpResponseBadRequest, HttpResponseForbidden
from django.views.decorators.csrf import csrf_exempt
from incubator.settings import STATUS_SECRETS
def one_or_zero(arg):
"""Typecast to 1 or 0"""
if arg == '1':
return 1
elif arg == '0':
return 0
raise ValueError("not one or zero")
def private_api(**required_params):
"""
Filter incoming private API requests, and perform parameter validation and
extraction
"""
def outer(some_view):
@csrf_exempt
def inner(request, *args, **kwargs):
if request.method != 'POST':
return HttpResponseBadRequest("Only POST is allowed")
if 'secret' not in request.POST.keys():
return HttpResponseBadRequest(
"You must query this endpoint with a secret.")
if request.POST['secret'] not in STATUS_SECRETS:
message = 'Bad secret {} is not in the allowed list'.format(
request.POST['secret'])
return HttpResponseForbidden(message)
params = {}
for name, typecast in required_params.items():
if name not in request.POST.keys():
return HttpResponseBadRequest(
"Parameter %s is required" % name)
try:
params[name] = typecast(request.POST[name])
except ValueError:
return HttpResponseBadRequest(
"Did not understood %s=%s" % (name, request.POST[name]))
return some_view(request, **params)
return inner
return outer
|
Enable integration test of citation-matching module | package pl.edu.icm.coansys.citations.coansys;
import java.io.File;
import java.util.List;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Text;
import org.testng.annotations.Test;
import pl.edu.icm.coansys.commons.hadoop.LocalSequenceFileUtils;
import pl.edu.icm.oozierunner.OozieRunner;
/**
* @author madryk
*/
public class CoansysCitationMatchingWorkflowIT {
//------------------------ TESTS --------------------------
@Test
public void testCoansysCitationMatchingWorkflow() throws Exception {
// given
OozieRunner oozieRunner = new OozieRunner();
// execute
File workflowOutputData = oozieRunner.run();
// assert
List<Pair<Text, BytesWritable>> actualOutputDocIdPicOuts = LocalSequenceFileUtils.readSequenceFile(workflowOutputData, Text.class, BytesWritable.class);
List<Pair<Text, BytesWritable>> expectedOutputDocIdPicOuts = LocalSequenceFileUtils.readSequenceFile(new File("src/test/resources/expectedOutput"), Text.class, BytesWritable.class);
PicOutAssert.assertDocIdPicOutsEquals(expectedOutputDocIdPicOuts, actualOutputDocIdPicOuts);
}
}
| package pl.edu.icm.coansys.citations.coansys;
import java.io.File;
import java.util.List;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Text;
import org.testng.annotations.Test;
import pl.edu.icm.coansys.commons.hadoop.LocalSequenceFileUtils;
import pl.edu.icm.oozierunner.OozieRunner;
/**
* @author madryk
*/
public class CoansysCitationMatchingWorkflowIT {
//------------------------ TESTS --------------------------
//@Test
public void testCoansysCitationMatchingWorkflow() throws Exception {
// given
OozieRunner oozieRunner = new OozieRunner();
// execute
File workflowOutputData = oozieRunner.run();
// assert
List<Pair<Text, BytesWritable>> actualOutputDocIdPicOuts = LocalSequenceFileUtils.readSequenceFile(workflowOutputData, Text.class, BytesWritable.class);
List<Pair<Text, BytesWritable>> expectedOutputDocIdPicOuts = LocalSequenceFileUtils.readSequenceFile(new File("src/test/resources/expectedOutput"), Text.class, BytesWritable.class);
PicOutAssert.assertDocIdPicOutsEquals(expectedOutputDocIdPicOuts, actualOutputDocIdPicOuts);
}
}
|
[Capabilities] Fix doc formatting; wasn't expecting <pre> | # coding=utf-8
from enum import Enum, unique
__author__ = 'Sean'
__all__ = ["Capabilities"]
@unique
class Capabilities(Enum):
"""
An enum containing constants to declare what a protocol is capable of
You can use *protocol.get_capabilities()* or *protocol.has_capability(cap)*
to get all of a protocol's capabilities or check whether it has a specific
one respectively.
The current capabilities we have are as follows:
MULTILINE_MESSAGE Messages can contain line-breaks
MULTIPLE_CHANNELS Protocol supports the concept of separate
channels
MULTIPLE_CHANNELS_JOINED Protocol may be in more than one channel at
once
VOICE Protocol supports voice/audio communication
MESSAGE_UNJOINED_CHANNELS Protocol is able to send messages to
channels that it hasn't joined
INDEPENDENT_VOICE_CHANNELS Voice and text channels are separate; can't
send text to a voice channel and vice-versa
"""
#: Messages can contain linebreaks
MULTILINE_MESSAGE = 0
#: Protocol uses channels
#: (rather than a single "channel" for the whole protocol)
MULTIPLE_CHANNELS = 1
#: The protocol can be in more than one channel at a time
MULTIPLE_CHANNELS_JOINED = 2
#: Voice communication support
VOICE = 3
#: Able to send messages to channels the protocol isn't in
MESSAGE_UNJOINED_CHANNELS = 4
#: Voice and text channels are separate;
#: can't send text to voice and vice versa
INDEPENDENT_VOICE_CHANNELS = 5
| # coding=utf-8
from enum import Enum, unique
__author__ = 'Sean'
__all__ = ["Capabilities"]
@unique
class Capabilities(Enum):
"""
An enum containing constants to declare what a protocol is capable of
You can use *protocol.get_capabilities()* or *protocol.has_capability(cap)*
to get all of a protocol's capabilities or check whether it has a specific
one respectively.
The current capabilities we have are as follows:
**MULTILINE_MESSAGE**: Messages can contain line-breaks
**MULTIPLE_CHANNELS**: Protocol supports the concept of separate channels
**MULTIPLE_CHANNELS_JOINED**: Protocol may be in more than one channel at
once
**VOICE**: Protocol support voice/audio communication
**MESSAGE_UNJOINED_CHANNELS**: Protocol is able to send messages to
channels that it hasn't joined
**INDEPENDENT_VOICE_CHANNELS**: Voice and text channels are separate; can't
send text to a voice channel and vice-versa
"""
#: Messages can contain linebreaks
MULTILINE_MESSAGE = 0
#: Protocol uses channels
#: (rather than a single "channel" for the whole protocol)
MULTIPLE_CHANNELS = 1
#: The protocol can be in more than one channel at a time
MULTIPLE_CHANNELS_JOINED = 2
#: Voice communication support
VOICE = 3
#: Able to send messages to channels the protocol isn't in
MESSAGE_UNJOINED_CHANNELS = 4
#: Voice and text channels are separate;
#: can't send text to voice and vice versa
INDEPENDENT_VOICE_CHANNELS = 5
|
Add third, fourth and fifth test to the benchmark. | "use strict";
module.exports = function (grunt) {
grunt.initConfig({
eslint: {
src: [
"Gruntfile.js",
"index.js",
"lib/**/*.js",
"test/**/*.js"
]
},
vows: {
all: {
src: "test/*-test.js",
options: {
reporter: "spec",
error: false
}
}
},
benchmark: {
all: {
src: [
"test/first.js",
"test/second.js",
"test/third.js",
"test/fourth.js",
"test/fifth.js"
]
}
}
});
grunt.loadNpmTasks("grunt-eslint");
grunt.loadNpmTasks("grunt-vows-runner");
grunt.loadNpmTasks("grunt-benchmark");
grunt.registerTask("default", [
"eslint",
"vows",
"benchmark"
]);
};
| "use strict";
module.exports = function (grunt) {
grunt.initConfig({
eslint: {
src: [
"Gruntfile.js",
"index.js",
"lib/**/*.js",
"test/**/*.js"
]
},
vows: {
all: {
src: "test/*-test.js",
options: {
reporter: "spec",
error: false
}
}
},
benchmark: {
all: {
src: ["test/first.js", "test/second.js"]
}
}
});
grunt.loadNpmTasks("grunt-eslint");
grunt.loadNpmTasks("grunt-vows-runner");
grunt.loadNpmTasks("grunt-benchmark");
grunt.registerTask("default", [
"eslint",
"vows",
"benchmark"
]);
};
|
Make it possible to register the locators via the constructor | package org.realityforge.replicant.client;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import static org.realityforge.braincheck.Guards.*;
/**
* A basic EntityLocator implementation that allows explicit per-type registration
*/
public class AggregateEntityLocator
implements EntityLocator
{
private final ArrayList<EntityLocator> _entityLocators = new ArrayList<>();
public AggregateEntityLocator( @Nonnull final EntityLocator... entityLocator )
{
for ( final EntityLocator locator : entityLocator )
{
registerEntityLocator( locator );
}
}
protected final <T> void registerEntityLocator( @Nonnull final EntityLocator entityLocator )
{
apiInvariant( () -> !_entityLocators.contains( entityLocator ),
() -> "Attempting to register entityLocator " + entityLocator + " when already present." );
_entityLocators.add( entityLocator );
}
/**
* {@inheritDoc}
*/
@Nullable
@Override
public final <T> T findByID( @Nonnull final Class<T> type, @Nonnull final Object id )
{
for ( final EntityLocator entityLocator : _entityLocators )
{
final T entity = entityLocator.findByID( type, id );
if ( null != entity )
{
return entity;
}
}
return null;
}
/**
* {@inheritDoc}
*/
@Nonnull
@Override
public <T> List<T> findAll( @Nonnull final Class<T> type )
{
final ArrayList<T> results = new ArrayList<>();
for ( final EntityLocator entityLocator : _entityLocators )
{
results.addAll( entityLocator.findAll( type ) );
}
return results;
}
}
| package org.realityforge.replicant.client;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import static org.realityforge.braincheck.Guards.*;
/**
* A basic EntityLocator implementation that allows explicit per-type registration
*/
public class AggregateEntityLocator
implements EntityLocator
{
private final ArrayList<EntityLocator> _entityLocators = new ArrayList<>();
protected final <T> void registerEntityLocator( @Nonnull final EntityLocator entityLocator )
{
apiInvariant( () -> !_entityLocators.contains( entityLocator ),
() -> "Attempting to register entityLocator " + entityLocator + " when already present." );
_entityLocators.add( entityLocator );
}
/**
* {@inheritDoc}
*/
@Nullable
@Override
public final <T> T findByID( @Nonnull final Class<T> type, @Nonnull final Object id )
{
for ( final EntityLocator entityLocator : _entityLocators )
{
final T entity = entityLocator.findByID( type, id );
if ( null != entity )
{
return entity;
}
}
return null;
}
/**
* {@inheritDoc}
*/
@Nonnull
@Override
public <T> List<T> findAll( @Nonnull final Class<T> type )
{
final ArrayList<T> results = new ArrayList<>();
for ( final EntityLocator entityLocator : _entityLocators )
{
results.addAll( entityLocator.findAll( type ) );
}
return results;
}
}
|
Move tests to the top | package uk.co.benjiweber.expressions;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import static uk.co.benjiweber.expressions.Using.using;
public class UsingTest {
@Test public void should_return_value() {
String result = using(Foo::new, foo -> {
return foo.result();
});
}
@Test public void should_close_closeable() {
Foo closeable = using(Foo::new, foo -> {
return foo;
});
Assert.assertTrue(closeable.closed);
}
@Test public void should_close_closeable_when_exception() {
try {
using(this::getClosable, foo -> {
if (true) throw new NullPointerException();
return "";
});
} catch (NullPointerException e) {
// Expected
}
Assert.assertTrue(foo.closed);
}
Foo foo = new Foo();
Foo getClosable() {
return foo;
}
static class Foo implements AutoCloseable {
public String result() {
return "result";
}
boolean closed = false;
public void close() throws Exception {
closed = true;
}
}
}
| package uk.co.benjiweber.expressions;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import static uk.co.benjiweber.expressions.Using.using;
public class UsingTest {
static class Foo implements AutoCloseable {
public String result() {
return "result";
}
boolean closed = false;
public void close() throws Exception {
closed = true;
}
}
@Test public void should_return_value() {
String result = using(Foo::new, foo -> {
return foo.result();
});
}
@Test public void should_close_closeable() {
Foo closeable = using(Foo::new, foo -> {
return foo;
});
Assert.assertTrue(closeable.closed);
}
Foo foo = new Foo();
Foo getClosable() {
return foo;
}
@Test public void should_close_closeable_when_exception() {
try {
using(this::getClosable, foo -> {
if (true) throw new NullPointerException();
return "";
});
} catch (NullPointerException e) {
// Expected
}
Assert.assertTrue(foo.closed);
}
}
|
Change history limit to 100 when viewing on single page | <?php
namespace Page;
class User
{
public function index()
{
$this->router->redirect('user/profile');
}
public function profile()
{
$this->load->model('Manga');
$this->load->library('Manga', 'MangaLib');
$this->load->library('Image');
$this->load->library('Date');
$cfg = $this->config->loadInfo('Manga');
$mangas = $this->manga->getUserManga(
$this->auth->getUserId(), 0, 36);
$history = $this->manga->getUserHistory(
$this->auth->getUserId(), 0, 31);
$this->load->storeView('User', [
'mangas'=>$mangas,
'history'=>$history,
'mangapath'=>$cfg['path']
]);
$this->load->layout('Fresh', [
'title'=>'My Reading History'
]);
}
public function history()
{
$this->load->model('Manga');
$this->load->library('Manga', 'MangaLib');
$this->load->library('Date');
$history = $this->manga->getUserHistory(
$this->auth->getUserId(), 0, 100);
$this->load->storeView('History', [
'history'=>$history,
'single'=>true
]);
$this->load->layout('Fresh', [
'title'=>'My Reading History'
]);
}
}
?>
| <?php
namespace Page;
class User
{
public function index()
{
$this->router->redirect('user/profile');
}
public function profile()
{
$this->load->model('Manga');
$this->load->library('Manga', 'MangaLib');
$this->load->library('Image');
$this->load->library('Date');
$cfg = $this->config->loadInfo('Manga');
$mangas = $this->manga->getUserManga(
$this->auth->getUserId(), 0, 36);
$history = $this->manga->getUserHistory(
$this->auth->getUserId(), 0, 31);
$this->load->storeView('User', [
'mangas'=>$mangas,
'history'=>$history,
'mangapath'=>$cfg['path']
]);
$this->load->layout('Fresh', [
'title'=>'My Reading History'
]);
}
public function history()
{
$this->load->model('Manga');
$this->load->library('Manga', 'MangaLib');
$this->load->library('Date');
$history = $this->manga->getUserHistory(
$this->auth->getUserId(), 0, 31);
$this->load->storeView('History', [
'history'=>$history,
'single'=>true
]);
$this->load->layout('Fresh', [
'title'=>'My Reading History'
]);
}
}
?>
|
Send proper response time even if non-200 | #!/usr/bin/env python
from maas_common import (status_ok, status_err, metric, get_keystone_client,
get_auth_ref)
from requests import Session
from requests import exceptions as exc
def check(auth_ref):
keystone = get_keystone_client(auth_ref)
tenant_id = keystone.tenant_id
auth_token = keystone.auth_token
registry_endpoint = 'http://127.0.0.1:9191'
api_status = 1
milliseconds = 0
s = Session()
s.headers.update(
{'Content-type': 'application/json',
'x-auth-token': auth_token})
try:
# /images returns a list of public, non-deleted images
r = s.get('%s/images' % registry_endpoint, verify=False, timeout=10)
except (exc.ConnectionError,
exc.HTTPError,
exc.Timeout):
api_status = 0
milliseconds = -1
except Exception as e:
status_err(str(e))
else:
milliseconds = r.elapsed.total_seconds() * 1000
if not r.ok:
api_status = 0
status_ok()
metric('glance_registry_local_status', 'uint32', api_status)
metric('glance_registry_local_response_time', 'uint32', milliseconds)
def main():
auth_ref = get_auth_ref()
check(auth_ref)
if __name__ == "__main__":
main()
| #!/usr/bin/env python
from maas_common import (status_ok, status_err, metric, get_keystone_client,
get_auth_ref)
from requests import Session
from requests import exceptions as exc
def check(auth_ref):
keystone = get_keystone_client(auth_ref)
tenant_id = keystone.tenant_id
auth_token = keystone.auth_token
registry_endpoint = 'http://127.0.0.1:9191'
api_status = 1
milliseconds = 0
s = Session()
s.headers.update(
{'Content-type': 'application/json',
'x-auth-token': auth_token})
try:
# /images returns a list of public, non-deleted images
r = s.get('%s/images' % registry_endpoint, verify=False, timeout=10)
except (exc.ConnectionError,
exc.HTTPError,
exc.Timeout) as e:
api_status = 0
milliseconds = -1
except Exception as e:
status_err(str(e))
else:
if r.ok:
milliseconds = r.elapsed.total_seconds() * 1000
else:
api_status = 0
milliseconds = -1
status_ok()
metric('glance_registry_local_status', 'uint32', api_status)
metric('glance_registry_local_response_time', 'uint32', milliseconds)
def main():
auth_ref = get_auth_ref()
check(auth_ref)
if __name__ == "__main__":
main()
|
Use assign instead of merge | 'use strict'
import * as types from '../constants/action-types'
import { REQUEST_PAGE_START_FROM } from '../constants/author-page'
import get from 'lodash/get'
import isArray from 'lodash/isArray'
import uniq from 'lodash/uniq'
const _ = {
get,
isArray,
uniq
}
const initialStates = {
isFetching: false
}
export const author = (state = initialStates, action = {}) => {
switch (action.type) {
case types.FETCH_AUTHOR_COLLECTION_REQUEST:
return Object.assign({}, state, {
isFetching: true
})
case types.FETCH_AUTHOR_COLLECTION_SUCCESS:
const {
authorId,
response,
currentPage,
totalResults,
totalPages,
receivedAt } = action
const previousCollectionIdList = _.get(state, [ authorId, 'collectIndexList' ], [])
const saveToState = {
isFetching: false,
[authorId]: {
collectIndexList: _.uniq(previousCollectionIdList.concat(_.get(response, 'result', []))),
currentPage,
totalResults,
receivedAt,
isFinish: (currentPage - REQUEST_PAGE_START_FROM + 1 >= totalPages)
}
}
return Object.assign({}, state, saveToState)
case types.FETCH_AUTHOR_COLLECTION_FAILURE:
return Object.assign({}, state, {
isFetching: false,
error: action.error
})
default:
return state
}
}
| 'use strict'
import * as types from '../constants/action-types'
import { REQUEST_PAGE_START_FROM } from '../constants/author-page'
import get from 'lodash/get'
import isArray from 'lodash/isArray'
import merge from 'lodash/merge'
import uniq from 'lodash/uniq'
const _ = {
get,
isArray,
merge,
uniq
}
const initialStates = {
isFetching: false
}
export const author = (state = initialStates, action = {}) => {
switch (action.type) {
case types.FETCH_AUTHOR_COLLECTION_REQUEST:
return Object.assign({}, state, {
isFetching: true
})
case types.FETCH_AUTHOR_COLLECTION_SUCCESS:
const {
authorId,
response,
currentPage,
totalResults,
totalPages,
receivedAt } = action
const previousCollectionIdList = _.get(state, [ authorId, 'collectIndexList' ], [])
const saveToState = {
isFetching: false,
[authorId]: {
collectIndexList: _.uniq(previousCollectionIdList.concat(_.get(response, 'result', []))),
currentPage,
totalResults,
receivedAt,
isFinish: (currentPage - REQUEST_PAGE_START_FROM + 1 >= totalPages)
}
}
return _.merge({}, state, saveToState)
case types.FETCH_AUTHOR_COLLECTION_FAILURE:
return Object.assign({}, state, {
isFetching: false,
error: action.error
})
default:
return state
}
}
|
Add state column to user create api | import uuid
from ckan import model
from ckan.lib import dictization
from ckan.plugins import toolkit
from sqlalchemy import Column, types
from sqlalchemy.ext.declarative import declarative_base
import logging
log = logging.getLogger(__name__)
Base = declarative_base()
def make_uuid():
return unicode(uuid.uuid4())
class UserForOrganization(Base):
__tablename__ = 'user_for_organization'
id = Column(types.UnicodeText, primary_key=True, default=make_uuid)
name = Column(types.UnicodeText, nullable=False)
email = Column(types.UnicodeText, nullable=False)
business_id = Column(types.UnicodeText, nullable=False)
organization_name = Column(types.UnicodeText, nullable=False)
state = Column(types.UnicodeText, nullable=False)
@classmethod
def create(cls, name, email, business_id, organization_name):
user_for_organization = UserForOrganization(name=name,
email=email,
business_id=business_id,
organization_name=organization_name,
state="pending")
model.Session.add(user_for_organization)
model.repo.commit()
def init_table(engine):
Base.metadata.create_all(engine)
log.info("Table for users for organization is set-up") | import uuid
from ckan import model
from ckan.lib import dictization
from ckan.plugins import toolkit
from sqlalchemy import Column, types
from sqlalchemy.ext.declarative import declarative_base
import logging
log = logging.getLogger(__name__)
Base = declarative_base()
def make_uuid():
return unicode(uuid.uuid4())
class UserForOrganization(Base):
__tablename__ = 'user_for_organization'
id = Column(types.UnicodeText, primary_key=True, default=make_uuid)
name = Column(types.UnicodeText, nullable=False)
email = Column(types.UnicodeText, nullable=False)
business_id = Column(types.UnicodeText, nullable=False)
organization_name = Column(types.UnicodeText, nullable=False)
@classmethod
def create(cls, name, email, business_id, organization_name):
user_for_organization = UserForOrganization(name=name,
email=email,
business_id=business_id,
organization_name=organization_name)
model.Session.add(user_for_organization)
model.repo.commit()
def init_table(engine):
Base.metadata.create_all(engine)
log.info("Table for users for organization is set-up") |
Add baseUrl to require config | require.config({
baseUrl: "/js",
paths: {
'jquery': 'lib/jquery',
'underscore': 'lib/underscore',
'backbone': 'lib/backbone',
'doTCompiler': "lib/doTCompiler",
'text': 'lib/text',
'doT': 'lib/doT'
},
shim: {
'underscore': {
exports: '_'
},
'backbone': {
deps: ["underscore", "jquery"],
exports: 'Backbone'
}
}
});
require(
["jquery",
"underscore",
"backbone",
"util/ScrollIntoView",
"providers/matching/MatchingProvider",
"providers/ddg/DDGProvider",
"providers/feedzilla/FeedZillaCategoryProvider",
"providers/fs/FolderProvider",
"providers/nytimes/NYTimesProvider",
"QuickAction"
],
function($, _, B, SIV,
MatchingProvider,
DDGProvider,
FeedZillaCategoryProvider,
FolderProvider,
NYTimesProvider,
QuickAction
) {
$(function() {
QuickAction
.create($("#demo"))
.baseUrl("/")
.provider(new MatchingProvider()
.add(new DDGProvider())
.add(new FeedZillaCategoryProvider())
.add(new NYTimesProvider())
.add(new FolderProvider())
)
.bind();
;
});
}
);
| require.config({
paths: {
'jquery': 'lib/jquery',
'underscore': 'lib/underscore',
'backbone': 'lib/backbone',
'doTCompiler': "lib/doTCompiler",
'text': 'lib/text',
'doT': 'lib/doT'
},
shim: {
'underscore': {
exports: '_'
},
'backbone': {
deps: ["underscore", "jquery"],
exports: 'Backbone'
}
}
});
require(
["jquery",
"underscore",
"backbone",
"util/ScrollIntoView",
"providers/matching/MatchingProvider",
"providers/ddg/DDGProvider",
"providers/feedzilla/FeedZillaCategoryProvider",
"providers/fs/FolderProvider",
"providers/nytimes/NYTimesProvider",
"QuickAction"
],
function($, _, B, SIV,
MatchingProvider,
DDGProvider,
FeedZillaCategoryProvider,
FolderProvider,
NYTimesProvider,
QuickAction
) {
$(function() {
QuickAction
.create($("#demo"))
.baseUrl("/")
.provider(new MatchingProvider()
.add(new DDGProvider())
.add(new FeedZillaCategoryProvider())
.add(new NYTimesProvider())
.add(new FolderProvider())
)
.bind();
;
});
}
);
|
Make the question more clear (for composition)
When the generator is being composed, people using the other generator might not be aware of its presence, so it's unclear what "Choose your style of DSL" refers to.
Ref. yeoman/generator-webapp#545.
Ref. yeoman/generator-webapp#538. | 'use strict';
var generators = require('yeoman-generator');
module.exports = generators.Base.extend({
constructor: function () {
generators.Base.apply(this, arguments);
this.option('ui', {
desc: 'Choose your style of test DSL for Mocha (bdd, tdd)',
type: String
});
this.option('rjs', {
desc: 'Add support for RequireJS',
type: Boolean
});
},
prompting: function () {
var done = this.async();
var prompts = [{
type: 'list',
name: 'ui',
message: 'Choose your style of DSL',
choices: ['BDD', 'TDD'],
default: 'BDD',
when: !this.options.ui
}];
this.prompt(prompts, function (answers) {
this.options.ui = (this.options.ui || answers.ui).toLowerCase();
done();
}.bind(this));
},
configuring: function () {
this.config.set('ui', this.options.ui);
this.config.set('rjs', !!this.options.rjs);
},
writing: function () {
this.template('test.js', 'test/spec/test.js');
this.template('index.html', 'test/index.html');
},
install: function () {
if (this.options['skip-install']) {
return;
}
var dependencies = [
'chai',
'mocha'
];
if (this.options.rjs) {
dependencies.push('requirejs');
}
this.bowerInstall(dependencies, {saveDev: true});
}
});
| 'use strict';
var generators = require('yeoman-generator');
module.exports = generators.Base.extend({
constructor: function () {
generators.Base.apply(this, arguments);
this.option('ui', {
desc: 'Choose your style of DSL (bdd, tdd)',
type: String
});
this.option('rjs', {
desc: 'Add support for RequireJS',
type: Boolean
});
},
prompting: function () {
var done = this.async();
var prompts = [{
type: 'list',
name: 'ui',
message: 'Choose your style of DSL',
choices: ['BDD', 'TDD'],
default: 'BDD',
when: !this.options.ui
}];
this.prompt(prompts, function (answers) {
this.options.ui = (this.options.ui || answers.ui).toLowerCase();
done();
}.bind(this));
},
configuring: function () {
this.config.set('ui', this.options.ui);
this.config.set('rjs', !!this.options.rjs);
},
writing: function () {
this.template('test.js', 'test/spec/test.js');
this.template('index.html', 'test/index.html');
},
install: function () {
if (this.options['skip-install']) {
return;
}
var dependencies = [
'chai',
'mocha'
];
if (this.options.rjs) {
dependencies.push('requirejs');
}
this.bowerInstall(dependencies, {saveDev: true});
}
});
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.