text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Allow Markdown editor to be resized
|
from django.forms import ModelForm,Textarea,TextInput
from .models import Post
class PostForm(ModelForm):
class Meta:
model = Post
fields = ('subject','body')
widgets = {
'subject': TextInput(attrs={'autofocus':'autofocus'}),
'body': Textarea(
attrs={
'data-provide':'markdown',
'data-hidden-buttons':'cmdHeading',
'data-iconlibrary':'octicons',
'data-resize': 'vertical',
}),
}
|
from django.forms import ModelForm,Textarea,TextInput
from .models import Post
class PostForm(ModelForm):
class Meta:
model = Post
fields = ('subject','body')
widgets = {
'subject': TextInput(attrs={'autofocus':'autofocus'}),
'body': Textarea(
attrs={
'data-provide':'markdown',
'data-hidden-buttons':'cmdHeading',
'data-iconlibrary':'octicons',
}),
}
|
Add the viewer to the package_data entry
|
# coding: utf-8
from __future__ import print_function, unicode_literals
import sys
import codecs
from setuptools import setup, find_packages
from nhentai import __version__, __author__, __email__
with open('requirements.txt') as f:
requirements = [l for l in f.read().splitlines() if l]
def long_description():
with codecs.open('README.md', 'rb') as f:
if sys.version_info >= (3, 0, 0):
return str(f.read())
setup(
name='nhentai',
version=__version__,
packages=find_packages(),
package_data={
'nhentai': ['viewer/**']
},
author=__author__,
author_email=__email__,
keywords='nhentai, doujinshi',
description='nhentai.net doujinshis downloader',
long_description=long_description(),
url='https://github.com/RicterZ/nhentai',
download_url='https://github.com/RicterZ/nhentai/tarball/master',
include_package_data=True,
zip_safe=False,
install_requires=requirements,
entry_points={
'console_scripts': [
'nhentai = nhentai.command:main',
]
},
license='MIT',
)
|
# coding: utf-8
from __future__ import print_function, unicode_literals
import sys
import codecs
from setuptools import setup, find_packages
from nhentai import __version__, __author__, __email__
with open('requirements.txt') as f:
requirements = [l for l in f.read().splitlines() if l]
def long_description():
with codecs.open('README.md', 'rb') as f:
if sys.version_info >= (3, 0, 0):
return str(f.read())
setup(
name='nhentai',
version=__version__,
packages=find_packages(),
author=__author__,
author_email=__email__,
keywords='nhentai, doujinshi',
description='nhentai.net doujinshis downloader',
long_description=long_description(),
url='https://github.com/RicterZ/nhentai',
download_url='https://github.com/RicterZ/nhentai/tarball/master',
include_package_data=True,
zip_safe=False,
install_requires=requirements,
entry_points={
'console_scripts': [
'nhentai = nhentai.command:main',
]
},
license='MIT',
)
|
Add new percolation alg to init - to be renamed later
|
r"""
###############################################################################
:mod:`OpenPNM.Algorithms` -- Algorithms on Networks
###############################################################################
Contents
--------
This submodule contains algorithms for performing simulations on pore networks
Classes
-------
.. autoclass:: GenericAlgorithm
:members:
.. autoclass:: Drainage
:members:
.. autoclass:: InvasionPercolation
:members:
.. autoclass:: FickianDiffusion
:members:
.. autoclass:: StokesFlow
:members:
.. autoclass:: OhmicConduction
:members:
.. autoclass:: FourierConduction
:members:
"""
from .__GenericAlgorithm__ import GenericAlgorithm
from .__GenericLinearTransport__ import GenericLinearTransport
from .__FickianDiffusion__ import FickianDiffusion
from .__FourierConduction__ import FourierConduction
from .__OhmicConduction__ import OhmicConduction
from .__StokesFlow__ import StokesFlow
from .__OrdinaryPercolation__ import OrdinaryPercolation
from .__InvasionPercolation__ import InvasionPercolation
from .__Drainage__ import Drainage
from .__InvasionPercolationTT__ import InvasionPercolationTT
|
r"""
###############################################################################
:mod:`OpenPNM.Algorithms` -- Algorithms on Networks
###############################################################################
Contents
--------
This submodule contains algorithms for performing simulations on pore networks
Classes
-------
.. autoclass:: GenericAlgorithm
:members:
.. autoclass:: Drainage
:members:
.. autoclass:: InvasionPercolation
:members:
.. autoclass:: FickianDiffusion
:members:
.. autoclass:: StokesFlow
:members:
.. autoclass:: OhmicConduction
:members:
.. autoclass:: FourierConduction
:members:
"""
from .__GenericAlgorithm__ import GenericAlgorithm
from .__GenericLinearTransport__ import GenericLinearTransport
from .__FickianDiffusion__ import FickianDiffusion
from .__FourierConduction__ import FourierConduction
from .__OhmicConduction__ import OhmicConduction
from .__StokesFlow__ import StokesFlow
from .__OrdinaryPercolation__ import OrdinaryPercolation
from .__InvasionPercolation__ import InvasionPercolation
from .__Drainage__ import Drainage
|
Add use with python3 in the classifiers
|
#!/usr/bin/env python
import os
from setuptools import setup, find_packages
README = os.path.join(os.path.dirname(__file__), 'README.rst')
# when running tests using tox, README.md is not found
try:
with open(README) as file:
long_description = file.read()
except Exception:
long_description = ''
setup(
name='python-resize-image',
version='1.1.10',
description='A Small python package to easily resize images',
long_description=long_description,
url='https://github.com/VingtCinq/python-resize-image',
author='Charles TISSIER',
author_email='charles@vingtcinq.io',
license='MIT',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
],
keywords='image resize resizing python',
packages=find_packages(),
install_requires=['pillow', 'requests'],
test_suite='tests',
)
|
#!/usr/bin/env python
import os
from setuptools import setup, find_packages
README = os.path.join(os.path.dirname(__file__), 'README.rst')
# when running tests using tox, README.md is not found
try:
with open(README) as file:
long_description = file.read()
except Exception:
long_description = ''
setup(
name='python-resize-image',
version='1.1.10',
description='A Small python package to easily resize images',
long_description=long_description,
url='https://github.com/VingtCinq/python-resize-image',
author='Charles TISSIER',
author_email='charles@vingtcinq.io',
license='MIT',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
],
keywords='image resize resizing python',
packages=find_packages(),
install_requires=['pillow', 'requests'],
test_suite='tests',
)
|
Update import for rmq package
|
/*
http://www.apache.org/licenses/LICENSE-2.0.txt
Copyright 2015 Intel Coporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"os"
// Import the pulse plugin library
"github.com/intelsdi-x/pulse-plugin-publisher-rabbitmq/rmq"
"github.com/intelsdi-x/pulse/control/plugin"
)
func main() {
// Three things provided:
// the definition of the plugin metadata
// the implementation satfiying plugin.CollectorPlugin
// the collector configuration policy satifying plugin.ConfigRules
// Define metadata about Plugin
meta := rmq.Meta()
// Start a collector
plugin.Start(meta, rmq.NewRmqPublisher(), os.Args[1])
}
|
/*
http://www.apache.org/licenses/LICENSE-2.0.txt
Copyright 2015 Intel Coporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"os"
// Import the pulse plugin library
"github.com/intelsdi-x/pulse/control/plugin"
"github.com/intelsdi-x/pulse/plugin/publisher/pulse-publisher-rabbitmq/rmq"
)
func main() {
// Three things provided:
// the definition of the plugin metadata
// the implementation satfiying plugin.CollectorPlugin
// the collector configuration policy satifying plugin.ConfigRules
// Define metadata about Plugin
meta := rmq.Meta()
// Start a collector
plugin.Start(meta, rmq.NewRmqPublisher(), os.Args[1])
}
|
Add jsdoc to two stack queue
|
/**
* @license
* js-interview-questions <http://github.com/Tyriar/js-interview-questions>
* Copyright 2015 Daniel Imms <http://www.growingwiththeweb.com>
* Released under the MIT license <http://github.com/Tyriar/js-interview-questions/blob/master/LICENSE>
*/
'use strict';
/**
* Creates a queue implemented with two stacks.
* @constructor
*/
function TwoStackQueue() {
this.inbox = [];
this.outbox = [];
}
/**
* Push a value to the queue.
* @param {Object} value The value to push.
*/
TwoStackQueue.prototype.push = function (value) {
this.inbox.push(value);
};
/**
* Pops a value from the queue and returns it.
* @return {Object} The popped value.
*/
TwoStackQueue.prototype.pop = function () {
if (!this.outbox.length) {
if (!this.inbox.length) {
return undefined;
}
while (this.inbox.length) {
this.outbox.push(this.inbox.pop());
}
}
return this.outbox.pop();
};
module.exports = TwoStackQueue;
|
/**
* @license
* js-interview-questions <http://github.com/Tyriar/js-interview-questions>
* Copyright 2015 Daniel Imms <http://www.growingwiththeweb.com>
* Released under the MIT license <http://github.com/Tyriar/js-interview-questions/blob/master/LICENSE>
*/
'use strict';
/**
* @constructor
*/
function TwoStackQueue() {
this.inbox = [];
this.outbox = [];
}
TwoStackQueue.prototype.push = function (value) {
this.inbox.push(value);
};
TwoStackQueue.prototype.pop = function () {
if (!this.outbox.length) {
if (!this.inbox.length) {
return undefined;
}
while (this.inbox.length) {
this.outbox.push(this.inbox.pop());
}
}
return this.outbox.pop();
};
module.exports = TwoStackQueue;
|
Make SQLite3 tests actually run
PHPUnit was using "sqlite" as extension name, however it should be
"sqlite3". The tests were being skipped because of that.
|
<?php
namespace Doctrine\Tests\Common\Cache;
use Doctrine\Common\Cache\CacheProvider;
use Doctrine\Common\Cache\SQLite3Cache;
use SQLite3;
/**
* @requires extension sqlite3 >= 3
*/
class SQLite3CacheTest extends CacheTest
{
private $file;
private $sqlite;
protected function setUp() : void
{
$this->file = tempnam(null, 'doctrine-cache-test-');
unlink($this->file);
$this->sqlite = new SQLite3($this->file);
}
protected function tearDown() : void
{
$this->sqlite = null; // DB must be closed before
unlink($this->file);
}
public function testGetStats() : void
{
$this->assertNull($this->_getCacheDriver()->getStats());
}
/**
* {@inheritDoc}
*/
protected function _getCacheDriver() : CacheProvider
{
return new SQLite3Cache($this->sqlite, 'test_table');
}
}
|
<?php
namespace Doctrine\Tests\Common\Cache;
use Doctrine\Common\Cache\CacheProvider;
use Doctrine\Common\Cache\SQLite3Cache;
use SQLite3;
/**
* @requires extension sqlite3
*/
class SQLite3CacheTest extends CacheTest
{
private $file;
private $sqlite;
protected function setUp() : void
{
$this->file = tempnam(null, 'doctrine-cache-test-');
unlink($this->file);
$this->sqlite = new SQLite3($this->file);
}
protected function tearDown() : void
{
$this->sqlite = null; // DB must be closed before
unlink($this->file);
}
public function testGetStats() : void
{
$this->assertNull($this->_getCacheDriver()->getStats());
}
/**
* {@inheritDoc}
*/
protected function _getCacheDriver() : CacheProvider
{
return new SQLite3Cache($this->sqlite, 'test_table');
}
}
|
Change label for saving bookmark button
|
<?php
/**
* Copyright (c) 2011 Marvin Thomas Rabe <mrabe@marvinrabe.de>
* Copyright (c) 2011 Arthur Schiwon <blizzz@arthur-schiwon.de>
* This file is licensed under the Affero General Public License version 3 or
* later.
* See the COPYING-README file.
*/
?>
<input type="hidden" id="bookmarkFilterTag" value="<?php if(isset($_GET['tag'])) echo htmlentities($_GET['tag']); ?>" />
<div id="controls">
<input type="hidden" id="bookmark_add_id" value="0" />
<input type="text" id="bookmark_add_url" placeholder="<?php echo $l->t('Address'); ?>" class="bookmarks_input" />
<input type="text" id="bookmark_add_title" placeholder="<?php echo $l->t('Title'); ?>" class="bookmarks_input" />
<input type="text" id="bookmark_add_tags" placeholder="<?php echo $l->t('Tags'); ?>" class="bookmarks_input" />
<input type="submit" value="<?php echo $l->t('Save bookmark'); ?>" id="bookmark_add_submit" />
</div>
<div class="bookmarks_list">
</div>
<div id="firstrun" style="display: none;">
<?php
echo $l->t('You have no bookmarks');
require_once(OC::$APPSROOT . '/apps/bookmarks/templates/bookmarklet.php');
createBookmarklet();
?>
</div>
|
<?php
/**
* Copyright (c) 2011 Marvin Thomas Rabe <mrabe@marvinrabe.de>
* Copyright (c) 2011 Arthur Schiwon <blizzz@arthur-schiwon.de>
* This file is licensed under the Affero General Public License version 3 or
* later.
* See the COPYING-README file.
*/
?>
<input type="hidden" id="bookmarkFilterTag" value="<?php if(isset($_GET['tag'])) echo htmlentities($_GET['tag']); ?>" />
<div id="controls">
<input type="hidden" id="bookmark_add_id" value="0" />
<input type="text" id="bookmark_add_url" placeholder="<?php echo $l->t('Address'); ?>" class="bookmarks_input" />
<input type="text" id="bookmark_add_title" placeholder="<?php echo $l->t('Title'); ?>" class="bookmarks_input" />
<input type="text" id="bookmark_add_tags" placeholder="<?php echo $l->t('Tags'); ?>" class="bookmarks_input" />
<input type="submit" value="<?php echo $l->t('Add bookmark'); ?>" id="bookmark_add_submit" />
</div>
<div class="bookmarks_list">
</div>
<div id="firstrun" style="display: none;">
<?php
echo $l->t('You have no bookmarks');
require_once(OC::$APPSROOT . '/apps/bookmarks/templates/bookmarklet.php');
createBookmarklet();
?>
</div>
|
Add support for nullable Booleans
Summary:
Before this diff, a null Boolean prop would cause an exception, as reported by priteshrnandgaonkar
{F338566882}
Reviewed By: priteshrnandgaonkar
Differential Revision: D24111821
fbshipit-source-id: ae33aa9d70d3878d62ce4a1be89505e7e9319784
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.litho.editor.instances;
import com.facebook.litho.editor.Editor;
import com.facebook.litho.editor.model.EditorBool;
import com.facebook.litho.editor.model.EditorValue;
import java.lang.reflect.Field;
public class BoolEditorInstance implements Editor {
@Override
public EditorValue read(final Field f, final Object node) {
// If you use Boolean here it causes an exception when attempting to do implicit conversion to
// boolean
final Object b = EditorUtils.<Object>getNodeUNSAFE(f, node);
return b == null ? EditorValue.string("null") : EditorValue.bool((Boolean) b);
}
@Override
public boolean write(final Field f, final Object node, final EditorValue values) {
values.when(
new EditorValue.DefaultEditorVisitor() {
@Override
public Void isBool(final EditorBool bool) {
EditorUtils.setNodeUNSAFE(f, node, bool.value);
return null;
}
});
return true;
}
}
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.litho.editor.instances;
import com.facebook.litho.editor.Editor;
import com.facebook.litho.editor.model.EditorBool;
import com.facebook.litho.editor.model.EditorValue;
import java.lang.reflect.Field;
public class BoolEditorInstance implements Editor {
@Override
public EditorValue read(Field f, Object node) {
return EditorValue.bool(EditorUtils.<Boolean>getNodeUNSAFE(f, node));
}
@Override
public boolean write(final Field f, final Object node, final EditorValue values) {
values.when(
new EditorValue.DefaultEditorVisitor() {
@Override
public Void isBool(EditorBool bool) {
EditorUtils.setNodeUNSAFE(f, node, bool.value);
return null;
}
});
return true;
}
}
|
Fix support for `batch` event
|
'use strict';
var memoize = require('memoizee/lib/primitive')
, Fragment = require('dbjs-fragment')
, objFragment = require('dbjs-fragment/object-family')
, getId = function (obj) { return obj.__id__; };
module.exports = function (set, meta, fragment) {
var getFragment, onAdd, onDelete;
if (!fragment) fragment = new Fragment();
getFragment = memoize(function (obj) {
return objFragment(obj, meta);
}, { serialize: getId });
set.forEach(onAdd = function (obj) {
fragment.sets.add(getFragment(obj));
});
onDelete = function (obj) { fragment.sets.delete(getFragment(obj)); };
set.on('change', function (event) {
if (event.type === 'add') {
onAdd(event.value);
return;
}
if (event.type === 'delete') {
onDelete(event.value);
return;
}
if (event.type === 'batch') {
if (event.added) event.added.forEach(onAdd);
if (event.deleted) event.deleted.forEach(onDelete);
return;
}
console.log("Errorneous event:", event);
throw new TypeError("Unsupported event: " + event.type);
});
return fragment;
};
|
'use strict';
var memoize = require('memoizee/lib/primitive')
, Fragment = require('dbjs-fragment')
, objFragment = require('dbjs-fragment/object-family')
, getId = function (obj) { return obj.__id__; };
module.exports = function (set, meta, fragment) {
var getFragment, onAdd;
if (!fragment) fragment = new Fragment();
getFragment = memoize(function (obj) {
return objFragment(obj, meta);
}, { serialize: getId });
set.forEach(onAdd = function (obj) {
fragment.sets.add(getFragment(obj));
});
set.on('change', function (event) {
if (event.type === 'add') {
onAdd(event.value);
return;
}
if (event.type === 'delete') {
fragment.sets.delete(getFragment(event.value));
return;
}
throw new TypeError("Unsupported event: " + event.type);
});
return fragment;
};
|
Fix issue with editor content
|
<?php
// Exit if accessed directly
defined( 'ABSPATH' ) || exit;
/**
* Papi Property Editor class.
*
* @package Papi
*/
class Papi_Property_Editor extends Papi_Property {
/**
* Format the value of the property before it's returned to the application.
*
* @param mixed $value
* @param string $slug
* @param int $post_id
*
* @return array
*/
public function format_value( $value, $slug, $post_id ) {
return is_admin() ? $value : apply_filters( 'the_content', $value );
}
/**
* Render property html.
*/
public function html() {
$value = $this->get_value();
$id = str_replace(
'[',
'',
str_replace( ']', '', $this->html_name() )
) . '-' . uniqid();
wp_editor( $value, $id, [
'textarea_name' => $this->html_name(),
'media_buttons' => true
] );
if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
add_filter( 'mce_external_plugins', '__return_empty_array' );
}
}
}
|
<?php
// Exit if accessed directly
defined( 'ABSPATH' ) || exit;
/**
* Papi Property Editor class.
*
* @package Papi
*/
class Papi_Property_Editor extends Papi_Property {
/**
* Format the value of the property before it's returned to the application.
*
* @param mixed $value
* @param string $slug
* @param int $post_id
*
* @return array
*/
public function format_value( $value, $slug, $post_id ) {
return apply_filters( 'the_content', $value );
}
/**
* Render property html.
*/
public function html() {
$value = $this->get_value();
$id = str_replace(
'[',
'',
str_replace( ']', '', $this->html_name() )
) . '-' . uniqid();
wp_editor( $value, $id, [
'textarea_name' => $this->html_name(),
'media_buttons' => true
] );
if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
add_filter( 'mce_external_plugins', '__return_empty_array' );
}
}
}
|
Set default logging level to WARN.
|
import datetime
import logging
from django.core.management.base import BaseCommand
import mysite.profile.tasks
import mysite.search.models
import mysite.search.tasks
## FIXME: Move to a search management command?
def periodically_check_if_bug_epoch_eclipsed_the_cached_search_epoch():
logging.info("Checking if bug epoch eclipsed the cached search epoch")
cache_time = mysite.search.models.Epoch.get_for_string('search_cache')
bug_time = mysite.search.models.Epoch.get_for_string('search_cache')
if cache_time < bug_time:
mysite.search.tasks.clear_search_cache()
mysite.search.models.Epoch.bump_for_string('search_cache')
logging.info("Finished dealing with bug epoch vs. cached search epoch.")
class Command(BaseCommand):
help = "Run this once hourly for the OpenHatch profile app."
def handle(self, *args, **options):
rootLogger = logging.getLogger('')
rootLogger.setLevel(logging.WARN)
mysite.profile.tasks.sync_bug_epoch_from_model_then_fill_recommended_bugs_cache()
mysite.profile.tasks.fill_recommended_bugs_cache()
# Every 4 hours, clear search cache
if (datetime.datetime.utcnow().hour % 4) == 0:
periodically_check_if_bug_epoch_eclipsed_the_cached_search_epoch()
|
import datetime
import logging
from django.core.management.base import BaseCommand
import mysite.profile.tasks
import mysite.search.models
import mysite.search.tasks
## FIXME: Move to a search management command?
def periodically_check_if_bug_epoch_eclipsed_the_cached_search_epoch():
logging.info("Checking if bug epoch eclipsed the cached search epoch")
cache_time = mysite.search.models.Epoch.get_for_string('search_cache')
bug_time = mysite.search.models.Epoch.get_for_string('search_cache')
if cache_time < bug_time:
mysite.search.tasks.clear_search_cache()
mysite.search.models.Epoch.bump_for_string('search_cache')
logging.info("Finished dealing with bug epoch vs. cached search epoch.")
class Command(BaseCommand):
help = "Run this once hourly for the OpenHatch profile app."
def handle(self, *args, **options):
mysite.profile.tasks.sync_bug_epoch_from_model_then_fill_recommended_bugs_cache()
mysite.profile.tasks.fill_recommended_bugs_cache()
# Every 4 hours, clear search cache
if (datetime.datetime.utcnow().hour % 4) == 0:
periodically_check_if_bug_epoch_eclipsed_the_cached_search_epoch()
|
Select different max page records will default to show first page.
|
/**
*
*/
$( document ).ready( function() {
var moretext = "Read More";
var lesstext = "Read Less";
$( ".more-link" ).click( function() {
if ( $( this ).hasClass( "less" ) ) {
$( this ).removeClass( "less" );
$( this ).html( moretext );
} else {
$( this ).addClass( "less" );
$( this ).html( lesstext );
}
$( this ).parent().children( ".more-skip" ).toggle();
$( this ).prev().toggle();
return false;
} );
$( "#list-max" ).change( function() {
var url = window.location.href.replace( /\&max\=[0-9]+/g, "" );
url.replace( /\&page\=[0-9]+/g, "" );
window.location = url + "&max=" + $( this ).val();
} );
});
|
/**
*
*/
$( document ).ready( function() {
var moretext = "Read More";
var lesstext = "Read Less";
$( ".more-link" ).click( function() {
if ( $( this ).hasClass( "less" ) ) {
$( this ).removeClass( "less" );
$( this ).html( moretext );
} else {
$( this ).addClass( "less" );
$( this ).html( lesstext );
}
$( this ).parent().children( ".more-skip" ).toggle();
$( this ).prev().toggle();
return false;
} );
$( "#list-max" ).change( function() {
var url = window.location.href.replace( /\&max\=[0-9]+/g, "" );
window.location = url + "&max=" + $( this ).val();
} );
});
|
Update the camb3lyp example to libxc 5 series
|
#!/usr/bin/env python
#
# Author: Qiming Sun <osirpt.sun@gmail.com>
#
'''Density functional calculations can be run with either the default
backend library, libxc, or an alternative library, xcfun. See also
example 32-xcfun_as_default.py for how to set xcfun as the default XC
functional library.
'''
from pyscf import gto, dft
from pyscf.hessian import uks as uks_hess
from pyscf import tdscf
mol = gto.M(atom="H; F 1 1.", basis='631g')
# Calculation using libxc
mf = dft.UKS(mol)
mf.xc = 'CAMB3LYP'
mf.kernel()
mf.nuc_grad_method().kernel()
# We can also evaluate the geometric hessian
hess = uks_hess.Hessian(mf).kernel()
print(hess.reshape(2,3,2,3))
# or TDDFT gradients
tdks = tdscf.TDA(mf)
tdks.nstates = 3
tdks.kernel()
tdks.nuc_grad_method().kernel()
# Switch to the xcfun library on the fly
mf._numint.libxc = dft.xcfun
# Repeat the geometric hessian
hess = uks_hess.Hessian(mf).kernel()
print(hess.reshape(2,3,2,3))
# and the TDDFT gradient calculation
tdks = tdscf.TDA(mf)
tdks.nstates = 3
tdks.kernel()
tdks.nuc_grad_method().kernel()
|
#!/usr/bin/env python
#
# Author: Qiming Sun <osirpt.sun@gmail.com>
#
'''
The default XC functional library (libxc) supports the energy and nuclear
gradients for range separated functionals. Nuclear Hessian and TDDFT gradients
need xcfun library. See also example 32-xcfun_as_default.py for how to set
xcfun library as the default XC functional library.
'''
from pyscf import gto, dft
mol = gto.M(atom="H; F 1 1.", basis='631g')
mf = dft.UKS(mol)
mf.xc = 'CAMB3LYP'
mf.kernel()
mf.nuc_grad_method().kernel()
from pyscf.hessian import uks as uks_hess
# Switching to xcfun library on the fly
mf._numint.libxc = dft.xcfun
hess = uks_hess.Hessian(mf).kernel()
print(hess.reshape(2,3,2,3))
from pyscf import tdscf
# Switching to xcfun library on the fly
mf._numint.libxc = dft.xcfun
tdks = tdscf.TDA(mf)
tdks.nstates = 3
tdks.kernel()
tdks.nuc_grad_method().kernel()
|
Add deferred register to items
|
package info.u_team.u_team_test.init;
import info.u_team.u_team_core.item.armor.*;
import info.u_team.u_team_core.item.tool.*;
import info.u_team.u_team_test.TestMod;
import info.u_team.u_team_test.item.*;
import net.minecraft.item.Item;
import net.minecraft.item.Item.Properties;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.registries.*;
public class TestItems {
public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, TestMod.MODID);
public static final Item BASIC = new BasicItem("basicitem");
public static final Item BETTER_ENDERPEARL = new BetterEnderPearlItem("better_enderpearl");
public static final Item BASIC_FOOD = new BasicFoodItem("basicfood");
public static final ToolSet BASIC_TOOL = ToolSetCreator.create("basictool", TestItemGroups.GROUP, new Properties(), TestToolMaterial.BASIC);
public static final ArmorSet BASIC_ARMOR = ArmorSetCreator.create("basicarmor", TestItemGroups.GROUP, new Properties(), TestArmorMaterial.BASIC);
public static void register(IEventBus bus) {
ITEMS.register(bus);
}
}
|
package info.u_team.u_team_test.init;
import info.u_team.u_team_core.item.armor.*;
import info.u_team.u_team_core.item.tool.*;
import info.u_team.u_team_core.util.registry.BaseRegistryUtil;
import info.u_team.u_team_test.TestMod;
import info.u_team.u_team_test.item.*;
import net.minecraft.item.Item;
import net.minecraft.item.Item.Properties;
import net.minecraftforge.event.RegistryEvent.Register;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus;
@EventBusSubscriber(modid = TestMod.MODID, bus = Bus.MOD)
public class TestItems {
public static final Item BASIC = new BasicItem("basicitem");
public static final Item BETTER_ENDERPEARL = new BetterEnderPearlItem("better_enderpearl");
public static final Item BASIC_FOOD = new BasicFoodItem("basicfood");
public static final ToolSet BASIC_TOOL = ToolSetCreator.create("basictool", TestItemGroups.GROUP, new Properties(), TestToolMaterial.BASIC);
public static final ArmorSet BASIC_ARMOR = ArmorSetCreator.create("basicarmor", TestItemGroups.GROUP, new Properties(), TestArmorMaterial.BASIC);
@SubscribeEvent
public static void registerBlockItem(Register<Item> event) {
BaseRegistryUtil.getAllRegistryEntriesAndApplyNames(TestMod.MODID, Item.class).forEach(event.getRegistry()::register);
}
}
|
fix(tests): Allow importing test data for any db collection
|
const fs = require('fs');
const { promisify } = require('util');
const mongodb = require('mongodb');
const request = require('request');
async function readMongoDocuments(file) {
const ISODate = (d) => new Date(d);
const ObjectId = (id) => mongodb.ObjectID.createFromHexString(id);
return eval(await fs.promises.readFile(file, 'utf-8'));
}
async function insertTestData(url, docsPerCollection) {
const mongoClient = await mongodb.MongoClient.connect(url);
const db = mongoClient.db();
await Promise.all(
Object.keys(docsPerCollection).map(async (collection) => {
await db.collection(collection).deleteMany({});
await db.collection(collection).insertMany(docsPerCollection[collection]);
})
);
await mongoClient.close();
}
/* refresh openwhyd's in-memory cache of users, to allow this user to login */
async function refreshOpenwhydCache(urlPrefix = 'http://localhost:8080') {
await promisify(request.post)(urlPrefix + '/testing/refresh');
}
module.exports = {
readMongoDocuments,
insertTestData,
refreshOpenwhydCache,
};
|
const fs = require('fs');
const { promisify } = require('util');
const mongodb = require('mongodb');
const request = require('request');
async function readMongoDocuments(file) {
const ISODate = (d) => new Date(d);
const ObjectId = (id) => mongodb.ObjectID.createFromHexString(id);
return eval(await fs.promises.readFile(file, 'utf-8'));
}
async function insertTestData(url, users, posts) {
const mongoClient = await mongodb.MongoClient.connect(url);
const db = mongoClient.db();
await db.collection('user').deleteMany({});
await db.collection('post').deleteMany({});
await db.collection('user').insertMany(users);
await db.collection('post').insertMany(posts);
await mongoClient.close();
}
/* refresh openwhyd's in-memory cache of users, to allow this user to login */
async function refreshOpenwhydCache(urlPrefix = 'http://localhost:8080') {
await promisify(request.post)(urlPrefix + '/testing/refresh');
}
module.exports = {
readMongoDocuments,
insertTestData,
refreshOpenwhydCache,
};
|
Include features are now processed asynchronously
TemplateFeatureInclude
* moved from fs.readFileSync to fs.readFile
+ added proper error calling when no file argument was found
|
var TemplateFeature = require('./index.js'),
XML = require('xmldom'),
fs = require('fs');
/*
* Embed external templates
* @name TemplateFeatureInclude
* @package Scaffold
*/
function TemplateFeatureInclude(element, template)
{
var include = this;
TemplateFeature.apply(include, arguments);
/**
* Replace the feature node with the contents of included file
* @name prepare
* @type method
* @access public
* @return void
*/
include.prepare = function(done)
{
var file = include.attribute('file');
include.clean();
if (file)
{
fs.readFile(file, function(error, data){
var dom;
if (!error && data)
{
dom = new XML.DOMParser().parseFromString('<include>' + data + '</include>');
while (dom.documentElement.firstChild)
{
element.parentNode.insertBefore(element.ownerDocument.importNode(dom.documentElement.firstChild, true), element);
dom.documentElement.removeChild(dom.documentElement.firstChild);
}
}
if (done)
done(error, include);
});
return;
}
done(new Error('no template file provided for k:include feature'));
};
}
module.exports = TemplateFeatureInclude;
|
var TemplateFeature = require('./index.js'),
XML = require('xmldom'),
fs = require('fs');
/*
* Embed external templates
* @name TemplateFeatureInclude
* @package Scaffold
*/
function TemplateFeatureInclude(element, template)
{
var include = this;
TemplateFeature.apply(include, arguments);
/**
* Replace the feature node with the contents of included file
* @name prepare
* @type method
* @access public
* @return void
*/
include.prepare = function(done)
{
var file = include.attribute('file'),
dom;
if (file)
{
file = fs.readFileSync(file);
dom = new XML.DOMParser().parseFromString('<include>' + file.toString() + '</include>');
while (dom.documentElement.firstChild)
{
element.parentNode.insertBefore(element.ownerDocument.importNode(dom.documentElement.firstChild, true), element);
dom.documentElement.removeChild(dom.documentElement.firstChild);
}
}
include.clean();
if (done)
done(null, include);
};
}
module.exports = TemplateFeatureInclude;
|
Remove MonitorModel HashID from AccountModel:MonitorModel:hashID
|
var configuration = require('../config/configuration.json')
module.exports = function (redisClient, accountHashID, monitorHashID, callback) {
multi = redisClient.multi()
var monitorTable = configuration.TableMAMonitorModel + monitorHashID
multi.hdel(monitorTable,
configuration.ConstantMMTime,
configuration.ConstantMMStatusCode,
configuration.ConstantMMServiceCaller,
configuration.ConstantMMModuleCaller,
configuration.ConstantMMAction,
configuration.ConstantMMLogMessage,
configuration.ConstantMMObjectInfo
)
var monitorModelTablesKeys = Object.keys(configuration.TableMonitorModel)
for(var i = 0; i < monitorModelTablesKeys.length; i++) {
var monitorModelOptionTablesKeys = Object.keys(configuration.TableMonitorModel[monitorModelTablesKeys[i]])
for (var j = 0; j < monitorModelOptionTablesKeys.length; j++) {
var opt = configuration.TableMonitorModel[monitorModelTablesKeys[i]]
var enums = Object.keys(opt)
multi.zrem(opt[enums[j]] + accountHashID, monitorHashID)
multi.zrem(opt[enums[j]], monitorHashID)
}
}
multi.zrem(configuration.TableMSAccountModelMonitorModel + accountHashID)
multi.zrem(configuration.TableMAMonitorModel, monitorHashID)
multi.exec(function (err, replies) {
if (err)
callback(err, null)
callback(null, configuration.message.log.removed)
})
}
|
var configuration = require('../config/configuration.json')
module.exports = function (redisClient, accountHashID, monitorHashID, callback) {
multi = redisClient.multi()
var monitorTable = configuration.TableMAMonitorModel + monitorHashID
multi.hdel(monitorTable,
configuration.ConstantMMTime,
configuration.ConstantMMStatusCode,
configuration.ConstantMMServiceCaller,
configuration.ConstantMMModuleCaller,
configuration.ConstantMMAction,
configuration.ConstantMMLogMessage,
configuration.ConstantMMObjectInfo
)
var monitorModelTablesKeys = Object.keys(configuration.TableMonitorModel)
for(var i = 0; i < monitorModelTablesKeys.length; i++) {
var monitorModelOptionTablesKeys = Object.keys(configuration.TableMonitorModel[monitorModelTablesKeys[i]])
for (var j = 0; j < monitorModelOptionTablesKeys.length; j++) {
var opt = configuration.TableMonitorModel[monitorModelTablesKeys[i]]
var enums = Object.keys(opt)
multi.zrem(opt[enums[j]] + accountHashID, monitorHashID)
multi.zrem(opt[enums[j]], monitorHashID)
}
}
multi.zrem(configuration.TableMAMonitorModel, monitorHashID)
multi.exec(function (err, replies) {
if (err)
callback(err, null)
callback(null, configuration.message.log.removed)
})
}
|
feat(header): Add link to Docker Hub :rocket:
|
import React from 'react'
import {iconify} from '../lib/str'
import styles from './styles'
export const Link = ({name, href, title}) => (
<a className={styles.link} href={href} title={title} target={'_blank'}>
<span className={styles[iconify(name)]} />
</a>
)
export const Header = () => (
<header className={styles.header}>
<h1 className={styles.title}>Langri-Sha</h1>
<nav className={styles.nav}>
{[
[
'Stack Overflow', 'https://stackoverflow.com/users/44041/filip-dupanovi%C4%87?tab=profile',
'StackOverflow profile #SOreadytohelp 💓'
],
[
'Keybase', 'https://keybase.io/langrisha',
'Identity details on Keybase.io'
],
[
'GitHub', 'https://github.com/langri-sha',
'GitHub profile'
],
[
'Docker', 'https://hub.docker.com/u/langrisha/',
'Docker Hub profile'
]
].map(([name, href, title]) => (
<Link key={name} name={name} href={href} title={title} />
))}
</nav>
</header>
)
|
import React from 'react'
import {iconify} from '../lib/str'
import styles from './styles'
export const Link = ({name, href, title}) => (
<a className={styles.link} href={href} title={title} target={'_blank'}>
<span className={styles[iconify(name)]} />
</a>
)
export const Header = () => (
<header className={styles.header}>
<h1 className={styles.title}>Langri-Sha</h1>
<nav className={styles.nav}>
{[
[
'Stack Overflow', 'https://stackoverflow.com/users/44041/filip-dupanovi%C4%87?tab=profile',
'StackOverflow profile #SOreadytohelp 💓'
],
[
'Keybase', 'https://keybase.io/langrisha',
'Identity details on Keybase.io'
],
[
'GitHub', 'https://github.com/langri-sha',
'GitHub profile'
]
].map(([name, href, title]) => (
<Link key={name} name={name} href={href} title={title} />
))}
</nav>
</header>
)
|
Use the real unknown command err-code
Using the real unknown command error code means that the client
actually understands the error and behaves appropriately.
|
import generate as gen
commands = {}
def cmd_func(name):
def _cmd_func(f):
commands.setdefault(name, f)
return f
return _cmd_func
@cmd_func('get-latest-rev')
def get_latest_rev(args):
return "%s %s" % (gen.success('( )', gen.string('test')),
gen.success('12'))
def handle_command(msg):
command = msg[0]
args = msg [1]
if command not in commands:
return gen.failure(gen.list('210001',
gen.string("Unknown command '%s'" % command),
gen.string('commands.py'), '0'))
return commands[command](args)
|
import generate as gen
commands = {}
def cmd_func(name):
def _cmd_func(f):
commands.setdefault(name, f)
return f
return _cmd_func
@cmd_func('get-latest-rev')
def get_latest_rev(args):
return "%s %s" % (gen.success('( )', gen.string('test')),
gen.success('12'))
def handle_command(msg):
command = msg[0]
args = msg [1]
if command not in commands:
return gen.failure(gen.list('12',
gen.string('unknown command: %s' % command),
gen.string('commands.py'), '0'))
return commands[command](args)
|
Fix compile error on Linux
|
/*
* Resources.java
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
package org.rstudio.studio.client.pdfviewer.ui.images;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.ImageResource;
public interface Resources extends ClientBundle
{
@Source("FileOptionsIcon.png")
ImageResource fileOptionsIcon();
@Source("NextPageIcon.png")
ImageResource nextPageIcon();
@Source("PreviousPageIcon.png")
ImageResource previousPageIcon();
@Source("SizeButton.png")
ImageResource sizeButton();
@Source("SizeButtonPressed.png")
ImageResource sizeButtonPressed();
@Source("ZoomButtonLeft.png")
ImageResource zoomButtonLeft();
@Source("ZoomButtonLeftPressed.png")
ImageResource zoomButtonLeftPressed();
@Source("ZoomButtonRight.png")
ImageResource zoomButtonRight();
@Source("ZoomButtonRightPressed.png")
ImageResource zoomButtonRightPressed();
@Source("ZoomInIcon.png")
ImageResource zoomInIcon();
@Source("ZoomOutIcon.png")
ImageResource zoomOutIcon();
@Source("ThumbnailsIcon.png")
ImageResource thumbnailsIcon();
}
|
/*
* Resources.java
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
package org.rstudio.studio.client.pdfviewer.ui.images;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.ImageResource;
public interface Resources extends ClientBundle
{
ImageResource fileOptionsIcon();
ImageResource nextPageIcon();
ImageResource previousPageIcon();
ImageResource sizeButton();
ImageResource sizeButtonPressed();
ImageResource zoomButtonLeft();
ImageResource zoomButtonLeftPressed();
ImageResource zoomButtonRight();
ImageResource zoomButtonRightPressed();
ImageResource zoomInIcon();
ImageResource zoomOutIcon();
ImageResource thumbnailsIcon();
}
|
Improve detectQuoteStyle (needed when adding imports and requires)
|
/**
* As Recast is not preserving original quoting, we try to detect it.
* See https://github.com/benjamn/recast/issues/171
* and https://github.com/facebook/jscodeshift/issues/143
* @return 'double', 'single' or null
*/
export default function detectQuoteStyle(j, ast) {
let doubles = 0;
let singles = 0;
ast
.find(j.Literal, {
value: v => typeof v === 'string',
raw: v => typeof v === 'string',
})
.forEach(p => {
// The raw value is from the original babel source
const quote = p.value.raw[0];
if (quote === '"') {
doubles += 1;
}
if (quote === "'") {
singles += 1;
}
});
if (doubles === singles) {
return null;
}
return doubles > singles ? 'double' : 'single';
}
|
/**
* As Recast is not preserving original quoting, we try to detect it.
* See https://github.com/benjamn/recast/issues/171
* and https://github.com/facebook/jscodeshift/issues/143
* @return 'double', 'single' or null
*/
export default function detectQuoteStyle(j, ast) {
let detectedQuoting = null;
ast
.find(j.Literal, {
value: v => typeof v === 'string',
raw: v => typeof v === 'string',
})
.forEach(p => {
// The raw value is from the original babel source
if (p.value.raw[0] === "'") {
detectedQuoting = 'single';
}
if (p.value.raw[0] === '"') {
detectedQuoting = 'double';
}
});
return detectedQuoting;
}
|
Document methods in conference repository
|
package mn.devfest.persistence;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import mn.devfest.api.model.Conference;
/**
* Stores and provides information about the conference. The app is shipped with a local copy of
* the latest conference information. As we get newer information from the API, this is updated.
*
* @author pfuentes
*/
public class ConferenceRepository {
Context mContext;
SharedPreferences mSharedPreferences;
public ConferenceRepository(@NonNull Context context) {
mContext = context;
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
}
/**
* Removes any existing persisted conference data and replaces it with the passed value
*
* @param conference most up-to-date conference information available
*/
public void setConference(@Nullable Conference conference) {
//TODO implement
}
/**
* Provides the most recently persisted conference data
*
* @return persisted conference data
*/
@NonNull
public Conference getConference() {
//TODO implement and remove dummy return
return new Conference();
}
}
|
package mn.devfest.persistence;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import mn.devfest.api.model.Conference;
/**
* Stores and provides information about the conference. The app is shipped with a local copy of
* the latest conference information. As we get newer information from the API, this is updated.
*
* @author pfuentes
*/
public class ConferenceRepository {
Context mContext;
SharedPreferences mSharedPreferences;
public ConferenceRepository (@NonNull Context context){
mContext = context;
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
}
public void setConference(Conference conference) {
//TODO implement
}
public Conference getConference() {
//TODO implement and remove dummy return
return new Conference();
}
}
|
Add removal of email address
|
const now = require('performance-now');
module.exports = {
help: {
name: 'eval',
desc: 'Runs a JavaScript snippet',
usage: '<js snippet>',
aliases: ['e']
},
exec: (client, msg, params) => {
let time = now();
let input = params.join(' ');
try {
let message = msg, self = client, bot = client;
let output = eval(input.replace(/\r?\n|\r/g, ' '));
if(typeof output != 'string') {
output = require('util').inspect(output);
}
output = output.replace(client.token, '[token redacted]').replace(client.user.email, '[email redacted]');
msg.edit(`***\`Input\`*** \`\`\`js\n${input}\n\`\`\`\n***\`Output\`*** \`\`\`js\n${output}\n\`\`\``).catch(console.error);
} catch (error) {
msg.edit(`***\`Input\`*** \`\`\`js\n${input}\n\`\`\`\n***\`Error\`*** \`\`\`js\n${error}\n\`\`\``).catch(console.error);
}
}
}
|
const now = require('performance-now');
module.exports = {
help: {
name: 'eval',
desc: 'Runs a JavaScript snippet',
usage: '<js snippet>',
aliases: ['e']
},
exec: (client, msg, params) => {
let time = now();
let input = params.join(' ');
try {
let message = msg;
let output = eval(input.replace(/\r?\n|\r/g, ' '));
if(typeof output != 'string') {
output = require('util').inspect(output);
}
output = output.replace(client.token, '[token redacted]');
msg.edit(`***\`Input\`*** \`\`\`js\n${input}\n\`\`\`\n***\`Output\`*** \`\`\`js\n${output}\n\`\`\``).catch(console.error);
} catch (error) {
msg.edit(`***\`Input\`*** \`\`\`js\n${input}\n\`\`\`\n***\`Error\`*** \`\`\`js\n${error}\n\`\`\``).catch(console.error);
}
}
}
|
Stop media player after sound.
|
package com.tom_e_white.chickenalerts;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
public class ChickenAlertReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Notification notification = new Notification.Builder(context)
.setContentTitle("Chicken Alert")
.setContentText("Have you put the chickens to bed?")
.setTicker("Have you put the chickens to bed?")
.setSmallIcon(R.drawable.ic_launcher).build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notification);
MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.cluck);
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
}
}
|
package com.tom_e_white.chickenalerts;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
public class ChickenAlertReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Notification notification = new Notification.Builder(context)
.setContentTitle("Chicken Alert")
.setContentText("Have you put the chickens to bed?")
.setTicker("Have you put the chickens to bed?")
.setSmallIcon(R.drawable.ic_launcher).build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notification);
MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.cluck);
mediaPlayer.start(); // no need to call prepare(); create() does that for you
}
}
|
Add Heroku DNS to allowed hosts
|
from django.core.exceptions import ImproperlyConfigured
from .settings import *
def get_env_variable(var_name):
"""
Get the environment variable or return exception.
"""
try:
return os.environ[var_name]
except KeyError:
error_msg = 'Set the %s environment variable' % var_name
raise ImproperlyConfigured(error_msg)
DEBUG = False
ALLOWED_HOSTS = [
'tictactoe.zupec.net',
'tictactoe-zupec.herokuapp.com',
]
SECRET_KEY = get_env_variable('SECRET_KEY')
MIDDLEWARE_CLASSES += (
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
'whitenoise.middleware.WhiteNoiseMiddleware',
)
# TODO: temporarily disabled to test Heroku
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.postgresql',
# 'NAME': get_env_variable("DATABASE_NAME"),
# 'USER': get_env_variable("DATABASE_USER"),
# 'PASSWORD': get_env_variable("DATABASE_PASSWORD"),
# 'HOST': get_env_variable("DATABASE_HOST"),
# 'PORT': '5432',
# },
# }
|
from django.core.exceptions import ImproperlyConfigured
from .settings import *
def get_env_variable(var_name):
"""
Get the environment variable or return exception.
"""
try:
return os.environ[var_name]
except KeyError:
error_msg = 'Set the %s environment variable' % var_name
raise ImproperlyConfigured(error_msg)
DEBUG = False
# TODO: temporarily disabled to test Heroku
# ALLOWED_HOSTS = ['tictactoe.zupec.net']
SECRET_KEY = get_env_variable('SECRET_KEY')
MIDDLEWARE_CLASSES += (
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
'whitenoise.middleware.WhiteNoiseMiddleware',
)
# TODO: temporarily disabled to test Heroku
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.postgresql',
# 'NAME': get_env_variable("DATABASE_NAME"),
# 'USER': get_env_variable("DATABASE_USER"),
# 'PASSWORD': get_env_variable("DATABASE_PASSWORD"),
# 'HOST': get_env_variable("DATABASE_HOST"),
# 'PORT': '5432',
# },
# }
|
Use function exsists instead of extension loaded
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Symfony\Polyfill\Ctype as p;
if (!function_exists('ctype_alnum')) {
function ctype_alnum($text) { return p\Ctype::ctype_alnum($text); }
function ctype_alpha($text) { return p\Ctype::ctype_alpha($text); }
function ctype_cntrl($text) { return p\Ctype::ctype_cntrl($text); }
function ctype_digit($text) { return p\Ctype::ctype_digit($text); }
function ctype_graph($text) { return p\Ctype::ctype_graph($text); }
function ctype_lower($text) { return p\Ctype::ctype_lower($text); }
function ctype_print($text) { return p\Ctype::ctype_print($text); }
function ctype_punct($text) { return p\Ctype::ctype_punct($text); }
function ctype_space($text) { return p\Ctype::ctype_space($text); }
function ctype_upper($text) { return p\Ctype::ctype_upper($text); }
function ctype_xdigit($text) { return p\Ctype::ctype_xdigit($text); }
}
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Symfony\Polyfill\Ctype as p;
if (!extension_loaded('ctype')) {
function ctype_alnum($text) { return p\Ctype::ctype_alnum($text); }
function ctype_alpha($text) { return p\Ctype::ctype_alpha($text); }
function ctype_cntrl($text) { return p\Ctype::ctype_cntrl($text); }
function ctype_digit($text) { return p\Ctype::ctype_digit($text); }
function ctype_graph($text) { return p\Ctype::ctype_graph($text); }
function ctype_lower($text) { return p\Ctype::ctype_lower($text); }
function ctype_print($text) { return p\Ctype::ctype_print($text); }
function ctype_punct($text) { return p\Ctype::ctype_punct($text); }
function ctype_space($text) { return p\Ctype::ctype_space($text); }
function ctype_upper($text) { return p\Ctype::ctype_upper($text); }
function ctype_xdigit($text) { return p\Ctype::ctype_xdigit($text); }
}
|
Fix 1 ErrorProneStyle finding:
* Constructors and methods with the same name should appear sequentially with no other code in between. Please re-order or re-name methods.
-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=286176935
|
/*
* Copyright 2013 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.auto.factory.processor;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableSet;
import javax.lang.model.type.TypeMirror;
@AutoValue
abstract class ImplementationMethodDescriptor {
abstract String name();
abstract TypeMirror returnType();
abstract boolean publicMethod();
abstract ImmutableSet<Parameter> passedParameters();
abstract boolean isVarArgs();
static Builder builder() {
return new AutoValue_ImplementationMethodDescriptor.Builder()
.publicMethod(true)
.isVarArgs(false);
}
@AutoValue.Builder
static abstract class Builder {
abstract Builder name(String name);
abstract Builder returnType(TypeMirror returnTypeElement);
abstract Builder publicMethod(boolean publicMethod);
final Builder publicMethod() {
return publicMethod(true);
}
abstract Builder passedParameters(Iterable<Parameter> passedParameters);
abstract Builder isVarArgs(boolean isVarargs);
abstract ImplementationMethodDescriptor build();
}
}
|
/*
* Copyright 2013 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.auto.factory.processor;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableSet;
import javax.lang.model.type.TypeMirror;
@AutoValue
abstract class ImplementationMethodDescriptor {
abstract String name();
abstract TypeMirror returnType();
abstract boolean publicMethod();
abstract ImmutableSet<Parameter> passedParameters();
abstract boolean isVarArgs();
static Builder builder() {
return new AutoValue_ImplementationMethodDescriptor.Builder()
.publicMethod(true)
.isVarArgs(false);
}
@AutoValue.Builder
static abstract class Builder {
abstract Builder name(String name);
abstract Builder returnType(TypeMirror returnTypeElement);
abstract Builder publicMethod(boolean publicMethod);
abstract Builder passedParameters(Iterable<Parameter> passedParameters);
abstract Builder isVarArgs(boolean isVarargs);
abstract ImplementationMethodDescriptor build();
Builder publicMethod() {
return publicMethod(true);
}
}
}
|
Remove useless javadoc that produces warning.
|
package com.netcetera.trema.eclipse.exporting;
import java.io.Writer;
import org.eclipse.core.runtime.IProgressMonitor;
import com.netcetera.trema.core.exporting.TremaCSVPrinter;
/**
* Subclass of <code>CSVPrinter</code> to support progress monitors,
* since a CSV export has turned out to be rather a time consuming
* operation.
*/
public class MonitoringTremaCSVPrinter extends TremaCSVPrinter {
private final IProgressMonitor monitor;
/**
* Create a printer that will print values to the given
* stream. Comments will be
* written using the default comment character '#'.
* @param out the output writer to use
* @param separator the csv separator to use
* @param monitor the monitor to use while writing
*/
public MonitoringTremaCSVPrinter(Writer out, char separator, IProgressMonitor monitor) {
super(out, separator);
this.monitor = monitor;
}
public void monitorBeginTask(int totalwork) {
if (monitor != null) {
monitor.beginTask("Exporting...", totalwork);
}
}
public void monitorWorked(int work) {
if (monitor != null) {
monitor.worked(work);
}
}
}
|
package com.netcetera.trema.eclipse.exporting;
import java.io.Writer;
import org.eclipse.core.runtime.IProgressMonitor;
import com.netcetera.trema.core.exporting.TremaCSVPrinter;
/**
* Subclass of <code>CSVPrinter</code> to support progress monitors,
* since a CSV export has turned out to be rather a time consuming
* operation.
*/
public class MonitoringTremaCSVPrinter extends TremaCSVPrinter {
private final IProgressMonitor monitor;
/**
* Create a printer that will print values to the given
* stream. Comments will be
* written using the default comment character '#'.
* @param out the output writer to use
* @param separator the csv separator to use
* @param monitor the monitor to use while writing
*/
public MonitoringTremaCSVPrinter(Writer out, char separator, IProgressMonitor monitor) {
super(out, separator);
this.monitor = monitor;
}
/** {@inheritDoc} */
public void monitorBeginTask(int totalwork) {
if (monitor != null) {
monitor.beginTask("Exporting...", totalwork);
}
}
/** {@inheritDoc} */
public void monitorWorked(int work) {
if (monitor != null) {
monitor.worked(work);
}
}
}
|
Add b1 to version number; add more keywords
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import setuptools
setuptools.setup(
name="jack-select",
version="0.1b1",
url="https://github.com/SpotlightKid/jack-select",
author="Christopher Arndt",
author_email="chris@chrisarndt.de",
description="A systray app to set the JACK configuration from QJackCtl "
"presets via DBus",
keywords="JACK,systray,GTK,DBus,audio",
packages=setuptools.find_packages(),
include_package_data=True,
install_requires=[
'PyGObject',
'dbus-python',
'pyxdg'
],
entry_points = {
'console_scripts': [
'jack-select = jackselect.jackselect:main',
]
},
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: End users',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Environment :: X11 Applications :: GTK',
'Topic :: Multimedia :: Sound/Audio'
],
)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import setuptools
setuptools.setup(
name="jack-select",
version="0.1",
url="https://github.com/SpotlightKid/jack-select",
author="Christopher Arndt",
author_email="chris@chrisarndt.de",
description="A systray app to set the JACK configuration from QJackCtl "
"presets via DBus",
keywords="JACK,systray,GTK",
packages=setuptools.find_packages(),
include_package_data=True,
install_requires=[
'PyGObject',
'dbus-python',
'pyxdg'
],
entry_points = {
'console_scripts': [
'jack-select = jackselect.jackselect:main',
]
},
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: End users',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Environment :: X11 Applications :: GTK',
'Topic :: Multimedia :: Sound/Audio'
],
)
|
CRM-157: Add support of multiAddress to Contact API
- added processing of contact addresses
- added cascade validation to contact API form type
- small code style fixes
|
<?php
namespace Oro\Bundle\AddressBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use BeSimple\SoapBundle\ServiceDefinition\Annotation as Soap;
use JMS\Serializer\Annotation\Exclude;
use Oro\Bundle\AddressBundle\Entity\AddressType;
/**
* Address
*
* @ORM\Table("oro_address_typed")
* @ORM\HasLifecycleCallbacks()
* @ORM\Entity(repositoryClass="Oro\Bundle\AddressBundle\Entity\Repository\AddressRepository")
*/
class TypedAddress extends AddressBase
{
/**
* @var AddressType
*
* @ORM\ManyToOne(targetEntity="AddressType")
* @Soap\ComplexType("string", nillable=true)
*/
protected $type;
/**
* @var \Oro\Bundle\FlexibleEntityBundle\Model\AbstractFlexibleValue[]
*
* @ORM\OneToMany(targetEntity="Oro\Bundle\AddressBundle\Entity\Value\AddressValue", mappedBy="entity", cascade={"persist", "remove"}, orphanRemoval=true)
* @Exclude
*/
protected $values;
/**
* @param AddressType $type
* @return TypedAddress
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* @return AddressType
*/
public function getType()
{
return $this->type;
}
}
|
<?php
namespace Oro\Bundle\AddressBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use BeSimple\SoapBundle\ServiceDefinition\Annotation as Soap;
use JMS\Serializer\Annotation\Exclude;
use Oro\Bundle\AddressBundle\Entity\AddressType;
/**
* Address
*
* @ORM\Table("oro_address_typed")
* @ORM\HasLifecycleCallbacks()
* @ORM\Entity(repositoryClass="Oro\Bundle\AddressBundle\Entity\Repository\AddressRepository")
*/
class TypedAddress extends AddressBase
{
/**
* @var integer
*
* @ORM\ManyToOne(targetEntity="AddressType")
* @Soap\ComplexType("string", nillable=true)
*/
protected $type;
/**
* @var \Oro\Bundle\FlexibleEntityBundle\Model\AbstractFlexibleValue[]
*
* @ORM\OneToMany(targetEntity="Oro\Bundle\AddressBundle\Entity\Value\AddressValue", mappedBy="entity", cascade={"persist", "remove"}, orphanRemoval=true)
* @Exclude
*/
protected $values;
/**
* @param AddressType $type
* @return TypedAddress
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* @return AddressType
*/
public function getType()
{
return $this->type;
}
}
|
Remove this useless assignment to local variable "success".
|
package hu.bme.mit.spaceship;
import java.util.Random;
/**
* Class storing and managing the torpedos of a ship
*/
public class TorpedoStore {
private int torpedos = 0;
private Random generator = new Random();
public TorpedoStore(int numberOfTorpedos){
this.torpedos = numberOfTorpedos;
}
public boolean fire(int numberOfTorpedos){
if(numberOfTorpedos < 1 || numberOfTorpedos > this.torpedos){
throw new IllegalArgumentException("numberOfTorpedos");
}
boolean success;
//simulate random overheating of the launcher bay which prevents firing
double r = generator.nextDouble();
if (r > 0.1) {
// successful firing
this.torpedos -= numberOfTorpedos;
success = true;
} else {
// failure
success = false;
}
return success;
}
public boolean isEmpty(){
return this.torpedos <= 0;
}
public int getNumberOfTorpedos() {
return this.torpedos;
}
}
|
package hu.bme.mit.spaceship;
import java.util.Random;
/**
* Class storing and managing the torpedos of a ship
*/
public class TorpedoStore {
private int torpedos = 0;
private Random generator = new Random();
public TorpedoStore(int numberOfTorpedos){
this.torpedos = numberOfTorpedos;
}
public boolean fire(int numberOfTorpedos){
if(numberOfTorpedos < 1 || numberOfTorpedos > this.torpedos){
throw new IllegalArgumentException("numberOfTorpedos");
}
boolean success = false;
//simulate random overheating of the launcher bay which prevents firing
double r = generator.nextDouble();
if (r > 0.1) {
// successful firing
this.torpedos -= numberOfTorpedos;
success = true;
} else {
// failure
success = false;
}
return success;
}
public boolean isEmpty(){
return this.torpedos <= 0;
}
public int getNumberOfTorpedos() {
return this.torpedos;
}
}
|
Print the return value of onClose if it's not null
|
#!/usr/bin/env node
'use strict';
let [,, onLineSrc, onCloseSrc ] = process.argv;
let onLine = eval(onLineSrc) || (line => line);
let onClose = eval(onCloseSrc) || (() => undefined);
let env = new Set();
require('readline')
.createInterface({
input: process.stdin
})
.on('line', line => {
let columns = line.match(/('(\\'|[^'])*'|"(\\"|[^"])*"|\/(\\\/|[^\/])*\/|(\\ |[^ ])+|[\w-]+)/g) || [];
let value = onLine(line, columns, env);
if (value != null) {
console.log(value);
}
})
.on('close', () => {
let value = onClose(env);
if (value != null) {
console.log(value);
}
});
|
#!/usr/bin/env node
'use strict';
let [,, onLineSrc, onCloseSrc ] = process.argv;
let onLine = eval(onLineSrc) || (line => line);
let onClose = eval(onCloseSrc) || (() => undefined);
let env = new Set();
require('readline')
.createInterface({
input: process.stdin
})
.on('line', line => {
let columns = line.match(/('(\\'|[^'])*'|"(\\"|[^"])*"|\/(\\\/|[^\/])*\/|(\\ |[^ ])+|[\w-]+)/g) || [];
let value = onLine(line, columns, env);
if (value != null) {
console.log(value);
}
})
.on('close', () => {
onClose(env);
});
|
Add some shortcuts we currently have in tddbin.
|
var $ = document.getElementById.bind(document);
var exampleTests = require('./example-tests');
var Main = require('../src/main/main-controller');
var providedByAceEditor = function() {/* noop() */};
var isMac = navigator.platform.indexOf('Mac') === 0;
var metaKey = isMac ? 'Meta' : 'Control';
var shortcuts = [
[[metaKey, 'S'], executeTestCode, 'Save+Run'],
[[metaKey, 'D'], providedByAceEditor(), 'Delete line'],
[[metaKey, 'Shift', 'D'], providedByAceEditor(), 'Duplicate line'],
[[metaKey, '/'], providedByAceEditor(), 'Comment in/out line'],
[[metaKey, 'I', 'E'], providedByAceEditor(), '???'],
[[metaKey, 'I', 'I'], providedByAceEditor(), '???'],
[[metaKey, 'I', 'E', 'E'], providedByAceEditor(), '???'],
[['Shift', 'F6'], refactoringRename, 'Rename (refactoring)']
];
var main = new Main($('tddbin'), {
initialContent: exampleTests.simplePassingTestCode,
iframeSrcUrl: '../src/test-runner/mocha/spec-runner.html',
shortcuts: shortcuts
});
function executeTestCode() {
main.runEditorContent();
}
function refactoringRename() {
main.placeCursorsForRenaming();
}
|
var $ = document.getElementById.bind(document);
var exampleTests = require('./example-tests');
var Main = require('../src/main/main-controller');
var providedByAceEditor = function() {/* noop() */};
var isMac = navigator.platform.indexOf('Mac') === 0;
var metaKey = isMac ? 'Meta' : 'Control';
var shortcuts = [
[[metaKey, 'S'], executeTestCode, 'Save+Run'],
[[metaKey, 'D'], providedByAceEditor(), 'Delete line'],
[[metaKey, 'Shift', 'D'], providedByAceEditor(), 'Duplicate line'],
[[metaKey, '/'], providedByAceEditor(), 'Comment in/out line'],
[['Shift', 'F6'], refactoringRename, 'Rename (refactoring)']
];
var main = new Main($('tddbin'), {
initialContent: exampleTests.simplePassingTestCode,
iframeSrcUrl: '../src/test-runner/mocha/spec-runner.html',
shortcuts: shortcuts
});
function executeTestCode() {
main.runEditorContent();
}
function refactoringRename() {
main.placeCursorsForRenaming();
}
|
Return readable date format in toString
|
<?php
namespace Opifer\EavBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* DateTimeValue
*
* @ORM\Entity
*/
class DateTimeValue extends Value
{
/**
* Turn value into string for form field value purposes
*
* @return string
*/
public function __toString()
{
return date('d-m-Y H:i:s', $this->getTimestamp());
}
/**
* Get value
*
* @return \DateTime
*/
public function getValue()
{
$datetime = new \DateTime();
return $datetime->setTimestamp($this->value);
}
/**
* Set value
*
* @param \DateTime $value
*
* @return DateTimeValue
*/
public function setValue($value)
{
$this->value = $value->getTimestamp();
return $this;
}
/**
* Get raw value
*
* @return string
*/
public function getTimestamp()
{
return $this->value;
}
}
|
<?php
namespace Opifer\EavBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* DateTimeValue
*
* @ORM\Entity
*/
class DateTimeValue extends Value
{
/**
* Turn value into string for form field value purposes
*
* @return string
*/
public function __toString()
{
return (string) $this->getTimestamp();
}
/**
* Get value
*
* @return \DateTime
*/
public function getValue()
{
$datetime = new \DateTime();
return $datetime->setTimestamp($this->value);
}
/**
* Set value
*
* @param \DateTime $value
*
* @return DateTimeValue
*/
public function setValue($value)
{
$this->value = $value->getTimestamp();
return $this;
}
/**
* Get raw value
*
* @return string
*/
public function getTimestamp()
{
return $this->value;
}
}
|
Tidy up the unit test a little.
|
package com.nullprogram.guide;
import com.nullprogram.guide.Arch;
import com.nullprogram.guide.NativeGuide;
import junit.framework.TestCase;
public class NativeGuideTest extends TestCase {
public final void testIsArchitecture() {
try {
NativeGuide.prepare(Arch.LINUX_32, "linux32/libguide.so");
NativeGuide.prepare(Arch.LINUX_64, "linux64/libguide.so");
NativeGuide.prepare(Arch.WINDOWS_32, "windows32/guide.dll");
NativeGuide.prepare(Arch.WINDOWS_64, "windows64/guide.dll");
System.loadLibrary("guide");
} catch (java.io.IOException e) {
fail("Could not prepare library: " + e);
}
}
}
|
package com.nullprogram.guide;
import com.nullprogram.guide.Arch;
import com.nullprogram.guide.NativeGuide;
import junit.framework.TestCase;
public class NativeGuideTest extends TestCase {
public final void testIsArchitecture() {
String root = "/com/nullprogram/guide/";
try {
NativeGuide.prepare(Arch.LINUX_32, root + "linux32/libguide.so");
NativeGuide.prepare(Arch.LINUX_64, root + "linux64/libguide.so");
NativeGuide.prepare(Arch.WINDOWS_32, root + "windows32/guide.dll");
NativeGuide.prepare(Arch.WINDOWS_64, root + "windows64/guide.dll");
System.loadLibrary("guide");
} catch (java.io.IOException e) {
fail("Could not prepare library: " + e);
}
}
}
|
Add a missing required param to deployment create
|
<?php
/**
* @file
* Contains \Eloqua\Api\Assets\Email\Deployment.
*/
namespace Eloqua\Api\Assets\Email;
use Eloqua\Api\AbstractApi;
use Eloqua\Api\CreatableInterface;
use Eloqua\Api\ReadableInterface;
use Eloqua\Api\SearchableInterface;
use Eloqua\Exception\InvalidArgumentException;
/**
* Eloqua e-mail group.
*/
class Deployment extends AbstractApi implements CreatableInterface, ReadableInterface, SearchableInterface {
/**
* {@inheritdoc}
*/
public function search($search, array $options = array()) {
return $this->get('assets/email/deployments', array_merge(array(
'search' => $search,
), $options));
}
/**
* {@inheritdoc}
*/
public function show($id, $depth = 'complete', $extensions = null) {
return $this->get('assets/email/deployment/' . rawurlencode($id), array(
'depth' => $depth,
'extensions' => $extensions,
));
}
/**
* {@inheritdoc}
*/
public function create($data) {
// Validate the request before sending it.
$required = array('name', 'email', 'contacts', 'type');
foreach ($required as $key) {
if (!array_key_exists($key, $data) || empty($data[$key])) {
throw new InvalidArgumentException("You must specify a non-empty value for $key.");
}
}
return $this->post('assets/email/deployment', $data);
}
}
|
<?php
/**
* @file
* Contains \Eloqua\Api\Assets\Email\Deployment.
*/
namespace Eloqua\Api\Assets\Email;
use Eloqua\Api\AbstractApi;
use Eloqua\Api\CreatableInterface;
use Eloqua\Api\ReadableInterface;
use Eloqua\Api\SearchableInterface;
use Eloqua\Exception\InvalidArgumentException;
/**
* Eloqua e-mail group.
*/
class Deployment extends AbstractApi implements CreatableInterface, ReadableInterface, SearchableInterface {
/**
* {@inheritdoc}
*/
public function search($search, array $options = array()) {
return $this->get('assets/email/deployments', array_merge(array(
'search' => $search,
), $options));
}
/**
* {@inheritdoc}
*/
public function show($id, $depth = 'complete', $extensions = null) {
return $this->get('assets/email/deployment/' . rawurlencode($id), array(
'depth' => $depth,
'extensions' => $extensions,
));
}
/**
* {@inheritdoc}
*/
public function create($data) {
// Validate the request before sending it.
$required = array('name', 'email', 'contacts');
foreach ($required as $key) {
if (!array_key_exists($key, $data) || empty($data[$key])) {
throw new InvalidArgumentException("You must specify a non-empty value for $key.");
}
}
return $this->post('assets/email/deployment', $data);
}
}
|
Use patch.object for python 2 compat
|
from os.path import join
import sublime
import sys
from unittest import TestCase
from unittest.mock import patch
version = sublime.version()
try:
from libsass import pathutils
except ImportError:
from sublime_libsass.libsass import pathutils
class TestPathutils(TestCase):
def test_subpaths(self):
path = join('/foo','bar','baz')
exprmt = pathutils.subpaths(path)
expect = [ join('/foo','bar','baz'), join('/foo','bar'), join('/foo'), join('/') ]
self.assertEqual(exprmt, expect)
@patch.object(pathutils, 'os')
def test_grep_r(self, mock_os):
mock_os.walk = lambda x: [('/tmp','',['file.scss'])]
self.assertEqual(pathutils.find_type_dirs('anything', '.scss'), ['/tmp'])
self.assertEqual(pathutils.find_type_dirs('anything', ['.scss', '.sass']), ['/tmp'])
self.assertEqual(pathutils.find_type_dirs('anything', '.sass'), [])
self.assertEqual(pathutils.find_type_dirs('anything', ['.txt', '.csv']), [])
|
from os.path import join
import sublime
import sys
from unittest import TestCase
from unittest.mock import patch
version = sublime.version()
try:
from libsass import pathutils
except ImportError:
from sublime_libsass.libsass import pathutils
class TestPathutils(TestCase):
def test_subpaths(self):
path = join('/foo','bar','baz')
exprmt = pathutils.subpaths(path)
expect = [ join('/foo','bar','baz'), join('/foo','bar'), join('/foo'), join('/') ]
self.assertEqual(exprmt, expect)
@patch('libsass.pathutils.os')
def test_grep_r(self, mock_os):
mock_os.walk = lambda x: [('/tmp','',['file.scss'])]
self.assertEqual(pathutils.find_type_dirs('anything', '.scss'), ['/tmp'])
self.assertEqual(pathutils.find_type_dirs('anything', ['.scss', '.sass']), ['/tmp'])
self.assertEqual(pathutils.find_type_dirs('anything', '.sass'), [])
self.assertEqual(pathutils.find_type_dirs('anything', ['.txt', '.csv']), [])
|
Add check if string is at EOF
|
package com.swandiggy.poe4j.data.readers.value;
import com.swandiggy.poe4j.data.DatFileReader;
import lombok.extern.slf4j.Slf4j;
/**
* Read a string value. Reads an int pointer into the variable width portion of the file. Strings are null terminated
* and encoded as UTF-16LE.
*
* @author Jacob Swanson
* @since 12/15/2015
*/
@Slf4j
public class StringReader extends BaseValueReader<String> {
public StringReader() {
}
@Override
public boolean supports(Class clazz) {
return clazz == String.class;
}
@Override
protected String readInternal(DatFileReader reader, Class clazz) {
int ref = reader.getBr().readInt();
long oldPos = reader.getBr().getPosition();
long stringPos = reader.getDataOffset() + ref;
if (stringPos >= reader.getFile().length()) {
log.warn("String was at end of file eof: '{}', string ref: '{}'", reader.getFile().length(), stringPos);
return null;
}
reader.getBr().setPosition(reader.getDataOffset() + ref);
String s = reader.getBr().readString("UTF-16LE");
reader.getBr().setPosition(oldPos);
return s;
}
@Override
public int size(Class clazz) {
return 4;
}
}
|
package com.swandiggy.poe4j.data.readers.value;
import com.swandiggy.poe4j.data.DatFileReader;
import org.springframework.stereotype.Service;
/**
* Read a string value. Reads an int pointer into the variable width portion of the file. Strings are null terminated
* and encoded as UTF-16LE.
*
* @author Jacob Swanson
* @since 12/15/2015
*/
public class StringReader extends BaseValueReader<String> {
public StringReader() {
}
@Override
public boolean supports(Class clazz) {
return clazz == String.class;
}
@Override
protected String readInternal(DatFileReader reader, Class clazz) {
int ref = reader.getBr().readInt();
long oldPos = reader.getBr().getPosition();
reader.getBr().setPosition(reader.getDataOffset() + ref);
String s = reader.getBr().readString("UTF-16LE");
reader.getBr().setPosition(oldPos);
return s;
}
@Override
public int size(Class clazz) {
return 4;
}
}
|
Fix to work in Windows
https://github.com/nulab/backlog4j/issues/49
|
package com.nulabinc.backlog4j.internal.json;
import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.TimeZone;
/**
* @author nulab-inc
*/
public abstract class AbstractJSONImplTest {
protected InternalFactoryJSONImpl factory = new InternalFactoryJSONImpl();
protected TimeZone timeZone = TimeZone.getTimeZone("Asia/Tokyo");
protected String getJsonString(String resourceFilePath) throws IOException {
InputStreamReader r = null;
try {
r = new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(resourceFilePath), "UTF-8");
CharArrayWriter writer = new CharArrayWriter();
char buff[] = new char[4096];
int size;
while ((size = r.read(buff)) > 0) {
writer.write(buff, 0, size);
}
return writer.toString();
} finally {
if (r != null) {
r.close();
}
}
}
}
|
package com.nulabinc.backlog4j.internal.json;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.TimeZone;
/**
* @author nulab-inc
*/
public abstract class AbstractJSONImplTest {
protected InternalFactoryJSONImpl factory = new InternalFactoryJSONImpl();
protected TimeZone timeZone = TimeZone.getTimeZone("Asia/Tokyo") ;
protected String getJsonString(String resourceFilePath) throws IOException {
String fileName = SpaceJSONImplTest.class.getClassLoader().getResource(resourceFilePath).getPath();
byte[] fileContentBytes = Files.readAllBytes(Paths.get(fileName));
String fileContentStr = new String(fileContentBytes, StandardCharsets.UTF_8);
return fileContentStr;
}
}
|
Fix content widget slate-editor toolbar z-index
|
export default {
button: {
borderRight: '1px solid #fff'
},
dropdown: {
position: 'relative',
top: 1,
backgroundColor: 'white',
height: 38,
paddingLeft: 20,
border: '3px solid #0275d8',
color: '#0275d8',
margin: '0',
WebkitAppearance: 'none',
padding: '0 10px 0 15px'
},
input: {
position: 'relative',
top: 1,
backgroundColor: 'white',
borderRadius: 0,
height: 16,
margin: 0,
color: '#0275d8',
border: '3px solid #0275d8'
},
toolbar: {
position: 'absolute',
top: 0,
left: 0,
width: '100%',
zIndex: 5,
display: 'none'
},
overlay: {
position: 'absolute',
top: 0,
bottom: 0,
left: 0,
right: 0,
backgroundColor: '#222',
color: '#fff',
borderRadius: 3,
opacity: '.82',
fontWeight: 300,
fontSize: '2.15rem',
cursor: 'pointer',
display: 'none'
}
}
|
export default {
button: {
borderRight: '1px solid #fff'
},
dropdown: {
position: 'relative',
top: 1,
backgroundColor: 'white',
height: 38,
paddingLeft: 20,
border: '3px solid #0275d8',
color: '#0275d8',
margin: '0',
WebkitAppearance: 'none',
padding: '0 10px 0 15px'
},
input: {
position: 'relative',
top: 1,
backgroundColor: 'white',
borderRadius: 0,
height: 16,
margin: 0,
color: '#0275d8',
border: '3px solid #0275d8'
},
toolbar: {
position: 'absolute',
top: 0,
left: 0,
width: '100%',
zIndex: 4,
display: 'none'
},
overlay: {
position: 'absolute',
top: 0,
bottom: 0,
left: 0,
right: 0,
backgroundColor: '#222',
color: '#fff',
borderRadius: 3,
opacity: '.82',
fontWeight: 300,
fontSize: '2.15rem',
cursor: 'pointer',
display: 'none'
}
}
|
Add CodeWithCopy component to module exports
Connects to #1289
change-type: patch
|
import { default as Banner } from './components/Banner'
import { default as Button } from './components/Button'
import { default as CodeWithCopy } from './components/CodeWithCopy'
import { default as DeleteButton } from './components/DeleteButton'
import { default as DeviceStatusGauge } from './components/DeviceStatusGauge'
import { default as Divider } from './components/Divider'
import { default as Filters } from './components/Filters'
import { default as Fixed } from './components/Fixed'
import { default as Input } from './components/Input'
import { default as Modal } from './components/Modal'
import { default as PineTypes } from './components/PineTypes'
import { default as ProgressBar } from './components/ProgressBar'
import { default as Provider } from './components/Provider'
import { default as SchemaSieve } from './components/Filters/SchemaSieve'
import { default as Select } from './components/Select'
import { default as Text } from './components/Text'
import { default as Textarea } from './components/Textarea'
import { Flex, Box } from './components/Grid'
export {
Banner,
Box,
Button,
CodeWithCopy,
DeleteButton,
DeviceStatusGauge,
Divider,
Filters,
Fixed,
Flex,
Input,
Modal,
PineTypes,
Provider,
ProgressBar,
SchemaSieve,
Select,
Text,
Textarea
}
|
import { default as Banner } from './components/Banner'
import { default as Button } from './components/Button'
import { default as DeleteButton } from './components/DeleteButton'
import { default as DeviceStatusGauge } from './components/DeviceStatusGauge'
import { default as Divider } from './components/Divider'
import { default as Filters } from './components/Filters'
import { default as Fixed } from './components/Fixed'
import { default as Input } from './components/Input'
import { default as Modal } from './components/Modal'
import { default as PineTypes } from './components/PineTypes'
import { default as ProgressBar } from './components/ProgressBar'
import { default as Provider } from './components/Provider'
import { default as SchemaSieve } from './components/Filters/SchemaSieve'
import { default as Select } from './components/Select'
import { default as Text } from './components/Text'
import { default as Textarea } from './components/Textarea'
import { Flex, Box } from './components/Grid'
export {
Banner,
Box,
Button,
DeleteButton,
DeviceStatusGauge,
Divider,
Filters,
Fixed,
Flex,
Input,
Modal,
PineTypes,
Provider,
ProgressBar,
SchemaSieve,
Select,
Text,
Textarea
}
|
Hide overlay when undo/redoing changes
|
import { win, isIframe } from 'classes/helpers';
import { eventBus } from './eventbus';
import UndoStack from 'classes/UndoStack';
const trackedMutations = {
updateFieldValue: 'Update to block field',
addBlock: 'Added block to page',
deleteBlock: 'Deleted block on page'
};
const undoStack = new UndoStack({ lock: true });
const undoRedo = store => {
if(isIframe) {
return;
}
undoStack.setUndoRedo((pageData) => {
store.commit('setPage', JSON.parse(pageData));
eventBus.$emit('block:hideOverlay', null);
});
undoStack.setCallback(({ canUndo, canRedo }) => {
store.commit('updateUndoRedo', { canUndo, canRedo });
});
store.subscribe((mutation, state) => {
if(!trackedMutations[mutation.type]) {
return;
}
undoStack.add(state.page.pageData);
});
};
export default undoRedo;
export const undoStackInstance = isIframe ?
win.top.astroUndoStack : (win.astroUndoStack = undoStack);
|
import { win, isIframe } from 'classes/helpers';
import UndoStack from 'classes/UndoStack';
const trackedMutations = {
updateFieldValue: 'Update to block field',
addBlock: 'Added block to page',
deleteBlock: 'Deleted block on page'
};
const undoStack = new UndoStack({ lock: true });
const undoRedo = store => {
if(isIframe) {
return;
}
undoStack.setUndoRedo(
(pageData) => store.commit('setPage', JSON.parse(pageData))
);
undoStack.setCallback(({ canUndo, canRedo }) => {
store.commit('updateUndoRedo', { canUndo, canRedo });
});
store.subscribe((mutation, state) => {
if(!trackedMutations[mutation.type]) {
return;
}
undoStack.add(state.page.pageData);
});
};
export default undoRedo;
export const undoStackInstance = isIframe ?
win.top.astroUndoStack : (win.astroUndoStack = undoStack);
|
Add style to show selected item
|
var Menu;
Menu = function(title, items, x, y, width, height) {
'use strict';
this.title = title;
this.items = items;
this.selectedItem = items[0];
this.x = x;
this.y = y;
this.width = width;
this.height = height;
};
Menu.prototype.render = function(context) {
'use strict';
var i, textMeasure, itemY;
itemY = 50;
// Background
context.fillStyle = '#000000';
context.fillRect(0, 0, this.width, this.height);
// Draw title
context.font = 'bold 80px Monaco, Courier New, monospace';
context.fillStyle = '#FFFFFF';
textMeasure = context.measureText(this.title);
context.fillText(this.title, (this.width / 2) - (textMeasure.width / 2), 100);
// Draw items
for (i = 0; i < this.items.length; i++) {
if (this.items[i] === this.selectedItem) {
context.font = 'bold 80px Monaco, Courier New, monospace';
context.fillStyle = '#FFCC33';
} else {
context.font = 'bold 60px Monaco, Courier New, monospace';
context.fillStyle = '#FFFFFF';
}
textMeasure = context.measureText(this.items[i]);
context.fillText(this.items[i], (this.width / 2) -
(textMeasure.width / 2), 200 + itemY);
itemY += 100;
}
};
Menu.prototype.update = function() {
};
|
var Menu;
Menu = function(title, items, x, y, width, height) {
'use strict';
this.title = title;
this.items = items;
this.x = x;
this.y = y;
this.width = width;
this.height = height;
};
Menu.prototype.render = function(context) {
'use strict';
var i, textMeasure, itemY;
itemY = 50;
// Background
context.fillStyle = '#000000';
context.fillRect(0, 0, this.width, this.height);
// Draw title
context.font = 'bold 80px Monaco, Courier New, monospace';
context.fillStyle = '#FFFFFF';
textMeasure = context.measureText(this.title);
context.fillText(this.title, (this.width / 2) - (textMeasure.width / 2), 100);
// Draw items
for (i = 0; i < this.items.length; i++) {
context.font = 'bold 60px Monaco, Courier New, monospace';
context.fillStyle = '#FFFFFF';
textMeasure = context.measureText(this.items[i]);
context.fillText(this.items[i], (this.width / 2) -
(textMeasure.width / 2), 200 + itemY);
itemY += 100;
}
};
Menu.prototype.update = function() {
};
|
Use Computer Modern for \LaTeX macro
Source Sans pro (and most othe sans-serif fonts) render the LaTeX macro
pretty weirdly, so the classic Computer Modern should be okay here. It
may wind up being an odd contrast in an otherwise sans-serif document
though, so this may eventually get reverted!
|
from jinja2._compat import text_type
import re
def do_right(value, width=80):
"""Right-justifies the value in a field of a given width."""
return text_type(value).rjust(width)
_LATEX_SUBS = (
(re.compile(r'\\'), r'\\textbackslash'),
(re.compile(r'([{}_#%&$])'), r'\\\1'),
(re.compile(r'~'), r'\~{}'),
(re.compile(r'\^'), r'\^{}'),
(re.compile(r'"'), r"''"),
(re.compile(r'\.\.\.+'), r'\\ldots'),
(re.compile(r'&'), r'&'),
(re.compile(r'LaTeX'), r'\\textrm{\\LaTeX}')
)
def escape_tex(value):
"""
Escapes TeX characters to avoid breaking {La,Lua,Xe}Tex compilers.
Kang'd (with permission!) from http://flask.pocoo.org/snippets/55/
"""
newval = value
for pattern, replacement in _LATEX_SUBS:
newval = pattern.sub(replacement, newval)
return newval
|
from jinja2._compat import text_type
import re
def do_right(value, width=80):
"""Right-justifies the value in a field of a given width."""
return text_type(value).rjust(width)
_LATEX_SUBS = (
(re.compile(r'\\'), r'\\textbackslash'),
(re.compile(r'([{}_#%&$])'), r'\\\1'),
(re.compile(r'~'), r'\~{}'),
(re.compile(r'\^'), r'\^{}'),
(re.compile(r'"'), r"''"),
(re.compile(r'\.\.\.+'), r'\\ldots'),
(re.compile(r'&'), r'&'),
(re.compile(r'LaTeX'), r'\\LaTeX')
)
def escape_tex(value):
"""
Escapes TeX characters to avoid breaking {La,Lua,Xe}Tex compilers.
Kang'd (with permission!) from http://flask.pocoo.org/snippets/55/
"""
newval = value
for pattern, replacement in _LATEX_SUBS:
newval = pattern.sub(replacement, newval)
return newval
|
Clean up of style and checksum warnings.
|
// Copyright (c) 2010, www.andrew-eells.com. All rights reserved.
package com.andrew_eells.persistence.service;
import com.andrew_eells.persistence.infrastructure.query.QuerySpecification;
import java.util.List;
/**
* Standardised database repository access.
*/
public interface PersistenceService<PersistentStrategy>
{
/**
* Persist new object.
*
* @param object New object.
*/
void create(final PersistentStrategy object);
/**
* Read unique result object.
*
* @param querySpecification Query specification.
* @return Unique result or <code>null</code> if none exists.
*/
PersistentStrategy readUnique(final QuerySpecification querySpecification);
/**
* Read collection of result objects.
*
* @param querySpecification Query specification.
* @return Collection of results or empty collection if none exists.
*/
List<PersistentStrategy> readList(final QuerySpecification querySpecification);
/**
* Update existing object.
*
* @param object Object to be updated.
*/
void update(final PersistentStrategy object);
/**
* Delete existing object.
*
* @param object Object to be deleted.
*/
void delete(final PersistentStrategy object);
}
|
// Copyright (c) 2010, www.andrew-eells.com. All rights reserved.
package com.andrew_eells.persistence.service;
import com.andrew_eells.persistence.infrastructure.query.QuerySpecification;
import java.util.List;
/**
* Standardised database repository access.
*/
public interface PersistenceService<PersistentStrategy>
{
/**
* Persist new object.
*
* @param object New object.
*/
void create(final PersistentStrategy object);
/**
* Read unique result object.
*
* @param querySpecification Query specification.
* @return Unique result or <code>null</code> if none exists.
*/
PersistentStrategy readUnique(final QuerySpecification querySpecification);
/**
* Read collection of result objects.
*
* @param querySpecification Query specification.
* @return Collection of results or empty collection if none exists.
*/
List<PersistentStrategy> readList(final QuerySpecification querySpecification);
/**
* Update existing object.
*
* @param object Object to be updated.
* @return Updated object.
*/
void update(final PersistentStrategy object);
/**
* Delete existing object.
*
* @param object Object to be deleted.
*/
void delete(final PersistentStrategy object);
}
|
Validate on changing from Total to Valuation/Valuation&Total when add_deduct_tax is 'Deduct'
|
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt
cur_frm.cscript.tax_table = "Purchase Taxes and Charges";
{% include "erpnext/public/js/controllers/accounts.js" %}
frappe.ui.form.on("Purchase Taxes and Charges", "add_deduct_tax", function(doc, cdt, cdn) {
var d = locals[cdt][cdn];
if(!d.category && d.add_deduct_tax) {
msgprint(__("Please select Category first"));
d.add_deduct_tax = '';
}
else if(d.category != 'Total' && d.add_deduct_tax == 'Deduct') {
msgprint(__("Cannot deduct when category is for 'Valuation' or 'Valuation and Total'"));
d.add_deduct_tax = '';
}
refresh_field('add_deduct_tax', d.name, 'taxes');
});
frappe.ui.form.on("Purchase Taxes and Charges", "category", function(doc, cdt, cdn) {
var d = locals[cdt][cdn];
if (d.category != 'Total' && d.add_deduct_tax == 'Deduct') {
msgprint(__("Cannot deduct when category is for 'Valuation' or 'Vaulation and Total'"));
d.add_deduct_tax = '';
}
refresh_field('add_deduct_tax', d.name, 'taxes');
})
|
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt
cur_frm.cscript.tax_table = "Purchase Taxes and Charges";
{% include "erpnext/public/js/controllers/accounts.js" %}
frappe.ui.form.on("Purchase Taxes and Charges", "add_deduct_tax", function(doc, cdt, cdn) {
var d = locals[cdt][cdn];
if(!d.category && d.add_deduct_tax) {
msgprint(__("Please select Category first"));
d.add_deduct_tax = '';
}
else if(d.category != 'Total' && d.add_deduct_tax == 'Deduct') {
msgprint(__("Cannot deduct when category is for 'Valuation' or 'Valuation and Total'"));
d.add_deduct_tax = '';
}
refresh_field('add_deduct_tax', d.name, 'taxes');
});
|
Add nospacing attribute to Grid
|
import m from 'mithril';
import attributes from './attributes';
export let Grid = {
view(ctrl, args, ...children) {
args = args || {};
let attr = attributes(args);
let {nospacing} = args;
attr.class.push('mdl-grid');
if (nospacing) attr.class.push('mdl-grid--no-spacing');
return <div {...attr}>{children}</div>;
}
};
export let Cell = {
view(ctrl, args, ...children) {
args = args || {};
let attr = attributes(args);
let {align, width, phone, tablet, desktop, nophone, notablet, nodesktop} = args;
attr.class.push('mdl-cell');
if(align) attr.class.push(`mdl-cell--${align}`);
if(width) attr.class.push(`mdl-cell--${width}-col`);
if(phone) attr.class.push(`mdl-cell--${phone}-col-phone`);
if(tablet) attr.class.push(`mdl-cell--${tablet}-col-tablet`);
if(desktop) attr.class.push(`mdl-cell--${desktop}-col-desktop`);
if(nophone) attr.class.push('mdl-cell--hide-phone');
if(notablet) attr.class.push('mdl-cell--hide-tablet');
if(nodesktop) attr.class.push('mdl-cell--hide-desktop');
return <div {...attr}>{children}</div>;
}
};
|
import m from 'mithril';
import attributes from './attributes';
export let Grid = {
view(ctrl, args, ...children) {
args = args || {};
let attr = attributes(args);
attr.class.push('mdl-grid');
return <div {...attr}>{children}</div>;
}
};
export let Cell = {
view(ctrl, args, ...children) {
args = args || {};
let attr = attributes(args);
let {align, width, phone, tablet, desktop, nophone, notablet, nodesktop} = args;
attr.class.push('mdl-cell');
if(align) attr.class.push(`mdl-cell--${align}`);
if(width) attr.class.push(`mdl-cell--${width}-col`);
if(phone) attr.class.push(`mdl-cell--${phone}-col-phone`);
if(tablet) attr.class.push(`mdl-cell--${tablet}-col-tablet`);
if(desktop) attr.class.push(`mdl-cell--${desktop}-col-desktop`);
if(nophone) attr.class.push('mdl-cell--hide-phone');
if(notablet) attr.class.push('mdl-cell--hide-tablet');
if(nodesktop) attr.class.push('mdl-cell--hide-desktop');
return <div {...attr}>{children}</div>;
}
};
|
[IMP] Test expecting results also since the begining
|
(function() {
'use strict';
openerp.Tour.register({
id: 'test_instance_introspection',
name: 'Complete a basic order trough the Front-End',
path: '/instance_introspection',
mode: 'test',
steps: [
{
title: 'Wait for the main screen',
waitFor: 'h3:contains("Addons Paths"),#accordion.results',
element: '.btn-reload',
wait: 200,
},
{
title: 'Load Repositories',
waitFor: '#accordion.results',
},
],
});
})();
|
(function() {
'use strict';
openerp.Tour.register({
id: 'test_instance_introspection',
name: 'Complete a basic order trough the Front-End',
path: '/instance_introspection',
mode: 'test',
steps: [
{
title: 'Wait for the main screen',
waitFor: 'h3:contains("Addons Paths")',
element: '.btn-reload',
wait: 200,
},
{
title: 'Load Repositories',
waitFor: '#accordion.results',
},
],
});
})();
|
Trim whitespace on subtitle import
|
const parseTime = (s) => {
const re = /(\d{2}):(\d{2}):(\d{2}),(\d{3})/;
const [, hours, mins, seconds, ms] = re.exec(s);
return 3600*(+hours) + 60*(+mins) + (+seconds) + 0.001*(+ms);
};
export const parseSRT = (text) => {
const normText = text.replace(/\r\n/g, '\n'); // normalize newlines
const re = /(\d+)\n(\d{2}:\d{2}:\d{2},\d{3}) --> (\d{2}:\d{2}:\d{2},\d{3})\n((?:.+\n)+)/g;
const subs = [];
let found;
while (true) {
found = re.exec(normText);
if (!found) {
break;
}
const [full, , beginStr, endStr, lines] = found;
const begin = parseTime(beginStr);
const end = parseTime(endStr);
// TODO: Should verify that end time is >= begin time
// NOTE: We could check that indexes and/or time are in order, but don't really care
subs.push({
begin,
end,
lines: lines.trim(),
});
re.lastIndex = found.index + full.length;
}
return subs;
};
|
const parseTime = (s) => {
const re = /(\d{2}):(\d{2}):(\d{2}),(\d{3})/;
const [, hours, mins, seconds, ms] = re.exec(s);
return 3600*(+hours) + 60*(+mins) + (+seconds) + 0.001*(+ms);
};
export const parseSRT = (text) => {
const normText = text.replace(/\r\n/g, '\n'); // normalize newlines
const re = /(\d+)\n(\d{2}:\d{2}:\d{2},\d{3}) --> (\d{2}:\d{2}:\d{2},\d{3})\n((?:.+\n)+)/g;
const subs = [];
let found;
while (true) {
found = re.exec(normText);
if (!found) {
break;
}
const [full, , beginStr, endStr, lines] = found;
const begin = parseTime(beginStr);
const end = parseTime(endStr);
// TODO: Should verify that end time is >= begin time
// NOTE: We could check that indexes and/or time are in order, but don't really care
subs.push({
begin,
end,
lines,
});
re.lastIndex = found.index + full.length;
}
return subs;
};
|
Allow cache path to be overwritten on by commandline option
|
#!/usr/bin/env node
var path = require('path');
/*
* NPM modules
*/
var program = require('commander');
var yaml = require("js-yaml");
var fs = require('fs-extra');
var _ = require('lodash');
/*
* App modules
*/
var html = require('./lib/html-validator.js');
var logger = require('./lib/utils/logger.js');
/*
* Config
*/
var packageJson = require('./package.json');
/**
* Initialise
*/
(function() {
var config;
program
.version(packageJson.version)
.option('-c, --config <file>', 'set the path to the config file. defaults to ./htmldoc.yaml')
.option('-u, --urls <urls>', 'comma seperated list of urls to test')
.option('-r, --reporter <default|table>', 'The results reporter to use')
.option('-C, --cache <path>', 'Path to the HMTL cache')
.option('-v, --verbose', 'Show additional log messages')
.option('-V, --version', 'Show current version')
.parse(process.argv);
var configYaml = program.config || './config.yaml';
try {
config = yaml.safeLoad(fs.readFileSync(configYaml, 'utf8'));
} catch (e) {
logger.log(e, logger.LOG_CRITICAL);
}
config = _.defaults(config, {
reporter: program.reporter,
cache: program.cache
});
/*
* Change to the directory the config yaml
*/
process.chdir(path.dirname(configYaml));
html(config).validateAll(config.files);
})();
|
#!/usr/bin/env node
var path = require('path');
/*
* NPM modules
*/
var program = require('commander');
var yaml = require("js-yaml");
var fs = require('fs-extra');
var _ = require('lodash');
/*
* App modules
*/
var html = require('./lib/html-validator.js');
var logger = require('./lib/utils/logger.js');
/*
* Config
*/
var packageJson = require('./package.json');
/**
* Initialise
*/
(function() {
var config;
program
.version(packageJson.version)
.option('-c, --config <file>', 'set the path to the config file. defaults to ./htmldoc.yaml')
.option('-u, --urls <urls>', 'comma seperated list of urls to test')
.option('-r, --reporter <default|table>', 'The results reporter to use')
.option('-v, --verbose', 'Show additional log messages')
.option('-V, --version', 'Show current version')
.parse(process.argv);
var configYaml = program.config || './config.yaml';
try {
config = yaml.safeLoad(fs.readFileSync(configYaml, 'utf8'));
} catch (e) {
logger.log(e, logger.LOG_CRITICAL);
}
config = _.defaults(config, {
reporter: program.reporter
});
/*
* Change to the directory the config yaml
*/
process.chdir(path.dirname(configYaml));
html(config).validateAll(config.files);
})();
|
Handle case where all rows in EE table should be included.
|
const ee = require('ee')
const _ = require('lodash')
const toGeometry = aoi => {
switch (aoi.type) {
case 'POLYGON':
return polygon(aoi)
case 'EE_TABLE':
return eeTable(aoi).geometry()
}
}
const toFeatureCollection = aoi => {
switch (aoi.type) {
case 'POLYGON':
return ee.FeatureCollection([ee.Feature(polygon(aoi))])
case 'EE_TABLE':
return eeTable(aoi)
}
}
const polygon = ({path}) =>
ee.Geometry({geoJson: ee.Geometry.Polygon({coords: [path]}), geodesic: false})
const eeTable = ({id, keyColumn, key}) => {
const table = ee.FeatureCollection(id)
if (keyColumn) {
const filters = [ee.Filter.eq(keyColumn, key)]
if (_.isFinite(key))
filters.push(ee.Filter.eq(keyColumn, _.toNumber(key)))
return table
.filter(ee.Filter.or(...filters))
} else {
return table
}
}
module.exports = {toGeometry, toFeatureCollection}
|
const ee = require('ee')
const _ = require('lodash')
const toGeometry = aoi => {
switch (aoi.type) {
case 'POLYGON':
return polygon(aoi)
case 'EE_TABLE':
return eeTable(aoi).geometry()
}
}
const toFeatureCollection = aoi => {
switch (aoi.type) {
case 'POLYGON':
return ee.FeatureCollection([ee.Feature(polygon(aoi))])
case 'EE_TABLE':
return eeTable(aoi)
}
}
const polygon = ({path}) =>
ee.Geometry({geoJson: ee.Geometry.Polygon({coords: [path]}), geodesic: false})
const eeTable = ({id, keyColumn, key}) => {
const table = ee.FeatureCollection(id)
const filters = [ee.Filter.eq(keyColumn, key)]
if (_.isFinite(key))
filters.push(ee.Filter.eq(keyColumn, _.toNumber(key)))
return table
.filter(ee.Filter.or(...filters))
}
module.exports = {toGeometry, toFeatureCollection}
|
Use a placeholder png to hold the image size
|
Photo = function (doc) {
_.extend(this, doc);
};
_.extend(Photo.prototype, {
getImgTag: function (dimension) {
return {
'class': 'lazy',
src: 'data:image/gif;base64,' +
'R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==',
'data-src': _.str.sprintf(
'%s/photos/%s/%s',
Meteor.settings.public.uri.cdn,
dimension,
this.filename
),
'data-src-retina': _.str.sprintf(
'%s/photos/%s@2x/%s',
Meteor.settings.public.uri.cdn,
dimension,
this.filename
),
alt: this.title,
width: dimension,
height: dimension
};
}
});
Photos = new Mongo.Collection('Photos', {
transform: function (doc) { return new Photo(doc); }
});
|
Photo = function (doc) {
_.extend(this, doc);
};
_.extend(Photo.prototype, {
getImgTag: function (dimension) {
return {
'class': 'lazy',
'data-src': _.str.sprintf(
'%s/photos/%s/%s',
Meteor.settings.public.uri.cdn,
dimension,
this.filename
),
'data-src-retina': _.str.sprintf(
'%s/photos/%s@2x/%s',
Meteor.settings.public.uri.cdn,
dimension,
this.filename
),
alt: this.title,
width: dimension,
height: dimension
};
}
});
Photos = new Mongo.Collection('Photos', {
transform: function (doc) { return new Photo(doc); }
});
|
Make sure participants can update their sessions
|
// TODO make user specific
var OSF = 'user-osf-*';
var PARTICIPANT = 'jam-experimenter:accounts-*';
var GLOBAL = '*';
var config = [
[OSF, 'CRUD']
];
var admin = [
[OSF, 'READ'],
[OSF, 'CREATE']
];
var experiment = [
[GLOBAL, 'READ'],
[OSF, 'CREATE']
];
var session = [
[PARTICIPANT, 'CREATE'],
[PARTICIPANT, 'UPDATE'],
[OSF, 'READ']
];
var account = [
[GLOBAL, 'CREATE'],
[OSF, 'READ']
];
var profile = [
[PARTICIPANT, 'CREATE'],
[OSF, 'READ']
];
var thumbnail = [
[PARTICIPANT, 'READ'],
[OSF, 'CREATE']
];
module.exports = {
account: account,
admin: admin,
config: config,
experiment: experiment,
profile: profile,
thumbnail: thumbnail
// session: session
};
|
// TODO make user specific
var OSF = 'user-osf-*';
var PARTICIPANT = 'jam-experimenter:accounts-*';
var GLOBAL = '*';
var config = [
[OSF, 'CRUD']
];
var admin = [
[OSF, 'READ'],
[OSF, 'CREATE']
];
var experiment = [
[GLOBAL, 'READ'],
[OSF, 'CREATE']
];
var session = [
[PARTICIPANT, 'CREATE'],
[OSF, 'READ']
];
var account = [
[GLOBAL, 'CREATE'],
[OSF, 'READ']
];
var profile = [
[PARTICIPANT, 'CREATE'],
[OSF, 'READ']
];
var thumbnail = [
[PARTICIPANT, 'READ'],
[OSF, 'CREATE']
];
module.exports = {
account: account,
admin: admin,
config: config,
experiment: experiment,
profile: profile,
thumbnail: thumbnail
// session: session
};
|
Add system parameter for dev mode
|
package com.techcavern.wavetact;
import com.techcavern.wavetact.utils.CommandLineUtils;
import com.techcavern.wavetact.utils.GeneralRegistry;
import com.techcavern.wavetact.utils.IRCUtils;
import org.slf4j.impl.SimpleLogger;
@SuppressWarnings("ConstantConditions")
public class Main {
public static void main(String[] args) throws Exception {
if (!Boolean.parseBoolean(System.getProperty("dev"))) {
System.out.println("Running in production mode");
CommandLineUtils.initializeCommandlines();
CommandLineUtils.parseCommandLineArguments(args);
} else {
System.out.println("Running in developer mode");
IRCUtils.registerDevServer();
}
System.setProperty(SimpleLogger.SHOW_DATE_TIME_KEY, "true");
System.setProperty(SimpleLogger.DATE_TIME_FORMAT_KEY, "[yyyy/MM/dd HH:mm:ss]");
System.setProperty(SimpleLogger.LEVEL_IN_BRACKETS_KEY, "true");
IRCUtils.registerCommands();
IRCUtils.registerDevServer();
IRCUtils.loadSimpleActions();
IRCUtils.loadSimpleMessages();
IRCUtils.startThreads();
GeneralRegistry.WaveTact.start();
}
}
|
package com.techcavern.wavetact;
import com.techcavern.wavetact.utils.CommandLineUtils;
import com.techcavern.wavetact.utils.GeneralRegistry;
import com.techcavern.wavetact.utils.IRCUtils;
import org.slf4j.impl.SimpleLogger;
@SuppressWarnings("ConstantConditions")
public class Main {
public static void main(String[] args) throws Exception {
CommandLineUtils.initializeCommandlines();
// CommandLineUtils.parseCommandLineArguments(args);
System.out.println("Starting...");
System.setProperty(SimpleLogger.SHOW_DATE_TIME_KEY, "true");
System.setProperty(SimpleLogger.DATE_TIME_FORMAT_KEY, "[yyyy/MM/dd HH:mm:ss]");
System.setProperty(SimpleLogger.LEVEL_IN_BRACKETS_KEY, "true");
IRCUtils.registerCommands();
// IRCUtils.registerNetworks();
IRCUtils.registerDevServer();
IRCUtils.loadSimpleActions();
IRCUtils.loadSimpleMessages();
IRCUtils.startThreads();
GeneralRegistry.WaveTact.start();
}
}
|
tracking: Fix in-flight collision of two related PRs
Unfortunately, I forgot to rebase before renaming trackMixpanelEvent() and a PR
adding a new trace point was already in-flight.
More precisely:
- https://github.com/weaveworks/scope/pull/2861 renames trackMixpanelEvent()
to trackAnalysticsEent()
- https://github.com/weaveworks/scope/pull/2857 add a new
trackMixpanelEvent() call.
Each PR is fine, but with the merge of both without rebasing any, we end up
with master having a dandling call to trackMixpanelEvent().
|
import React from 'react';
import { connect } from 'react-redux';
import { trackAnalyticsEvent } from '../../utils/tracking-utils';
import { doControl } from '../../actions/app-actions';
class NodeDetailsControlButton extends React.Component {
constructor(props, context) {
super(props, context);
this.handleClick = this.handleClick.bind(this);
}
render() {
let className = `node-control-button fa ${this.props.control.icon}`;
if (this.props.pending) {
className += ' node-control-button-pending';
}
return (
<span className={className} title={this.props.control.human} onClick={this.handleClick} />
);
}
handleClick(ev) {
ev.preventDefault();
const { id, human } = this.props.control;
trackAnalyticsEvent('scope.node.control.click', { id, title: human });
this.props.dispatch(doControl(this.props.nodeId, this.props.control));
}
}
// Using this instead of PureComponent because of props.dispatch
export default connect()(NodeDetailsControlButton);
|
import React from 'react';
import { connect } from 'react-redux';
import { trackMixpanelEvent } from '../../utils/tracking-utils';
import { doControl } from '../../actions/app-actions';
class NodeDetailsControlButton extends React.Component {
constructor(props, context) {
super(props, context);
this.handleClick = this.handleClick.bind(this);
}
render() {
let className = `node-control-button fa ${this.props.control.icon}`;
if (this.props.pending) {
className += ' node-control-button-pending';
}
return (
<span className={className} title={this.props.control.human} onClick={this.handleClick} />
);
}
handleClick(ev) {
ev.preventDefault();
const { id, human } = this.props.control;
trackMixpanelEvent('scope.node.control.click', { id, title: human });
this.props.dispatch(doControl(this.props.nodeId, this.props.control));
}
}
// Using this instead of PureComponent because of props.dispatch
export default connect()(NodeDetailsControlButton);
|
Add atlas.MustBuild, for those times when you really want a single return value.
Signed-off-by: Eric Myhre <2346ad27d7568ba9896f1b7da6b5991251debdf2@exultant.us>
|
package atlas
import (
"fmt"
"reflect"
)
func Build(entries ...AtlasEntry) (Atlas, error) {
atl := Atlas{
mappings: make(map[uintptr]*AtlasEntry),
}
for _, entry := range entries {
rtid := reflect.ValueOf(entry.Type).Pointer()
if _, exists := atl.mappings[rtid]; exists {
return Atlas{}, fmt.Errorf("repeated entry for %v", entry.Type)
}
atl.mappings[rtid] = &entry
}
return atl, nil
}
func MustBuild(entries ...AtlasEntry) Atlas {
atl, err := Build(entries...)
if err != nil {
panic(err)
}
return atl
}
func BuildEntry(typeHintObj interface{}) *BuilderCore {
return &BuilderCore{
&AtlasEntry{Type: reflect.TypeOf(typeHintObj)},
}
}
/*
Intermediate step in building an AtlasEntry: use `BuildEntry` to
get one of these to start with, then call one of the methods
on this type to get a specialized builder which has the methods
relevant for setting up that specific kind of mapping.
*/
type BuilderCore struct {
entry *AtlasEntry
}
|
package atlas
import (
"fmt"
"reflect"
)
func Build(entries ...AtlasEntry) (Atlas, error) {
atl := Atlas{
mappings: make(map[uintptr]*AtlasEntry),
}
for _, entry := range entries {
rtid := reflect.ValueOf(entry.Type).Pointer()
if _, exists := atl.mappings[rtid]; exists {
return Atlas{}, fmt.Errorf("repeated entry for %v", entry.Type)
}
atl.mappings[rtid] = &entry
}
return atl, nil
}
func BuildEntry(typeHintObj interface{}) *BuilderCore {
return &BuilderCore{
&AtlasEntry{Type: reflect.TypeOf(typeHintObj)},
}
}
/*
Intermediate step in building an AtlasEntry: use `BuildEntry` to
get one of these to start with, then call one of the methods
on this type to get a specialized builder which has the methods
relevant for setting up that specific kind of mapping.
*/
type BuilderCore struct {
entry *AtlasEntry
}
|
Add data: and unsafe-local for base64 fonts and inline js
|
from flask import render_template
from appname import app, db
from models import Foo
from flask.ext.assets import Environment, Bundle
# Static assets
assets = Environment(app)
css_main = Bundle(
'stylesheets/main.scss',
filters='scss',
output='build/main.css',
depends="**/*.scss"
)
assets.register('css_main', css_main)
# govuk_template asset path
@app.context_processor
def asset_path_context_processor():
return {'asset_path': '/static/govuk_template/'}
@app.route('/')
def index():
return render_template("index.html")
# Some useful headers to set to beef up the robustness of the app
# https://www.owasp.org/index.php/List_of_useful_HTTP_headers
@app.after_request
def after_request(response):
response.headers.add('Content-Security-Policy', "default-src 'self' 'unsafe-inline' data:")
response.headers.add('X-Frame-Options', 'deny')
response.headers.add('X-Content-Type-Options', 'nosniff')
response.headers.add('X-XSS-Protection', '1; mode=block')
return response
|
from flask import render_template
from appname import app, db
from models import Foo
from flask.ext.assets import Environment, Bundle
# Static assets
assets = Environment(app)
css_main = Bundle(
'stylesheets/main.scss',
filters='scss',
output='build/main.css',
depends="**/*.scss"
)
assets.register('css_main', css_main)
# govuk_template asset path
@app.context_processor
def asset_path_context_processor():
return {'asset_path': '/static/govuk_template/'}
@app.route('/')
def index():
return render_template("index.html")
# Some useful headers to set to beef up the robustness of the app
# https://www.owasp.org/index.php/List_of_useful_HTTP_headers
@app.after_request
def after_request(response):
response.headers.add('Content-Security-Policy', "default-src 'self'")
response.headers.add('X-Frame-Options', 'deny')
response.headers.add('X-Content-Type-Options', 'nosniff')
response.headers.add('X-XSS-Protection', '1; mode=block')
return response
|
Fix media scaling on single column layout
|
import Immutable from 'immutable';
import { COLUMN_MEDIA_RESIZE } from '../actions/column_media';
const initialState = Immutable.Map({
scale: null,
single: null,
wide: null,
});
function resize(state, { columnCount, defaultPage, single: givenSingle, window: givenWindow }) {
const single = state.get('single') || givenSingle;
const widthCandidate = (givenWindow.innerWidth - 300) / columnCount;
const width = single ? givenWindow.innerWidth : Math.max(widthCandidate, 330);
const wide = !defaultPage || width < givenWindow.innerHeight;
let scale;
if (!defaultPage || (!single && widthCandidate < 330)) {
scale = '230px';
} else if (!wide) {
scale = '50vh';
} else if (single) {
scale = 'calc(50vw - 100px)';
} else {
scale = `calc((100vw - 300px)/${columnCount} - 100px)`;
}
return state.merge({ scale, single, wide });
}
export default function columnMedia(state = initialState, action) {
switch (action.type) {
case COLUMN_MEDIA_RESIZE:
return resize(state, action);
default:
return state;
}
}
|
import Immutable from 'immutable';
import { COLUMN_MEDIA_RESIZE } from '../actions/column_media';
const initialState = Immutable.Map({
scale: null,
single: null,
wide: null,
});
function resize(state, { columnCount, defaultPage, single: givenSingle, window: givenWindow }) {
const single = state.get('single') || givenSingle;
const widthCandidate = (givenWindow.innerWidth - 300) / columnCount;
const width = single ? givenWindow.innerWidth : Math.max(widthCandidate, 330);
const wide = !defaultPage || width < givenWindow.innerHeight;
let scale;
if (!defaultPage || (!single && widthCandidate < 330)) {
scale = '230px';
} else if (!wide) {
scale = '50vh';
} else if (single) {
scale = '100vw';
} else {
scale = `calc((100vw - 300px)/${columnCount} - 100px)`;
}
return state.merge({ scale, single, wide });
}
export default function columnMedia(state = initialState, action) {
switch (action.type) {
case COLUMN_MEDIA_RESIZE:
return resize(state, action);
default:
return state;
}
}
|
Set focus on the first advanced search field
|
$(document).ready(function(){
$("#advanced_search_toggler").click(function(e){
$('body').append('<div class="as-form-overlay">')
$("#advanced_search_toggler").toggleClass('is-opened')
$("#advanced_search_form").toggle();
$('#advanced_search_form').find('input').focus();
$(".as-form-overlay").click(function(e){
$(".as-form-overlay").remove();
$("#advanced_search_form").hide();
$(".select2-drop").hide();
return false;
});
return false;
});
$("#search_button").click(function(e){
e.preventDefault();
var queryParams = [];
Carnival.submitIndexForm();
});
$("#clear_button").click(function(e){
e.preventDefault();
$($(this).parent().parent().parent()).trigger("reset")
$("#advanced_search_form input").each(function(){
var inputValue = $(this).val();
$(this).val('');
});
$("#advanced_search_form select").each(function(){
var inputValue = $(this).val();
$(this).val('');
});
Carnival.submitIndexForm();
});
});
|
$(document).ready(function(){
$("#advanced_search_toggler").click(function(e){
$('body').append('<div class="as-form-overlay">')
$("#advanced_search_toggler").toggleClass('is-opened')
$("#advanced_search_form").toggle();
$(".as-form-overlay").click(function(e){
$(".as-form-overlay").remove();
$("#advanced_search_form").hide();
$(".select2-drop").hide();
return false;
});
return false;
});
$("#search_button").click(function(e){
e.preventDefault();
var queryParams = [];
Carnival.submitIndexForm();
});
$("#clear_button").click(function(e){
e.preventDefault();
$($(this).parent().parent().parent()).trigger("reset")
$("#advanced_search_form input").each(function(){
var inputValue = $(this).val();
$(this).val('');
});
$("#advanced_search_form select").each(function(){
var inputValue = $(this).val();
$(this).val('');
});
Carnival.submitIndexForm();
});
});
|
Introduce listWidth, listHeight and slideHeight state attributes.
|
var initialState = {
animating: false,
dragging: false,
autoPlayTimer: null,
currentDirection: 0,
currentLeft: null,
currentSlide: 0,
direction: 1,
listWidth: null,
listHeight: null,
// loadIndex: 0,
slideCount: null,
slideWidth: null,
slideHeight: null,
// sliding: false,
// slideOffset: 0,
swipeLeft: null,
touchObject: {
startX: 0,
startY: 0,
curX: 0,
curY: 0
},
lazyLoadedList: [],
// added for react
initialized: false,
edgeDragged: false,
swiped: false, // used by swipeEvent. differentites between touch and swipe.
trackStyle: {},
trackWidth: 0
// Removed
// transformsEnabled: false,
// $nextArrow: null,
// $prevArrow: null,
// $dots: null,
// $list: null,
// $slideTrack: null,
// $slides: null,
};
module.exports = initialState;
|
var initialState = {
animating: false,
dragging: false,
autoPlayTimer: null,
currentDirection: 0,
currentLeft: null,
currentSlide: 0,
direction: 1,
// listWidth: null,
// listHeight: null,
// loadIndex: 0,
slideCount: null,
slideWidth: null,
// sliding: false,
// slideOffset: 0,
swipeLeft: null,
touchObject: {
startX: 0,
startY: 0,
curX: 0,
curY: 0
},
lazyLoadedList: [],
// added for react
initialized: false,
edgeDragged: false,
swiped: false, // used by swipeEvent. differentites between touch and swipe.
trackStyle: {},
trackWidth: 0
// Removed
// transformsEnabled: false,
// $nextArrow: null,
// $prevArrow: null,
// $dots: null,
// $list: null,
// $slideTrack: null,
// $slides: null,
};
module.exports = initialState;
|
Add fake console to get it running on iPhone
|
if (!window.console || !window.console.log) {
window.console = {
log: function() {}
};
}
/**
* Very simple reporter for jasmine
*/
var SimpleReporter = function() {
this.reportRunnerStarting = function(runner) {
var count = runner.specs().length;
console.log('start runner', count);
window.parent.socket.emit('result', 'Running ' + count + ' specs...');
};
this.reportRunnerResults = function(runner) {
console.log('complete');
window.parent.socket.emit('result', 'COMPLETE');
};
this.reportSuiteResults = function(suite) {
console.log('suite');
};
this.reportSpecStarting = function(spec) {
console.log('start spec: ' + spec.suite.description + ' ' + spec.description + '...');
};
this.reportSpecResults = function(spec) {
var result = spec.results_.failedCount === 0 ? 'PASSED' : 'FAILED';
window.parent.socket.emit('result', spec.suite.description + ': ' + spec.description + ' -- ' + result);
console.log('spec result', spec);
};
this.log = function() {
console.log('LOG', arguments);
};
};
window.addEventListener('DOMContentLoaded', function() {
var jasmineEnv = jasmine.getEnv();
jasmineEnv.addReporter(new SimpleReporter());
jasmineEnv.execute();
});
// jasmineEnv.updateInterval = 1000;
// jasmineEnv.specFilter = function(spec) {
// return trivialReporter.specFilter(spec);
// };
|
/**
* Very simple reporter for jasmine
*/
var SimpleReporter = function() {
this.reportRunnerStarting = function(runner) {
var count = runner.specs().length;
console.log('start runner', count);
window.parent.socket.emit('result', 'Running ' + count + ' specs...');
};
this.reportRunnerResults = function(runner) {
console.log('complete');
window.parent.socket.emit('result', 'COMPLETE');
};
this.reportSuiteResults = function(suite) {
console.log('suite');
};
this.reportSpecStarting = function(spec) {
console.log('start spec: ' + spec.suite.description + ' ' + spec.description + '...');
};
this.reportSpecResults = function(spec) {
var result = spec.results_.failedCount === 0 ? 'PASSED' : 'FAILED';
window.parent.socket.emit('result', spec.suite.description + ': ' + spec.description + ' -- ' + result);
console.log('spec result', spec);
};
this.log = function() {
console.log('LOG', arguments);
};
};
window.addEventListener('DOMContentLoaded', function() {
var jasmineEnv = jasmine.getEnv();
jasmineEnv.addReporter(new SimpleReporter());
jasmineEnv.execute();
});
// jasmineEnv.updateInterval = 1000;
// jasmineEnv.specFilter = function(spec) {
// return trivialReporter.specFilter(spec);
// };
|
Remove the OccurrenceOrderPlugin that is no longer necessary in Webpack2.
Add the LoaderOptionsPlugin that ensures that output of loaders is minified.
|
/*
* This defines the production settings for our webpack build.
* Anything defined here is only applied during production building.
*/
process.env.NODE_ENV = 'production';
var webpack = require('webpack');
var bundles = require('./webpack.config.js');
for (var i = 0; i < bundles.length; i++) {
bundles[i].plugins = bundles[i].plugins.concat([
// short-circuits all Vue.js warning code
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"',
},
}),
// minify with dead-code elimination
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
},
}),
new webpack.LoaderOptionsPlugin({
minimize: true,
debug: false,
}),
]);
}
module.exports = bundles;
|
/*
* This defines the production settings for our webpack build.
* Anything defined here is only applied during production building.
*/
process.env.NODE_ENV = 'production';
var webpack = require('webpack');
var bundles = require('./webpack.config.js');
for (var i = 0; i < bundles.length; i++) {
bundles[i].plugins = bundles[i].plugins.concat([
// short-circuits all Vue.js warning code
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"',
},
}),
// minify with dead-code elimination
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
},
}),
// optimize module ids by occurence count
new webpack.optimize.OccurrenceOrderPlugin(),
]);
}
module.exports = bundles;
|
Change import path to github.com.
|
// Copyright © 2017 Martin Lindner <mlindner@gaba.co.jp>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package main
import "github.com/martinlindner/go-vtm-cli/cmd"
func main() {
cmd.Execute()
}
|
// Copyright © 2017 Martin Lindner <mlindner@gaba.co.jp>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package main
import "gitlab.gaba.co.jp/gaba-infra/go-vtm-cli/cmd"
func main() {
cmd.Execute()
}
|
Add python 3.6 to the classifiers
|
from setuptools import setup, find_packages
setup(
name='django-cuser',
version=".".join(map(str, __import__("cuser").__version__)),
description='Middleware to make user information always available.',
long_description=open('README.rst').read(),
author='Alireza Savand',
author_email='alireza.savand@gmail.com',
url='https://github.com/Alir3z4/django-cuser',
packages=find_packages(exclude=["django_cuser"]),
install_requires=['Django>=1.8'],
classifiers=[
"Development Status :: 5 - Production/Stable",
"Development Status :: 6 - Mature",
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Topic :: Software Development",
"Topic :: Software Development :: Libraries",
],
)
|
from setuptools import setup, find_packages
setup(
name='django-cuser',
version=".".join(map(str, __import__("cuser").__version__)),
description='Middleware to make user information always available.',
long_description=open('README.rst').read(),
author='Alireza Savand',
author_email='alireza.savand@gmail.com',
url='https://github.com/Alir3z4/django-cuser',
packages=find_packages(exclude=["django_cuser"]),
install_requires=['Django>=1.8'],
classifiers=[
"Development Status :: 5 - Production/Stable",
"Development Status :: 6 - Mature",
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Topic :: Software Development",
"Topic :: Software Development :: Libraries",
],
)
|
Use the provided mongo db rather than mongomock
|
import random
from dmp import dmp
users = ["adam", "ben", "chris", "denis", "eric"]
file_types = ["fastq", "fasta", "bam", "bed", "hdf5", "tsv", "wig", "pdb"]
data_types = ['RNA-seq', 'MNase-Seq', 'ChIP-seq', 'WGBS', 'HiC']
compressed = [None, 'gzip', 'zip']
da = dmp(test=False)
for i in xrange(10):
u = random.choice(users)
ft = random.choice(file_types)
dt = random.choice(data_types)
z = random.choice(compressed)
f = '/tmp/test/' + dt + '/test_' + str(i) + '.' + ft
file_id = da.set_file(u, f, ft, dt, 9606, z)
if dt == 'RNA-seq' and ft == 'fastq' and random.choice([0,1]) == 1:
f = '/tmp/test/' + dt + '/test_' + str(i) + '.bam'
da.set_file(u, f, 'bam', dt, 9606, None, [file_id])
for u in users:
results = da.get_files_by_user(u)
print u, len(results)
|
import random
from dmp import dmp
users = ["adam", "ben", "chris", "denis", "eric"]
file_types = ["fastq", "fasta", "bam", "bed", "hdf5", "tsv", "wig", "pdb"]
data_types = ['RNA-seq', 'MNase-Seq', 'ChIP-seq', 'WGBS', 'HiC']
compressed = [None, 'gzip', 'zip']
da = dmp(test=True)
for i in xrange(10):
u = random.choice(users)
ft = random.choice(file_types)
dt = random.choice(data_types)
z = random.choice(compressed)
f = '/tmp/test/' + dt + '/test_' + str(i) + '.' + ft
file_id = da.set_file(u, f, ft, dt, 9606, z)
if dt == 'RNA-seq' and ft == 'fastq' and random.choice([0,1]) == 1:
f = '/tmp/test/' + dt + '/test_' + str(i) + '.bam'
da.set_file(u, f, 'bam', dt, 9606, None, [file_id])
for u in users:
results = da.get_files_by_user(u)
print u, len(results)
|
Fix a crash when a null Prefab field gets synchronized.
|
/*
* Copyright 2013 MovingBlocks
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.terasology.persistence.typeHandling.extensionTypes;
import org.terasology.utilities.Assets;
import org.terasology.entitySystem.prefab.Prefab;
import org.terasology.persistence.typeHandling.StringRepresentationTypeHandler;
/**
*/
public class PrefabTypeHandler extends StringRepresentationTypeHandler<Prefab> {
public PrefabTypeHandler() {
}
@Override
public String getAsString(Prefab item) {
if (item == null) {
return "";
}
return item.getName();
}
@Override
public Prefab getFromString(String representation) {
if (representation == null) {
return null;
}
return Assets.getPrefab(representation).orElse(null);
}
}
|
/*
* Copyright 2013 MovingBlocks
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.terasology.persistence.typeHandling.extensionTypes;
import org.terasology.utilities.Assets;
import org.terasology.entitySystem.prefab.Prefab;
import org.terasology.persistence.typeHandling.StringRepresentationTypeHandler;
/**
*/
public class PrefabTypeHandler extends StringRepresentationTypeHandler<Prefab> {
public PrefabTypeHandler() {
}
@Override
public String getAsString(Prefab item) {
if (item == null) {
return "";
}
return item.getName();
}
@Override
public Prefab getFromString(String representation) {
return Assets.getPrefab(representation).orElse(null);
}
}
|
Fix a typo in a comment :p
|
/*
* Include a logger in your module with:
*
* var logger = require('triton/core/logging').getLogger(__LOGGER__);
*
* This `logger` has methods for each level specified in logging/common.js.
*
* Example:
*
* logger.debug("result: %s", result);
*
* It *also* has a `time` method for timing named metrics. Metric names
* should be dot-separated and be few in number (i.e. don't include object
* IDs or other variables with many potential values).
*
* Example:
*
* logger.time(`result.${http_status_code}`, time_in_ms);
*
* If you need more than one logger in your module, you can distinguish them
* with labels:
*
* Example:
*
* var fooLogger = logging.getLogger(__LOGGER__({ label: "foo" }));
* var barLogger = logging.getLogger(__LOGGER__({ label: "bar" }));
*
*/
if (SERVER_SIDE)
module.exports = require('./logging/server.js');
else
module.exports = require('./logging/client.js');
|
/*
* Include a logger in your module with:
*
* var logger = require('triton/core/logging').getLogger(__LOGGER__);
*
* This `logger` has methods for each level specified in logging/common.js.
*
* Example:
*
* logger.debug("result: %s", result);
*
* It *also* has a `time` method for timing named metrics. Metric names
* should be dot-separated and be few in number (i.e. don't include object
* IDs or other variables with many potential values).
*
* Example:
*
* logger.time(`result.${http_status_code}`, time_in_ms);
*
* If you need more than one logger in your module, you can distinguish them
* with labels:
*
* Example:
*
* var fooLogger = logging.getLogger(__LOGGER__({ label: "foo" }));
* var fooLogger = logging.getLogger(__LOGGER__({ label: "bar" }));
*
*/
if (SERVER_SIDE)
module.exports = require('./logging/server.js');
else
module.exports = require('./logging/client.js');
|
Add search functionality for runs
Add search functionality for runs. Runs are searched using MongoDB's
full text search capabilities. Note that this requires a text index on
the collection (command used to create the text index:
db.recipies.createIndex({ "$**": "text" }, { name: "TextIndex" },
{language: "none"})
)
Closes #2
|
from flask import Blueprint, request, redirect, render_template, url_for
from flask.views import MethodView
from recipyGui import recipyGui, mongo
from forms import SearchForm
runs = Blueprint('runs', __name__, template_folder='templates')
@recipyGui.route('/')
def index():
form = SearchForm()
query = request.args.get('query', '')
if not query:
# Return all runs, ordered by date (oldest run first)
runs = [r for r in mongo.db.recipies.find({}).sort('date', -1)]
else:
# Search runs using the query string
q = { '$text': { '$search': query} }
runs = [r for r in mongo.db.recipies.find(q)]
print 'runs:', runs
print 'query:', query
return render_template('runs/list.html', runs=runs, query=query, form=form)
#class ListView(MethodView):
# def get(self):
# runs = Run.objects.all()
# print runs
# return render_template('runs/list.html', runs=runs)
# Register urls
#runs.add_url_rule('/', view_func=ListView.as_view('list'))
|
from flask import Blueprint, request, redirect, render_template, url_for
from flask.views import MethodView
from recipyGui import recipyGui, mongo
from forms import SearchForm
runs = Blueprint('runs', __name__, template_folder='templates')
@recipyGui.route('/')
def index():
form = SearchForm()
query = request.args.get('query', '')
if not query:
runs = [r for r in mongo.db.recipies.find({})]
else:
# TODO: search runs using the query string
runs = []
print 'runs:', runs
print 'query:', query
return render_template('runs/list.html', runs=runs, query=query, form=form)
#class ListView(MethodView):
# def get(self):
# runs = Run.objects.all()
# print runs
# return render_template('runs/list.html', runs=runs)
# Register urls
#runs.add_url_rule('/', view_func=ListView.as_view('list'))
|
Fix Sla class path scanner
|
package org.stagemonitor.core.instrument;
import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.DynamicType;
/**
* This transformer does not modify classes but only searches for matching {@link TypeDescription} and {@link MethodDescription}s
*/
public abstract class AbstractClassPathScanner extends StagemonitorByteBuddyTransformer {
@Override
public AgentBuilder.Transformer getTransformer() {
return new AgentBuilder.Transformer() {
@Override
public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder, TypeDescription typeDescription, ClassLoader classLoader) {
onTypeMatch(typeDescription);
return builder;
}
};
}
protected void onTypeMatch(TypeDescription typeDescription) {
for (MethodDescription.InDefinedShape methodDescription : typeDescription.getDeclaredMethods()
.filter(getMethodElementMatcher())) {
onMethodMatch(methodDescription);
}
}
protected abstract void onMethodMatch(MethodDescription.InDefinedShape methodDescription);
}
|
package org.stagemonitor.core.instrument;
import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.type.TypeDescription;
/**
* This transformer does not modify classes but only searches for matching {@link TypeDescription} and {@link MethodDescription}s
*/
public abstract class AbstractClassPathScanner extends StagemonitorByteBuddyTransformer {
@Override
public AgentBuilder.Transformer getTransformer() {
return AgentBuilder.Transformer.NoOp.INSTANCE;
}
@Override
public void beforeTransformation(TypeDescription typeDescription, ClassLoader classLoader) {
onTypeMatch(typeDescription);
}
protected void onTypeMatch(TypeDescription typeDescription) {
for (MethodDescription.InDefinedShape methodDescription : typeDescription.getDeclaredMethods()
.filter(getMethodElementMatcher())) {
onMethodMatch(methodDescription);
}
}
protected abstract void onMethodMatch(MethodDescription.InDefinedShape methodDescription);
}
|
:shirt: Add ignore option for max-nesting-depth rule
|
module.exports = {
plugins: ['stylelint-order', 'stylelint-scss'],
extends: [
'stylelint-config-sass-guidelines',
'stylelint-config-property-sort-order-smacss',
'./node_modules/prettier-stylelint/config.js',
],
rules: {
'function-parentheses-newline-inside': 'always-multi-line',
'function-parentheses-space-inside': 'never-single-line',
'selector-class-pattern': ['^[a-z0-9\\-_]+$'],
'selector-no-qualifying-type': [true, { ignore: 'class' }],
'order/properties-alphabetical-order': null,
// Temporary rules to reduce error noise.
'max-nesting-depth': [
1,
{
severity: 'warning',
ignoreAtRules: ['media', 'supports', 'include'],
},
],
'media-feature-name-no-vendor-prefix': [true, { severity: 'warning' }],
'property-no-vendor-prefix': [true, { severity: 'warning' }],
'selector-no-vendor-prefix': [true, { severity: 'warning' }],
'selector-max-compound-selectors': [3, { severity: 'warning' }],
'value-no-vendor-prefix': [true, { severity: 'warning' }],
'scss/selector-no-redundant-nesting-selector': [
true,
{ severity: 'warning' },
],
},
};
|
module.exports = {
plugins: ['stylelint-order', 'stylelint-scss'],
extends: [
'stylelint-config-sass-guidelines',
'stylelint-config-property-sort-order-smacss',
'./node_modules/prettier-stylelint/config.js',
],
rules: {
'function-parentheses-newline-inside': 'always-multi-line',
'function-parentheses-space-inside': 'never-single-line',
'selector-class-pattern': ['^[a-z0-9\\-_]+$'],
'selector-no-qualifying-type': [true, { ignore: 'class' }],
'order/properties-alphabetical-order': null,
// Temporary rules to reduce error noise.
'max-nesting-depth': [
1,
{
severity: 'warning',
ignore: 'blockless-at-rules',
ignoreAtRules: ['include'],
},
],
'media-feature-name-no-vendor-prefix': [true, { severity: 'warning' }],
'property-no-vendor-prefix': [true, { severity: 'warning' }],
'selector-no-vendor-prefix': [true, { severity: 'warning' }],
'selector-max-compound-selectors': [3, { severity: 'warning' }],
'value-no-vendor-prefix': [true, { severity: 'warning' }],
'scss/selector-no-redundant-nesting-selector': [
true,
{ severity: 'warning' },
],
},
};
|
Add route for admin panel
|
from flask import render_template, send_file
from app import app
from app.models import Post
@app.route('/')
@app.route('/page/<int:page>')
def blog(page=1):
"""View the blog."""
posts = Post.query.filter_by(visible=True) \
.order_by(Post.published.desc())
if posts:
pagination = posts.paginate(page=page, per_page=Post.PER_PAGE)
return render_template('blog.html', pagination=pagination)
@app.route('/archive')
def archive():
"""View an overview of all visible posts."""
posts = Post.query.filter_by(visible=True) \
.order_by(Post.published.desc())
return render_template('archive.html', posts=posts)
@app.route('/<path:slug>', methods=['GET', 'POST'])
def detail(slug):
"""View details of post with specified slug."""
post = Post.query.filter_by(visible=True, slug=slug) \
.first_or_404()
return render_template('detail.html', post=post)
@app.route('/admin')
def admin():
return send_file('static/admin-panel/app/index.html')
|
from app import app
from app.models import Post
from flask import render_template
@app.route('/')
@app.route('/page/<int:page>')
def blog(page=1):
"""View the blog."""
posts = Post.query.filter_by(visible=True) \
.order_by(Post.published.desc())
if posts:
pagination = posts.paginate(page=page, per_page=Post.PER_PAGE)
return render_template('blog.html', pagination=pagination)
@app.route('/archive')
def archive():
"""View an overview of all visible posts."""
posts = Post.query.filter_by(visible=True) \
.order_by(Post.published.desc())
return render_template('archive.html', posts=posts)
@app.route('/<path:slug>', methods=['GET', 'POST'])
def detail(slug):
"""View details of post with specified slug."""
post = Post.query.filter_by(visible=True, slug=slug) \
.first_or_404()
return render_template('detail.html', post=post)
|
Add wait to amazon page set to avoid tab crashes
BUG=skia:3049
TBR=borenet
NOTRY=true
Review URL: https://codereview.chromium.org/686133002
|
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# pylint: disable=W0401,W0614
from telemetry.page import page as page_module
from telemetry.page import page_set as page_set_module
class SkiaBuildbotDesktopPage(page_module.Page):
def __init__(self, url, page_set):
super(SkiaBuildbotDesktopPage, self).__init__(
url=url,
page_set=page_set,
credentials_path = 'data/credentials.json')
self.user_agent_type = 'desktop'
self.archive_data_file = 'data/skia_amazon_desktop.json'
def RunNavigateSteps(self, action_runner):
action_runner.NavigateToPage(self)
action_runner.Wait(15)
class SkiaAmazonDesktopPageSet(page_set_module.PageSet):
""" Pages designed to represent the median, not highly optimized web """
def __init__(self):
super(SkiaAmazonDesktopPageSet, self).__init__(
user_agent_type='desktop',
archive_data_file='data/skia_amazon_desktop.json')
urls_list = [
# Why: #1 world commerce website by visits; #3 commerce in the US by time
# spent.
'http://www.amazon.com',
]
for url in urls_list:
self.AddPage(SkiaBuildbotDesktopPage(url, self))
|
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# pylint: disable=W0401,W0614
from telemetry.page import page as page_module
from telemetry.page import page_set as page_set_module
class SkiaBuildbotDesktopPage(page_module.Page):
def __init__(self, url, page_set):
super(SkiaBuildbotDesktopPage, self).__init__(
url=url,
page_set=page_set,
credentials_path = 'data/credentials.json')
self.user_agent_type = 'desktop'
self.archive_data_file = 'data/skia_amazon_desktop.json'
class SkiaAmazonDesktopPageSet(page_set_module.PageSet):
""" Pages designed to represent the median, not highly optimized web """
def __init__(self):
super(SkiaAmazonDesktopPageSet, self).__init__(
user_agent_type='desktop',
archive_data_file='data/skia_amazon_desktop.json')
urls_list = [
# Why: #1 world commerce website by visits; #3 commerce in the US by time
# spent.
'http://www.amazon.com',
]
for url in urls_list:
self.AddPage(SkiaBuildbotDesktopPage(url, self))
|
Include new script in packaging
|
#!/usr/bin/env python
# Copyright 2015 University of Chicago
# Available under Apache 2.0 License
# setup for fsurf on OSG Connect login
from distutils.core import setup
setup(name='fsurfer-backend',
version='PKG_VERSION',
description='Scripts to handle background freesurfer processing',
author='Suchandra Thapa',
author_email='sthapa@ci.uchicago.edu',
url='https://github.com/OSGConnect/freesurfer_workflow',
scripts=['process_mri.py',
'update_fsurf_job.py',
'purge_inputs.py',
'purge_results.py',
'warn_purge.py',
'delete_jobs.py',
'task_completed.py',
'fsurf_user_admin.py'],
license='Apache 2.0')
|
#!/usr/bin/env python
# Copyright 2015 University of Chicago
# Available under Apache 2.0 License
# setup for fsurf on OSG Connect login
from distutils.core import setup
setup(name='fsurfer-backend',
version='PKG_VERSION',
description='Scripts to handle background freesurfer processing',
author='Suchandra Thapa',
author_email='sthapa@ci.uchicago.edu',
url='https://github.com/OSGConnect/freesurfer_workflow',
scripts=['process_mri.py',
'update_fsurf_job.py',
'purge_inputs.py',
'purge_results.py',
'warn_purge.py',
'delete_jobs.py',
'fsurf_user_admin.py'],
license='Apache 2.0')
|
Remove some tests because of new required arg
|
import unittest
from tailorscad.arg_parser import parse_args
# TODO: Making the config require required some changes I don't like to this
class TestArgParser(unittest.TestCase):
def test_parse_args_known(self):
args = []
argv = ['-c', 'test']
args = parse_args(argv)
self.assertTrue(args)
self.assertEqual(args.config, 'test')
def test_parse_args_unkown_and_known(self):
args = []
argv = ['-a', 'word', '-c', 'test']
args = parse_args(argv)
self.assertTrue(args)
self.assertEqual(args.config, 'test')
|
import unittest
from tailorscad.arg_parser import parse_args
class TestArgParser(unittest.TestCase):
def test_parse_args_none(self):
args = []
argv = []
args = parse_args(argv)
self.assertFalse(args.config)
def test_parse_args_inknown(self):
args = []
argv = ['-a', 'word']
args = parse_args(argv)
self.assertFalse(args.config)
def test_parse_args_known(self):
args = []
argv = ['-c', 'test']
args = parse_args(argv)
self.assertTrue(args)
self.assertEqual(args.config, 'test')
def test_parse_args_unkown_and_known(self):
args = []
argv = ['-a', 'word', '-c', 'test']
args = parse_args(argv)
self.assertTrue(args)
self.assertEqual(args.config, 'test')
|
Update classifiers to show Python 3 support
|
#! /usr/bin/env python
from setuptools import setup, find_packages
from basic_modeling_interface import __version__
setup(name='basic-modeling-interface',
version=__version__,
author='Eric Hutton',
author_email='eric.hutton@colorado.edu',
url='https://github.com/bmi-forum/bmi-python',
license='MIT',
description='Python bindings for the Basic Modeling Interface',
long_description=open('README.md').read(),
keywords='BMI model coupling',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
],
packages=find_packages(),
)
|
#! /usr/bin/env python
from setuptools import setup, find_packages
from basic_modeling_interface import __version__
setup(name='basic-modeling-interface',
version=__version__,
author='Eric Hutton',
author_email='eric.hutton@colorado.edu',
url='https://github.com/bmi-forum/bmi-python',
# download_url='https://github.com/bmi-forum/bmi-python/tarball/0.1.0',
license='MIT',
description='Python bindings for the Basic Modeling Interface',
long_description=open('README.md').read(),
keywords='BMI model coupling',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
],
packages=find_packages(),
)
|
Fix a typo in customize page url setup
|
from django.conf.urls.defaults import *
from django.conf import settings
from product_details import product_details
from mozorg.util import page
import views
urlpatterns = patterns('',
page('firefox/central', 'firefox/central.html'),
page('firefox/customize', 'firefox/customize.html'),
page('firefox/features', 'firefox/features.html'),
page('firefox/fx', 'firefox/fx.html'),
page('firefox/geolocation', 'firefox/geolocation.html',
gmap_api_key=settings.GMAP_API_KEY),
page('firefox/happy', 'firefox/happy.html'),
page('firefox/new', 'firefox/new.html'),
page('firefox/organizations/faq', 'firefox/organizations/faq.html'),
page('firefox/organizations', 'firefox/organizations.html'),
page('firefox/performance', 'firefox/performance.html'),
page('firefox/security', 'firefox/security.html'),
page('firefox/speed', 'firefox/speed.html',
latest_version=product_details.versions['LATEST_FIREFOX_DEVEL_VERSION']),
page('firefox/technology', 'firefox/technology.html'),
page('firefox/update', 'firefox/update.html'),
)
|
from django.conf.urls.defaults import *
from django.conf import settings
from product_details import product_details
from mozorg.util import page
import views
urlpatterns = patterns('',
page('firefox/central', 'firefox/central.html'),
page('firefox/customize', 'firefox/customize'),
page('firefox/features', 'firefox/features.html'),
page('firefox/fx', 'firefox/fx.html'),
page('firefox/geolocation', 'firefox/geolocation.html',
gmap_api_key=settings.GMAP_API_KEY),
page('firefox/happy', 'firefox/happy.html'),
page('firefox/new', 'firefox/new.html'),
page('firefox/organizations/faq', 'firefox/organizations/faq.html'),
page('firefox/organizations', 'firefox/organizations.html'),
page('firefox/performance', 'firefox/performance.html'),
page('firefox/security', 'firefox/security.html'),
page('firefox/speed', 'firefox/speed.html',
latest_version=product_details.versions['LATEST_FIREFOX_DEVEL_VERSION']),
page('firefox/technology', 'firefox/technology.html'),
page('firefox/update', 'firefox/update.html'),
)
|
Add unix timestamp field to Attachment struct
By providing the ts field with an integer value in "epoch time", the attachment will display an additional timestamp value as part of the attachment's footer. -https://api.slack.com/docs/message-attachments
|
package slack
// https://api.slack.com/docs/attachments
// It is possible to create more richly-formatted messages using Attachments.
type AttachmentField struct {
Title string `json:"title"`
Value string `json:"value"`
Short bool `json:"short"`
}
type Attachment struct {
Color string `json:"color,omitempty"`
Fallback string `json:"fallback"`
AuthorName string `json:"author_name,omitempty"`
AuthorSubname string `json:"author_subname,omitempty"`
AuthorLink string `json:"author_link,omitempty"`
AuthorIcon string `json:"author_icon,omitempty"`
Title string `json:"title,omitempty"`
TitleLink string `json:"title_link,omitempty"`
Pretext string `json:"pretext,omitempty"`
Text string `json:"text"`
ImageURL string `json:"image_url,omitempty"`
ThumbURL string `json:"thumb_url,omitempty"`
Footer string `json:"footer,omitempty"`
FooterIcon string `json:"footer_icon,omitempty"`
TimeStamp int64 `json:"ts,omitempty"`
Fields []*AttachmentField `json:"fields,omitempty"`
MarkdownIn []string `json:"mrkdwn_in,omitempty"`
}
|
package slack
// https://api.slack.com/docs/attachments
// It is possible to create more richly-formatted messages using Attachments.
type AttachmentField struct {
Title string `json:"title"`
Value string `json:"value"`
Short bool `json:"short"`
}
type Attachment struct {
Color string `json:"color,omitempty"`
Fallback string `json:"fallback"`
AuthorName string `json:"author_name,omitempty"`
AuthorSubname string `json:"author_subname,omitempty"`
AuthorLink string `json:"author_link,omitempty"`
AuthorIcon string `json:"author_icon,omitempty"`
Title string `json:"title,omitempty"`
TitleLink string `json:"title_link,omitempty"`
Pretext string `json:"pretext,omitempty"`
Text string `json:"text"`
ImageURL string `json:"image_url,omitempty"`
ThumbURL string `json:"thumb_url,omitempty"`
Footer string `json:"footer,omitempty"`
FooterIcon string `json:"footer_icon,omitempty"`
Fields []*AttachmentField `json:"fields,omitempty"`
MarkdownIn []string `json:"mrkdwn_in,omitempty"`
}
|
Fix no input call command
|
from django.apps import apps
from django.conf import settings
from django.contrib.gis.gdal import SpatialReference
from django.core.exceptions import ImproperlyConfigured
from django.core.management import call_command
from django.core.management.commands.migrate import Command as BaseCommand
from geotrek.common.utils.postgresql import move_models_to_schemas, load_sql_files, set_search_path
def check_srid_has_meter_unit():
if not hasattr(check_srid_has_meter_unit, '_checked'):
if SpatialReference(settings.SRID).units[1] != 'metre':
err_msg = 'Unit of SRID EPSG:%s is not meter.' % settings.SRID
raise ImproperlyConfigured(err_msg)
check_srid_has_meter_unit._checked = True
class Command(BaseCommand):
def handle(self, *args, **options):
check_srid_has_meter_unit()
set_search_path()
for app in apps.get_app_configs():
move_models_to_schemas(app)
load_sql_files(app, 'pre')
super().handle(*args, **options)
call_command('sync_translation_fields', '--noinput')
call_command('update_translation_fields')
for app in apps.get_app_configs():
move_models_to_schemas(app)
load_sql_files(app, 'post')
|
from django.apps import apps
from django.conf import settings
from django.contrib.gis.gdal import SpatialReference
from django.core.exceptions import ImproperlyConfigured
from django.core.management import call_command
from django.core.management.commands.migrate import Command as BaseCommand
from geotrek.common.utils.postgresql import move_models_to_schemas, load_sql_files, set_search_path
def check_srid_has_meter_unit():
if not hasattr(check_srid_has_meter_unit, '_checked'):
if SpatialReference(settings.SRID).units[1] != 'metre':
err_msg = 'Unit of SRID EPSG:%s is not meter.' % settings.SRID
raise ImproperlyConfigured(err_msg)
check_srid_has_meter_unit._checked = True
class Command(BaseCommand):
def handle(self, *args, **options):
check_srid_has_meter_unit()
set_search_path()
for app in apps.get_app_configs():
move_models_to_schemas(app)
load_sql_files(app, 'pre')
super().handle(*args, **options)
call_command('sync_translation_fields', noinput=True)
call_command('update_translation_fields')
for app in apps.get_app_configs():
move_models_to_schemas(app)
load_sql_files(app, 'post')
|
Update Version to reflect fsrepo change
License: MIT
Signed-off-by: Zander Mackie <dad6048958a096c4d96d991a47a426a281ad31ed@gmail.com>
|
package mfsr
import (
"io/ioutil"
"os"
"strconv"
"testing"
"github.com/ipfs/go-ipfs/thirdparty/assert"
)
func testVersionFile(v string, t *testing.T) (rp RepoPath) {
name, err := ioutil.TempDir("", v)
if err != nil {
t.Fatal(err)
}
rp = RepoPath(name)
return rp
}
func TestVersion(t *testing.T) {
rp := RepoPath("")
_, err := rp.Version()
assert.Err(err, t, "Should throw an error when path is bad,")
rp = RepoPath("/path/to/nowhere")
_, err = rp.Version()
if !os.IsNotExist(err) {
t.Fatalf("Should throw an `IsNotExist` error when file doesn't exist: %v", err)
}
fsrepoV := 5
rp = testVersionFile(strconv.Itoa(fsrepoV), t)
_, err = rp.Version()
assert.Err(err, t, "Bad VersionFile")
assert.Nil(rp.WriteVersion(fsrepoV), t, "Trouble writing version")
assert.Nil(rp.CheckVersion(fsrepoV), t, "Trouble checking the verion")
assert.Err(rp.CheckVersion(1), t, "Should throw an error for the wrong version.")
}
|
package mfsr
import (
"io/ioutil"
"os"
"testing"
"github.com/ipfs/go-ipfs/thirdparty/assert"
)
func testVersionFile(v string, t *testing.T) (rp RepoPath) {
name, err := ioutil.TempDir("", v)
if err != nil {
t.Fatal(err)
}
rp = RepoPath(name)
return rp
}
func TestVersion(t *testing.T) {
rp := RepoPath("")
_, err := rp.Version()
assert.Err(err, t, "Should throw an error when path is bad,")
rp = RepoPath("/path/to/nowhere")
_, err = rp.Version()
if !os.IsNotExist(err) {
t.Fatalf("Should throw an `IsNotExist` error when file doesn't exist: %v", err)
}
rp = testVersionFile("4", t)
_, err = rp.Version()
assert.Err(err, t, "Bad VersionFile")
assert.Nil(rp.WriteVersion(4), t, "Trouble writing version")
assert.Nil(rp.CheckVersion(4), t, "Trouble checking the verion")
assert.Err(rp.CheckVersion(1), t, "Should throw an error for the wrong version.")
}
|
Add note about naming functions uniquely
|
# This line keeps pyflakes from getting mad when it can't find the `scheduler`
# object declared in narcissa.py.
scheduler = globals()['scheduler']
# Write everything inside one giant function so that function can be scheduled
# for later execution.
# This function MUST be named uniquely so it doesn't interfere with other
# scrapers or Narcissa functions. One safe way to name functions is to use the
# scrape_ prefix with the filename of the scraper.
def scrape_test():
"""
This scraper illustrates the following:
* How to access Narcissa's config
* How to store and access local config variables
* How to schedule a scraper
* How to run a scraper immediately
"""
# Config usually comes first so the user sees it right away.
MY_NAME = 'Lil B the Based God'
# Imports usually come next.
import config
from datetime import datetime
# Program logic goes here. Whatever you use in a normal Python script will
# work as long as it's inside this function.
class MyClass:
def __init__(self):
self.greeting = 'Hello!'
def get_my_name():
return MY_NAME
c = MyClass()
print(c.greeting + ' My name is ' + get_my_name())
print('DB_URI: %s' % config.DB_URI)
print('Right now: %s' % datetime.now())
# Schedule this task to run every 3 seconds.
# It will run immediately as well.
scheduler.every(3).seconds.do(scrape_test)
|
# This line keeps pyflakes from getting mad when it can't find the `scheduler`
# object declared in narcissa.py.
scheduler = globals()['scheduler']
# Write everything inside one giant function so that function can be scheduled
# for later execution.
def scrape_test():
"""
This scraper illustrates the following:
* How to access Narcissa's config
* How to store and access local config variables
* How to schedule a scraper
* How to run a scraper immediately
"""
# Config usually comes first so the user sees it right away.
MY_NAME = 'Lil B the Based God'
# Imports usually come next.
import config
from datetime import datetime
# Program logic goes here. Whatever you use in a normal Python script will
# work as long as it's inside this function.
class MyClass:
def __init__(self):
self.greeting = 'Hello!'
def get_my_name():
return MY_NAME
c = MyClass()
print(c.greeting + ' My name is ' + get_my_name())
print('DB_URI: %s' % config.DB_URI)
print('Right now: %s' % datetime.now())
# Schedule this task to run every 3 seconds.
# It will run immediately as well.
scheduler.every(3).seconds.do(scrape_test)
|
Make un-versioned client script return the latest
|
"use strict";
var messages = require("./messages");
var config = require("./config");
var snippetUtils = require("./snippet").utils;
var connect = require("connect");
var http = require("http");
/**
* Launch the server for serving the client JS plus static files
* @param {String} scriptTags
* @param {Object} options
* @param {Function} scripts
* @returns {http.Server}
*/
module.exports.launchControlPanel = function (scriptTags, options, scripts) {
var clientScripts = messages.clientScript(options, true);
var app =
connect()
.use(clientScripts.versioned, scripts)
.use(clientScripts.path, scripts)
.use(snippetUtils.getSnippetMiddleware(scriptTags))
.use(connect.static(config.controlPanel.baseDir));
return http.createServer(app);
};
|
"use strict";
var messages = require("./messages");
var config = require("./config");
var snippetUtils = require("./snippet").utils;
var connect = require("connect");
var http = require("http");
/**
* Launch the server for serving the client JS plus static files
* @param {String} scriptTags
* @param {Object} options
* @param {Function} scripts
* @returns {http.Server}
*/
module.exports.launchControlPanel = function (scriptTags, options, scripts) {
var clientScripts = messages.clientScript(options, true);
var app =
connect()
.use(clientScripts.versioned, scripts)
.use(snippetUtils.getSnippetMiddleware(scriptTags))
.use(connect.static(config.controlPanel.baseDir));
return http.createServer(app);
};
|
Add category mapping for exhibitions
Too many exhibition events from TRDEvents got the "other"-category
|
module.exports = {
"Dagens bedrift": "PRESENTATIONS",
"Fest og moro": "NIGHTLIFE",
"Konsert": "MUSIC",
"Kurs og events": "PRESENTATIONS",
"Revy og teater": "PERFORMANCES",
"Foredrag": "PRESENTATIONS",
"Møte": "DEBATE",
"Happening": "NIGHTLIFE",
"Kurs": "OTHER",
"Show": "PERFORMANCES",
"Fotballkamp": "SPORT",
"Film": "PRESENTATIONS",
"Samfundsmøte": "DEBATE",
"Excenteraften": "DEBATE",
"Temafest": "NIGHTLIFE",
"Bokstavelig talt": "DEBATE",
"Quiz": "OTHER",
"DJ": "MUSIC",
"Teater": "PERFORMANCES",
"Annet": "OTHER",
"Kurs": "PRESENTATIONS",
"Omvising": "PRESENTATIONS",
"Samfunn": "DEBATE",
"Festival": "PERFORMANCES",
"Sport": "SPORT",
"Forestilling": "PERFORMANCES",
"Utstilling" : "EXHIBITIONS"
};
|
module.exports = {
"Dagens bedrift": "PRESENTATIONS",
"Fest og moro": "NIGHTLIFE",
"Konsert": "MUSIC",
"Kurs og events": "PRESENTATIONS",
"Revy og teater": "PERFORMANCES",
"Foredrag": "PRESENTATIONS",
"Møte": "DEBATE",
"Happening": "NIGHTLIFE",
"Kurs": "OTHER",
"Show": "PERFORMANCES",
"Fotballkamp": "SPORT",
"Film": "PRESENTATIONS",
"Samfundsmøte": "DEBATE",
"Excenteraften": "DEBATE",
"Temafest": "NIGHTLIFE",
"Bokstavelig talt": "DEBATE",
"Quiz": "OTHER",
"DJ": "MUSIC",
"Teater": "PERFORMANCES",
"Annet": "OTHER",
"Kurs": "PRESENTATIONS",
"Omvising": "PRESENTATIONS",
"Samfunn": "DEBATE",
"Festival": "PERFORMANCES",
"Sport": "SPORT",
"Forestilling": "PERFORMANCES"
};
|
Return raw output in unexpected exception
|
<?php
namespace RIPS\Connector\Exceptions;
use RIPS\Connector\Entities\Response;
class HttpException extends \RuntimeException
{
/** @var Response */
private $response;
/**
* @param Response $response
* @throws \Exception if no proper error is found
*/
public function __construct(Response $response)
{
$this->response = $response;
$data = $response->getDecodedData();
if (!is_object($data)) {
throw new \Exception('Unexpected response in exception: ' . $response->getRawData());
}
parent::__construct(
property_exists($data, 'message') ? $data->message : '',
property_exists($data, 'code') ? $data->code : 0
);
}
/**
* @return Response
*/
public function getResponse()
{
return $this->response;
}
}
|
<?php
namespace RIPS\Connector\Exceptions;
use RIPS\Connector\Entities\Response;
class HttpException extends \RuntimeException
{
/** @var Response */
private $response;
/**
* @param Response $response
* @throws \Exception if no proper error is found
*/
public function __construct(Response $response)
{
$this->response = $response;
$data = $response->getDecodedData();
if (!is_object($data)) {
throw new \Exception('Unexpected response in exception: ' . $data);
}
parent::__construct(
property_exists($data, 'message') ? $data->message : '',
property_exists($data, 'code') ? $data->code : 0
);
}
/**
* @return Response
*/
public function getResponse()
{
return $this->response;
}
}
|
Make sure to run test command tests
|
<?php declare(strict_types=1);
namespace ApiClients\Tests\Foundation\Transport\CommandBus\Command;
use ApiClients\Foundation\Transport\CommandBus\Command\SimpleRequestCommand;
use ApiClients\Tests\Foundation\Hydrator\TestCase;
use Psr\Http\Message\RequestInterface;
class SimpleRequestCommandTest extends TestCase
{
public function testCommand()
{
$method = 'GET';
$path = '/foo/bar.json';
$refresh = true;
$command = new SimpleRequestCommand($path, $refresh);
$this->assertInstanceOf(RequestInterface::class, $command->getRequest());
$this->assertSame($method, $command->getRequest()->getMethod());
$this->assertSame($path, $command->getRequest()->getUri()->getPath());
$this->assertSame($refresh, $command->getRefresh());
}
public function testCommandDefaultRefresh()
{
$method = 'GET';
$path = '/foo/bar.json';
$refresh = false;
$command = new SimpleRequestCommand($path);
$this->assertInstanceOf(RequestInterface::class, $command->getRequest());
$this->assertSame($method, $command->getRequest()->getMethod());
$this->assertSame($path, $command->getRequest()->getUri()->getPath());
$this->assertSame($refresh, $command->getRefresh());
}
}
|
<?php declare(strict_types=1);
namespace ApiClients\Tests\Foundation\Transport\CommandBus\Command;
use ApiClients\Foundation\Transport\CommandBus\Command\SimpleRequestCommand;
use ApiClients\Tests\Foundation\Hydrator\TestCase;
use Psr\Http\Message\RequestInterface;
class SimpleRequestCommandTest extends TestCase
{
public function _testCommand()
{
$method = 'GET';
$path = '/foo/bar.json';
$refresh = true;
$command = new SimpleRequestCommand($path, $refresh);
$this->assertInstanceOf(RequestInterface::class, $command->getRequest());
$this->assertSame($method, $command->getRequest()->getMethod());
$this->assertSame($path, $command->getRequest()->getUri()->getPath());
$this->assertSame($refresh, $command->getRefresh());
}
public function testCommandDefaultRefresh()
{
$method = 'GET';
$path = '/foo/bar.json';
$refresh = false;
$command = new SimpleRequestCommand($path);
$this->assertInstanceOf(RequestInterface::class, $command->getRequest());
$this->assertSame($method, $command->getRequest()->getMethod());
$this->assertSame($path, $command->getRequest()->getUri()->getPath());
$this->assertSame($refresh, $command->getRefresh());
}
}
|
Fix user input handling for confirm()
|
<?php
namespace PharIo\Phive\Cli;
class ConsoleInput implements Input {
/**
* @var Output
*/
private $output;
/**
* ConsoleInput constructor.
*
* @param Output $output
*/
public function __construct(Output $output) {
$this->output = $output;
}
/**
* @param string $message
*
* @return bool
*/
public function confirm($message) {
do {
$this->output->writeText(rtrim($message) . ' [Y|n] ');
$response = strtolower(rtrim(fgets(STDIN)));
} while (!in_array($response, ['y','n']));
return ($response === 'y');
}
}
|
<?php
namespace PharIo\Phive\Cli;
class ConsoleInput implements Input {
/**
* @var Cli\Output
*/
private $output;
/**
* ConsoleInput constructor.
*
* @param Cli\Output $output
*/
public function __construct(Output $output) {
$this->output = $output;
}
/**
* @param string $message
*
* @return bool
*/
public function confirm($message) {
$this->output->writeText(rtrim($message) . ' [Y|n] ');
$response = fgetc(STDIN);
return (trim($response) === '' || strpos('Yy', $response[0]) !== false);
}
}
|
Fix typo in MappedBy annotation
|
package jp.ac.nii.prl.mape.redundancy.model;
import java.util.Collection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import org.hibernate.validator.constraints.NotEmpty;
import com.fasterxml.jackson.annotation.JsonIgnore;
@Entity
public class RedundancyView {
@GeneratedValue
@Id
@JsonIgnore
private Long id;
@NotEmpty
@OneToMany(mappedBy="redundancyView")
private Collection<Instance> instances;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Collection<Instance> getInstances() {
return instances;
}
public void setInstances(Collection<Instance> instances) {
this.instances = instances;
}
public void addInstance(Instance instance) {
instances.add(instance);
}
}
|
package jp.ac.nii.prl.mape.redundancy.model;
import java.util.Collection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import org.hibernate.validator.constraints.NotEmpty;
import com.fasterxml.jackson.annotation.JsonIgnore;
@Entity
public class RedundancyView {
@GeneratedValue
@Id
@JsonIgnore
private Long id;
@NotEmpty
@OneToMany(mappedBy="RedundancyView")
private Collection<Instance> instances;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Collection<Instance> getInstances() {
return instances;
}
public void setInstances(Collection<Instance> instances) {
this.instances = instances;
}
public void addInstance(Instance instance) {
instances.add(instance);
}
}
|
Fix wagtail module paths in news
|
from django.conf import settings
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.utils.translation import ugettext_lazy as _
from wagtail.core.models import Page
from .news import get_news_feeds
class NewsIndexPage(Page):
@property
def news_list(self):
return get_news_feeds()
class Meta:
verbose_name = _('News index')
def get_context(self, request, *args, **kwargs):
context = super(NewsIndexPage, self).get_context(request, *args, **kwargs)
news_list = self.news_list
# Pagination
page = request.GET.get('page')
page_size = getattr(settings, 'NEWS_PAGINATION_PER_PAGE', 10)
if page_size is not None:
paginator = Paginator(news_list, page_size) # Show 10 blogs per page
try:
news_list = paginator.page(page)
except PageNotAnInteger:
news_list = paginator.page(1)
except EmptyPage:
news_list = paginator.page(paginator.num_pages)
context['news_list'] = news_list
return context
|
from django.conf import settings
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.utils.translation import ugettext_lazy as _
from wagtail.wagtailcore.models import Page
from .news import get_news_feeds
class NewsIndexPage(Page):
@property
def news_list(self):
return get_news_feeds()
class Meta:
verbose_name = _('News index')
def get_context(self, request, *args, **kwargs):
context = super(NewsIndexPage, self).get_context(request, *args, **kwargs)
news_list = self.news_list
# Pagination
page = request.GET.get('page')
page_size = getattr(settings, 'NEWS_PAGINATION_PER_PAGE', 10)
if page_size is not None:
paginator = Paginator(news_list, page_size) # Show 10 blogs per page
try:
news_list = paginator.page(page)
except PageNotAnInteger:
news_list = paginator.page(1)
except EmptyPage:
news_list = paginator.page(paginator.num_pages)
context['news_list'] = news_list
return context
|
Make utility class constructor private
|
package fr.utc.assos.uvweb.api;
import java.util.List;
import fr.utc.assos.uvweb.BuildConfig;
import fr.utc.assos.uvweb.model.Newsfeed;
import fr.utc.assos.uvweb.model.UvDetail;
import fr.utc.assos.uvweb.model.UvListItem;
import retrofit.Callback;
import retrofit.RestAdapter;
public class UvwebProvider {
private UvwebProvider() {
// Class should be instanciated
}
private static RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("https://assos.utc.fr/uvweb")
.setLogLevel(BuildConfig.DEBUG ? RestAdapter.LogLevel.FULL : RestAdapter.LogLevel.NONE)
.build();
private static UvwebApi uvwebApi = restAdapter.create(UvwebApi.class);
public static void getUvs(Callback<List<UvListItem>> callback) {
uvwebApi.getUvs(callback);
}
public static void getNewsfeed(Callback<Newsfeed> callback) {
uvwebApi.getNewsfeed(callback);
}
public static void getUvDetail(String name, Callback<UvDetail> callback) {
uvwebApi.getUvDetail(name, callback);
}
}
|
package fr.utc.assos.uvweb.api;
import java.util.List;
import fr.utc.assos.uvweb.BuildConfig;
import fr.utc.assos.uvweb.model.Newsfeed;
import fr.utc.assos.uvweb.model.UvDetail;
import fr.utc.assos.uvweb.model.UvListItem;
import retrofit.Callback;
import retrofit.RestAdapter;
public class UvwebProvider {
private static RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("https://assos.utc.fr/uvweb")
.setLogLevel(BuildConfig.DEBUG ? RestAdapter.LogLevel.FULL : RestAdapter.LogLevel.NONE)
.build();
private static UvwebApi uvwebApi = restAdapter.create(UvwebApi.class);
public static void getUvs(Callback<List<UvListItem>> callback) {
uvwebApi.getUvs(callback);
}
public static void getNewsfeed(Callback<Newsfeed> callback) {
uvwebApi.getNewsfeed(callback);
}
public static void getUvDetail(String name, Callback<UvDetail> callback) {
uvwebApi.getUvDetail(name, callback);
}
}
|
Allow sharing db connection across threads
|
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.pool import StaticPool
# Database
engine = create_engine('sqlite:///files/chats.db', convert_unicode=True,
connect_args= {'check_same_thread': False},
poolclass=StaticPool)
db_session = scoped_session(sessionmaker(autocommit=False,
autoflush=False,
bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()
def init_db():
# import all modules here that might define models so that
# they will be registered properly on the metadata. Otherwise
# you will have to import them first before calling init_db()
import scraper.models
Base.metadata.create_all(bind=engine)
|
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
# Database
engine = create_engine('sqlite:///files/chats.db', convert_unicode=True)
db_session = scoped_session(sessionmaker(autocommit=False,
autoflush=False,
bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()
def init_db():
# import all modules here that might define models so that
# they will be registered properly on the metadata. Otherwise
# you will have to import them first before calling init_db()
import scraper.models
Base.metadata.create_all(bind=engine)
|
Use oop helpers for GrowlBox class
[skip ci]
|
// website/static/js/growlBox.js
'use strict';
var $ = require('jquery');
require('bootstrap.growl');
var oop = require('js/oop');
/**
* Show a growl-style notification for messages. Defaults to an error type.
* @param {String} title Shows in bold at the top of the box. Required or it looks foolish.
* @param {String} message Shows a line below the title. This could be '' if there's nothing to say.
* @param {String} type One of 'success', 'info', 'warning', or 'danger'. Defaults to danger.
*/
var GrowlBox = oop.defclass({
constructor(title, message, type='danger') {
this.title = title;
this.message = message;
this.type = type;
this.show();
},
show() {
$.growl({
title: '<strong>' + this.title + '<strong><br />',
message: this.message
},{
type: this.type,
delay: 0,
animate: {
enter: 'animated slideInDown',
exit: 'animated slideOutRight'
}
});
}
});
module.exports = GrowlBox;
|
// website/static/js/growlBox.js
'use strict';
var $ = require('jquery');
require('bootstrap.growl');
/**
* Show a growl-style notification for messages. Defaults to an error type.
* @param {String} title Shows in bold at the top of the box. Required or it looks foolish.
* @param {String} message Shows a line below the title. This could be '' if there's nothing to say.
* @param {String} type One of 'success', 'info', 'warning', or 'danger'. Defaults to danger.
*/
class GrowlBox {
constructor(title, message, type='danger') {
this.title = title;
this.message = message;
this.type = type;
this.show();
}
show() {
$.growl({
title: '<strong>' + this.title + '<strong><br />',
message: this.message
},{
type: this.type,
delay: 0,
animate: {
enter: 'animated slideInDown',
exit: 'animated slideOutRight'
}
});
}
}
module.exports = GrowlBox;
|
Allow nullable payment_id for pending payment purposes; Add standard eloquent timestamps
|
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateDuesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('dues', function (Blueprint $table) {
$table->increments('id');
$table->boolean('eligible_for_shirt')->default(false);
$table->boolean('eligible_for_polo')->default(false);
$table->boolean('received_shirt')->default(false);
$table->boolean('received_polo')->default(false);
$table->timestamp('effective_start');
$table->timestamp('effective_end');
$table->unsignedInteger('payment_id')->nullable();
$table->timestamps();
$table->foreign('payment_id')->references('id')->on('payments');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('dues');
}
}
|
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateDuesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('dues', function (Blueprint $table) {
$table->increments('id');
$table->boolean('eligible_for_shirt')->default(false);
$table->boolean('eligible_for_polo')->default(false);
$table->boolean('received_shirt')->default(false);
$table->boolean('received_polo')->default(false);
$table->timestamp('effective_start');
$table->timestamp('effective_end');
$table->unsignedInteger('payment_id');
$table->foreign('payment_id')->references('id')->on('payments');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('dues');
}
}
|
Adjust OSF Storage default region names
|
# encoding: utf-8
import importlib
import os
import logging
from website import settings
logger = logging.getLogger(__name__)
DEFAULT_REGION_NAME = 'United States'
DEFAULT_REGION_ID = 'us'
WATERBUTLER_CREDENTIALS = {
'storage': {}
}
WATERBUTLER_SETTINGS = {
'storage': {
'provider': 'filesystem',
'folder': os.path.join(settings.BASE_PATH, 'osfstoragecache'),
}
}
WATERBUTLER_RESOURCE = 'folder'
DISK_SAVING_MODE = settings.DISK_SAVING_MODE
try:
mod = importlib.import_module('.{}'.format(settings.MIGRATION_ENV), package='addons.osfstorage.settings')
globals().update({k: getattr(mod, k) for k in dir(mod)})
except Exception as ex:
logger.warn('No migration settings loaded for OSFStorage, falling back to local dev. {}'.format(ex))
|
# encoding: utf-8
import importlib
import os
import logging
from website import settings
logger = logging.getLogger(__name__)
DEFAULT_REGION_NAME = 'N. Virginia'
DEFAULT_REGION_ID = 'us-east-1'
WATERBUTLER_CREDENTIALS = {
'storage': {}
}
WATERBUTLER_SETTINGS = {
'storage': {
'provider': 'filesystem',
'folder': os.path.join(settings.BASE_PATH, 'osfstoragecache'),
}
}
WATERBUTLER_RESOURCE = 'folder'
DISK_SAVING_MODE = settings.DISK_SAVING_MODE
try:
mod = importlib.import_module('.{}'.format(settings.MIGRATION_ENV), package='addons.osfstorage.settings')
globals().update({k: getattr(mod, k) for k in dir(mod)})
except Exception as ex:
logger.warn('No migration settings loaded for OSFStorage, falling back to local dev. {}'.format(ex))
|
Fix gallery image position field
|
<?php
namespace Ekyna\Bundle\CoreBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
/**
* Class GalleryImageType
* @package Ekyna\Bundle\CoreBundle\Form\Type
* @author Étienne Dauvergne <contact@ekyna.com>
*/
class GalleryImageType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('position', 'hidden', array(
'attr' => array(
'data-collection-role' => 'position'
)
))
;
}
/**
* {@inheritdoc}
*/
public function getParent()
{
return 'ekyna_core_image';
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'ekyna_core_gallery_image';
}
}
|
<?php
namespace Ekyna\Bundle\CoreBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
/**
* Class GalleryImageType
* @package Ekyna\Bundle\CoreBundle\Form\Type
* @author Étienne Dauvergne <contact@ekyna.com>
*/
class GalleryImageType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('position', 'hidden', array(
'attr' => array(
'data-role' => 'data-collection-position'
)
))
;
}
/**
* {@inheritdoc}
*/
public function getParent()
{
return 'ekyna_core_image';
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'ekyna_core_gallery_image';
}
}
|
Handle missing value in predit rf
|
import numpy as np
import pandas as pd
import sys
import os
from sklearn.externals import joblib
from sklearn.ensemble import RandomForestClassifier
scriptpath = os.path.dirname(os.path.realpath(sys.argv[0])) + '/../'
sys.path.append(os.path.abspath(scriptpath))
import utils
parameter_str = '_'.join(['top', str(utils.k), 'cw', str(utils.click_weight), 'year', utils.train_year])
cforest = joblib.load(utils.model_path + 'rf_all_without_time_' + parameter_str +'.pkl')
test = joblib.load(utils.processed_data_path + 'test_all_' + parameter_str +'.pkl')
#X_test = test.ix[:,1:]
X_test = test.ix[:9,1:]
X_test.fillna(-1, inplace=True)
print "predict RandomForest Classifier..."
probs = cforest.predict_proba(X_test)
sorted_index = np.argsort(-np.array(probs))[:,:5]
result = pd.DataFrame(columns = {'hotel_cluster'})
result['hotel_cluster'] = np.array([np.array_str(sorted_index[i])[1:-1] for i in range(sorted_index.shape[0])])
result.hotel_cluster.to_csv(utils.model_path +
'results/submission_rf_all_without_time_' + parameter_str + '.csv', header=True, index_label='id')
|
import numpy as np
import pandas as pd
import sys
import os
from sklearn.externals import joblib
from sklearn.ensemble import RandomForestClassifier
scriptpath = os.path.dirname(os.path.realpath(sys.argv[0])) + '/../'
sys.path.append(os.path.abspath(scriptpath))
import utils
parameter_str = '_'.join(['top', str(utils.k), 'cw', str(utils.click_weight), 'year', utils.train_year])
cforest = joblib.load(utils.model_path + 'rf_all_without_time_' + parameter_str +'.pkl')
test = joblib.load(utils.processed_data_path + 'test_all_' + parameter_str +'.pkl')
X_test = test.ix[:,1:]
print "predict RandomForest Classifier..."
probs = cforest.predict_proba(X_test)
sorted_index = np.argsort(-np.array(probs))[:,:5]
result = pd.DataFrame(columns = {'hotel_cluster'})
result['hotel_cluster'] = np.array([np.array_str(sorted_index[i])[1:-1] for i in range(sorted_index.shape[0])])
result.hotel_cluster.to_csv(utils.model_path +
'results/submission_rf_all_without_time_' + parameter_str + '.csv', header=True, index_label='id')
|
Update the comment with the URL to the source
|
import Ember from 'ember';
import DS from 'ember-data';
const VALIDATION_ERROR_STATUSES = [400, 422];
export default DS.RESTAdapter.extend({
namespace: 'api',
isInvalid: function(status) {
return VALIDATION_ERROR_STATUSES.indexOf(status) >= 0;
},
// Override the parseErrorResponse method from RESTAdapter
// so that we can munge the modelState into an errors collection.
// The source of the original method can be found at:
// https://github.com/emberjs/data/blob/v2.1.0/packages/ember-data/lib/adapters/rest-adapter.js#L899
parseErrorResponse: function(responseText) {
let json = this._super(responseText),
strippedErrors = {},
jsonIsObject = json && (typeof json === 'object');
if (jsonIsObject && json.message) {
delete json.message;
}
if (jsonIsObject && json.modelState) {
Object.keys(json.modelState).forEach(key => {
let newKey = key.substring(key.indexOf('.') + 1).camelize();
strippedErrors[newKey] = json.modelState[key];
});
json.errors = this.strippedErrors;
delete json.modelState;
}
return json;
}
});
|
import Ember from 'ember';
import DS from 'ember-data';
const VALIDATION_ERROR_STATUSES = [400, 422];
export default DS.RESTAdapter.extend({
namespace: 'api',
isInvalid: function(status) {
return VALIDATION_ERROR_STATUSES.indexOf(status) >= 0;
},
// Override the parseErrorResponse method from RESTAdapter
// so that we can munge the modelState into an errors collection.
parseErrorResponse: function(responseText) {
let json = this._super(responseText),
strippedErrors = {},
jsonIsObject = json && (typeof json === 'object');
if (jsonIsObject && json.message) {
delete json.message;
}
if (jsonIsObject && json.modelState) {
Object.keys(json.modelState).forEach(key => {
let newKey = key.substring(key.indexOf('.') + 1).camelize();
strippedErrors[newKey] = json.modelState[key];
});
json.errors = this.strippedErrors;
delete json.modelState;
}
return json;
}
});
|
Use split+join instead of ES2018 feature(look behind)
https://github.com/tc39/proposal-regexp-lookbehind
This feature is not supported in many environment (ex. Node.js 8.9.x, Safari etc).
|
// @flow
import type {
DocumentPath,
DotNotationString,
} from 'mongolike-operations'
/**
* @public
* Parse DocumentPath into an array of property names.
*/
export function parseDocumentPath(docPath: DocumentPath): Array<string | number> {
// Many JS runtime cannot use look behind.
return docPath.split(/\\./).join('$$$').split(/[.[]/).map(
attribute => attribute.charAt(attribute.length - 1) === ']' ? parseInt(attribute.slice(0, -1)) : unescapePathDelimiter(attribute.split('$$$').join('\\.'))
)
}
/**
* Create DocumentPath from arguments.
*/
export function createDocumentPath(...attributes: Array<string | number>): DocumentPath {
const joined = attributes.reduce((docPath, attr) =>
typeof attr === 'string' ? `${docPath}.${escapePathDelimiter(attr)}` : `${docPath}[${attr.toString()}]`, '')
return (joined.charAt(0) === '.') ? joined.slice(1) : joined
}
/**
*
*/
export function convertToDotNotationString(docPath: DocumentPath): DotNotationString {
return docPath.replace(/\[(\d{1,})\]/g, '.$1')
}
function escapePathDelimiter(attr: string | number): string | number {
return typeof attr === 'number' ? attr : attr.replace(/\./g, '\\.')
}
function unescapePathDelimiter(attr: string | number): string | number {
return typeof attr === 'number' ? attr : attr.replace(/\\\./, '.')
}
|
// @flow
import type {
DocumentPath,
DotNotationString,
} from 'mongolike-operations'
/**
* @public
* Parse DocumentPath into an array of property names.
*/
export function parseDocumentPath(docPath: DocumentPath): Array<string | number> {
return docPath.split(/(?<!\\)[.[]/).map(
attribute => attribute.charAt(attribute.length - 1) === ']' ? parseInt(attribute.slice(0, -1)) : unescapePathDelimiter(attribute)
)
}
/**
* Create DocumentPath from arguments.
*/
export function createDocumentPath(...attributes: Array<string | number>): DocumentPath {
const joined = attributes.reduce((docPath, attr) =>
typeof attr === 'string' ? `${docPath}.${escapePathDelimiter(attr)}` : `${docPath}[${attr.toString()}]`, '')
return (joined.charAt(0) === '.') ? joined.slice(1) : joined
}
/**
*
*/
export function convertToDotNotationString(docPath: DocumentPath): DotNotationString {
return docPath.replace(/\[(\d{1,})\]/g, '.$1')
}
function escapePathDelimiter(attr: string | number): string | number {
return typeof attr === 'number' ? attr : attr.replace(/\./g, '\\.')
}
function unescapePathDelimiter(attr: string | number): string | number {
return typeof attr === 'number' ? attr : attr.replace(/\\\./, '.')
}
|
Remove unused before each call
|
describe('Satellite game', function () {
it('should exists', function () {
expect(s).to.be.an('object');
expect(s).to.have.property('config');
expect(s).to.have.property('init');
});
it('should contains ship properties', function () {
expect(s).to.have.deep.property('config.ship.hull');
expect(s).to.have.deep.property('config.ship.shields');
expect(s).to.have.deep.property('config.ship.maxSpeed');
});
it('should init the game', function () {
var spy = sinon.spy();
s.init('init', spy);
spy.called.should.equal.true;
expect(s).to.have.property('projector').and.to.be.an('object');
expect(s).to.have.property('loader').and.to.be.an('object');
expect(s).to.have.property('game').and.to.be.an('object');
});
});
|
describe('Satellite game', function () {
beforeEach(function () {
});
it('should exists', function () {
expect(s).to.be.an('object');
expect(s).to.have.property('config');
expect(s).to.have.property('init');
});
it('should contains ship properties', function () {
expect(s).to.have.deep.property('config.ship.hull');
expect(s).to.have.deep.property('config.ship.shields');
expect(s).to.have.deep.property('config.ship.maxSpeed');
});
it('should init the game', function () {
var spy = sinon.spy();
s.init('init', spy);
spy.called.should.equal.true;
expect(s).to.have.property('projector').and.to.be.an('object');
expect(s).to.have.property('loader').and.to.be.an('object');
expect(s).to.have.property('game').and.to.be.an('object');
});
});
|
Add route for static files.
|
package server
import (
"net"
"net/http"
"github.com/gorilla/mux"
"github.com/sirupsen/logrus"
)
// Server provides the web UI for interacting with the application. Users can
// login, post suggestions, and queue items if they have the appropriate
// permissions.
type Server struct {
listener net.Listener
log *logrus.Entry
stopped chan bool
}
// New creates a new server with the specified configuration.
func New(cfg *Config) (*Server, error) {
l, err := net.Listen("tcp", cfg.Addr)
if err != nil {
return nil, err
}
var (
router = mux.NewRouter()
server = http.Server{
Handler: router,
}
s = &Server{
listener: l,
log: logrus.WithField("context", "server"),
stopped: make(chan bool),
}
)
router.PathPrefix("/static").Handler(http.FileServer(HTTP))
go func() {
defer close(s.stopped)
defer s.log.Info("web server has stopped")
s.log.Info("starting web server...")
if err := server.Serve(l); err != nil {
s.log.Error(err.Error())
}
}()
return s, nil
}
// Close shuts down the server and waits for it to complete.
func (s *Server) Close() {
s.listener.Close()
<-s.stopped
}
|
package server
import (
"net"
"net/http"
"github.com/gorilla/mux"
"github.com/sirupsen/logrus"
)
// Server provides the web UI for interacting with the application. Users can
// login, post suggestions, and queue items if they have the appropriate
// permissions.
type Server struct {
listener net.Listener
log *logrus.Entry
stopped chan bool
}
// New creates a new server with the specified configuration.
func New(cfg *Config) (*Server, error) {
l, err := net.Listen("tcp", cfg.Addr)
if err != nil {
return nil, err
}
var (
router = mux.NewRouter()
server = http.Server{
Handler: router,
}
s = &Server{
listener: l,
log: logrus.WithField("context", "server"),
stopped: make(chan bool),
}
)
go func() {
defer close(s.stopped)
defer s.log.Info("web server has stopped")
s.log.Info("starting web server...")
if err := server.Serve(l); err != nil {
s.log.Error(err.Error())
}
}()
return s, nil
}
// Close shuts down the server and waits for it to complete.
func (s *Server) Close() {
s.listener.Close()
<-s.stopped
}
|
Remove un-used reference to Boom
|
'use strict';
const createLambdaContext = require('./createLambdaContext');
const debugLog = require('./debugLog');
module.exports = {
getFunctionOptions: function(fun, populatedFun) {
const handlerParts = fun.handler.split('/').pop().split('.');
return {
handlerName: handlerParts[1],
handlerPath: fun.getRootPath(handlerParts[0]),
funTimeout: (populatedFun.timeout || 6) * 1000,
babelOptions: ((populatedFun.custom || {}).runtime || {}).babel,
};
},
createHandler: function(funOptions, options) {
if (!options.skipCacheInvalidation) {
debugLog('Invalidating cache...');
for (let key in require.cache) { // eslint-disable-line prefer-const
// Require cache invalidation, brutal and fragile.
// Might cause errors, if so please submit an issue.
if (!key.match('node_modules')) delete require.cache[key];
}
}
debugLog(`Loading handler... (${funOptions.handlerPath})`);
const handler = require(funOptions.handlerPath)[funOptions.handlerName];
if (typeof handler !== 'function') {
throw new Error(`Serverless-offline: handler for '${funName}' is not a function`);
}
return handler;
}
}
|
'use strict';
const Boom = require('boom');
const createLambdaContext = require('./createLambdaContext');
const debugLog = require('./debugLog');
module.exports = {
getFunctionOptions: function(fun, populatedFun) {
const handlerParts = fun.handler.split('/').pop().split('.');
return {
handlerName: handlerParts[1],
handlerPath: fun.getRootPath(handlerParts[0]),
funTimeout: (populatedFun.timeout || 6) * 1000,
babelOptions: ((populatedFun.custom || {}).runtime || {}).babel,
};
},
createHandler: function(funOptions, options) {
if (!options.skipCacheInvalidation) {
debugLog('Invalidating cache...');
for (let key in require.cache) { // eslint-disable-line prefer-const
// Require cache invalidation, brutal and fragile.
// Might cause errors, if so please submit an issue.
if (!key.match('node_modules')) delete require.cache[key];
}
}
debugLog(`Loading handler... (${funOptions.handlerPath})`);
const handler = require(funOptions.handlerPath)[funOptions.handlerName];
if (typeof handler !== 'function') {
throw new Error(`Serverless-offline: handler for '${funName}' is not a function`);
}
return handler;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.