text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
---|---|---|
Add time cache to static cache | importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.0.0/workbox-sw.js')
const staticCache = 'react-base-static-v1'
const dynamicCache = 'react-base-dynamic-v1'
const timeCache = 30 * 24 * 60 * 60
self.workbox.skipWaiting()
self.workbox.clientsClaim()
workbox.core.setCacheNameDetails({
precache: staticCache,
runtime: dynamicCache
})
workbox.routing.registerRoute(
/\.(?:js|css)$/,
workbox.strategies.cacheFirst({
cacheName: staticCache,
plugins: [
new workbox.expiration.Plugin({
maxEntries: 20,
maxAgeSeconds: timeCache
}),
],
}),
)
workbox.routing.registerRoute(
new RegExp('https://fonts.(?:googleapis|gstatic).com/(.*)'),
workbox.strategies.cacheFirst({
cacheName: staticCache,
plugins: [
new workbox.expiration.Plugin({
maxEntries: 10,
}),
],
}),
)
workbox.routing.registerRoute(
new RegExp('/content/(.*)'),
workbox.strategies.staleWhileRevalidate({
cacheName: dynamicCache,
plugins: [
new workbox.expiration.Plugin({
maxEntries: 60,
maxAgeSeconds: timeCache
}),
],
}),
)
| importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.0.0/workbox-sw.js')
const staticCache = 'react-base-static-v1'
const dynamicCache = 'react-base-dynamic-v1'
const timeCache = 30 * 24 * 60 * 60
self.workbox.skipWaiting()
self.workbox.clientsClaim()
workbox.core.setCacheNameDetails({
precache: staticCache,
runtime: dynamicCache
})
workbox.routing.registerRoute(
/\.(?:js|css)$/,
workbox.strategies.cacheFirst({
cacheName: staticCache
}),
)
workbox.routing.registerRoute(
new RegExp('https://fonts.(?:googleapis|gstatic).com/(.*)'),
workbox.strategies.cacheFirst({
cacheName: staticCache,
plugins: [
new workbox.expiration.Plugin({
maxEntries: 10,
}),
],
}),
)
workbox.routing.registerRoute(
new RegExp('/content/(.*)'),
workbox.strategies.staleWhileRevalidate({
cacheName: dynamicCache,
plugins: [
new workbox.expiration.Plugin({
maxEntries: 60,
maxAgeSeconds: timeCache
}),
],
}),
)
|
Add tra to plugin info
git-svn-id: 9bac41f8ebc9458fc3e28d41abfab39641e8bd1c@31175 b456876b-0849-0410-b77d-98878d47e9d5 | <?php
// (c) Copyright 2002-2010 by authors of the Tiki Wiki/CMS/Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$
function wikiplugin_attributes_info() {
return array(
'name' => tra('Attributes'),
'documentation' => tra('PluginAttributes'),
'description' => tra('Allows for generic attributes to be assigned to the current object. Attributes are provided as parameters. For tiki.geo.lat, {attributes tiki_geo_lat=...}. Removing the plugin or values in it will not remove the attributes.'),
'prefs' => array( 'wikiplugin_attributes' ),
'extraparams' => true,
'defaultfilter' => 'text',
'params' => array(
),
);
}
function wikiplugin_attributes_save( $context, $data, $params ) {
global $attributelib; require_once 'lib/attributes/attributelib.php';
foreach( $params as $key => $value ) {
$key = str_replace( '_', '.', $key );
$attributelib->set_attribute( $context['type'], $context['object'], $key, $value );
}
}
function wikiplugin_attributes($data, $params) {
return '';
}
| <?php
// (c) Copyright 2002-2010 by authors of the Tiki Wiki/CMS/Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$
function wikiplugin_attributes_info() {
return array(
'name' => tra('Attributes'),
'documentation' => 'PluginAttributes',
'description' => tra('Allows for generic attributes to be assigned to the current object. Attributes are provided as parameters. For tiki.geo.lat, {attributes tiki_geo_lat=...}. Removing the plugin or values in it will not remove the attributes.'),
'prefs' => array( 'wikiplugin_attributes' ),
'extraparams' => true,
'defaultfilter' => 'text',
'params' => array(
),
);
}
function wikiplugin_attributes_save( $context, $data, $params ) {
global $attributelib; require_once 'lib/attributes/attributelib.php';
foreach( $params as $key => $value ) {
$key = str_replace( '_', '.', $key );
$attributelib->set_attribute( $context['type'], $context['object'], $key, $value );
}
}
function wikiplugin_attributes($data, $params) {
return '';
}
|
Add caching to Elron provider (api) | const got = require('got');
const cache = require('../utils/cache.js');
const time = require('../utils/time.js');
// Get trips for stop.
async function getTrips(id) {
const now = time.getSeconds();
return (await cache.use('elron-trips', id, async () => {
const data = JSON.parse((await got(`http://elron.ee/api/v1/stop?stop=${encodeURIComponent(id)}`)).body).data;
if (!data) throw new Error("Provider 'Elron' is not returning data");
if (data.text) throw new Error(data.text);
return data.map((trip) => ({
time: time.toSeconds(trip.plaaniline_aeg),
countdown: time.toSeconds(trip.plaaniline_aeg) - now,
name: trip.reis,
destination: trip.liin,
type: 'train',
live: false,
provider: 'elron'
}));
})).filter((trip) => trip.time > now).slice(0, 15);
}
module.exports = {
getTrips
};
| const got = require('got');
const cache = require('../utils/cache.js');
const time = require('../utils/time.js');
// Get trips for stop.
async function getTrips(id) {
const now = time.getSeconds();
const data = JSON.parse((await got(`http://elron.ee/api/v1/stop?stop=${encodeURIComponent(id)}`)).body).data;
if (!data) throw new Error("Provider 'Elron' is not returning data");
if (data.text) throw new Error(data.text);
const trips = [];
for (const trip of data) if (time.toSeconds(trip.plaaniline_aeg) > now) trips.push({
time: time.toSeconds(trip.plaaniline_aeg),
countdown: time.toSeconds(trip.plaaniline_aeg) - now,
name: trip.reis,
destination: trip.liin,
type: 'train',
live: false,
provider: 'elron'
});
return trips.slice(0, 15);
}
module.exports = {
getTrips
};
|
zjsunit: Use modern spread arguments syntax.
Signed-off-by: Anders Kaseorg <[email protected]> | const _ = require('underscore/underscore.js');
// Stubs don't do any magical modifications to your namespace. They
// just provide you a function that records what arguments get passed
// to it. To use stubs as something more like "spies," use something
// like set_global() to override your namespace.
exports.make_stub = function () {
const self = {};
self.num_calls = 0;
self.f = function (...args) {
self.last_call_args = args;
self.num_calls += 1;
return true;
};
self.get_args = function (...param_names) {
const result = {};
_.each(param_names, function (name, i) {
result[name] = self.last_call_args[i];
});
return result;
};
return self;
};
exports.with_stub = function (f) {
const stub = exports.make_stub();
f(stub);
assert.equal(stub.num_calls, 1);
};
(function test_ourselves() {
exports.with_stub(function (stub) {
stub.f('blue', 42);
const args = stub.get_args('color', 'n');
assert.equal(args.color, 'blue');
assert.equal(args.n, 42);
});
}());
| const _ = require('underscore/underscore.js');
// Stubs don't do any magical modifications to your namespace. They
// just provide you a function that records what arguments get passed
// to it. To use stubs as something more like "spies," use something
// like set_global() to override your namespace.
exports.make_stub = function () {
const self = {};
self.num_calls = 0;
self.f = function () {
self.last_call_args = _.clone(arguments);
self.num_calls += 1;
return true;
};
self.get_args = function () {
const param_names = arguments;
const result = {};
_.each(param_names, function (name, i) {
result[name] = self.last_call_args[i];
});
return result;
};
return self;
};
exports.with_stub = function (f) {
const stub = exports.make_stub();
f(stub);
assert.equal(stub.num_calls, 1);
};
(function test_ourselves() {
exports.with_stub(function (stub) {
stub.f('blue', 42);
const args = stub.get_args('color', 'n');
assert.equal(args.color, 'blue');
assert.equal(args.n, 42);
});
}());
|
Remove @Before, not useful for static classes | package com.alexrnl.commons.gui.swing;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import org.junit.Test;
/**
* Test suite for the {@link SwingUtils} class.
* @author Alex
*/
public class SwingUtilsTest {
/**
* Test method for {@link com.alexrnl.commons.gui.swing.SwingUtils#setLookAndFeel(java.lang.String)}.
*/
@Test
public void testSetLookAndFeel () {
assertFalse(SwingUtils.setLookAndFeel(null));
assertFalse(SwingUtils.setLookAndFeel(""));
for (final LookAndFeelInfo laf : UIManager.getInstalledLookAndFeels()) {
assertTrue(SwingUtils.setLookAndFeel(laf.getName()));
Logger.getLogger(SwingUtils.class.getName()).setLevel(Level.FINE);
}
UIManager.installLookAndFeel(new LookAndFeelInfo("LDR", "com.alexrnl.commons.gui.swing.ldr"));
assertFalse(SwingUtils.setLookAndFeel("LDR"));
}
}
| package com.alexrnl.commons.gui.swing;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import org.junit.Before;
import org.junit.Test;
/**
* Test suite for the {@link SwingUtils} class.
* @author Alex
*/
public class SwingUtilsTest {
/**
* Test attributes.
*/
@Before
public void setUp () {
}
/**
* Test method for {@link com.alexrnl.commons.gui.swing.SwingUtils#setLookAndFeel(java.lang.String)}.
*/
@Test
public void testSetLookAndFeel () {
assertFalse(SwingUtils.setLookAndFeel(null));
assertFalse(SwingUtils.setLookAndFeel(""));
for (final LookAndFeelInfo laf : UIManager.getInstalledLookAndFeels()) {
assertTrue(SwingUtils.setLookAndFeel(laf.getName()));
Logger.getLogger(SwingUtils.class.getName()).setLevel(Level.FINE);
}
UIManager.installLookAndFeel(new LookAndFeelInfo("LDR", "com.alexrnl.commons.gui.swing.ldr"));
assertFalse(SwingUtils.setLookAndFeel("LDR"));
}
}
|
Add example for generic file tree to Javadoc
`SingletonFileTree`s aren't generic file trees. | /*
* Copyright 2019 the original author or authors.
*
* 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.gradle.internal.fingerprint;
import org.gradle.api.file.FileVisitor;
import org.gradle.api.internal.file.FileTreeInternal;
import org.gradle.internal.snapshot.FileSystemSnapshot;
/**
* A snapshotter for generic file trees, which are not based on a directory on disk.
*
* Examples of a generic file tree is a {@link org.gradle.api.internal.file.archive.TarFileTree} backed by a non-file resource.
* This is needed to build a Merkle directory tree from the elements of a file tree obtained by {@link org.gradle.api.file.FileTree#visit(FileVisitor)}.
*/
public interface GenericFileTreeSnapshotter {
FileSystemSnapshot snapshotFileTree(FileTreeInternal tree);
}
| /*
* Copyright 2019 the original author or authors.
*
* 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.gradle.internal.fingerprint;
import org.gradle.api.file.FileVisitor;
import org.gradle.api.internal.file.FileTreeInternal;
import org.gradle.internal.snapshot.FileSystemSnapshot;
/**
* A snapshotter for generic file trees, which are not based on a directory on disk.
*
* This is needed to build a Merkle directory tree from the elements of a file tree obtained by {@link org.gradle.api.file.FileTree#visit(FileVisitor)}.
*/
public interface GenericFileTreeSnapshotter {
FileSystemSnapshot snapshotFileTree(FileTreeInternal tree);
}
|
Change doc style in addEvent() | /* Helper function to add an event listener.
* @param {Element} el - The element we want to add an event listener to.
* @param {Event} event - The event we want to listen to.
* @param {function} callback - The callback function to call when the event is
* transmitted.
*/
function addEvent(el, event, callback) {
if ('addEventListener' in el) {
el.addEventListener(event, callback, false);
} else {
el['e' + event + callback] = callback;
el[event + callback] = function() {
el['e' + event + callback](window.event);
};
el.attachEvent('on' + event, el[event + callback]);
}
}
function clearWarningOnInput(inputId, warningId) {
var el= document.getElementById(inputId);
addEvent(el, 'input', function() {
var cl = document.getElementById(warningId).classList;
if (!cl.contains('hidden-warning')) {
cl.add('hidden-warning');
}
});
}
| /* Helper function to add an event listener.
* @param el The element we want to add an event listener to.
* @param event The event we want to listen to.
* @param callback The callback function to call when the event is transmitted.
*/
function addEvent(el, event, callback) {
if ('addEventListener' in el) {
el.addEventListener(event, callback, false);
} else {
el['e' + event + callback] = callback;
el[event + callback] = function() {
el['e' + event + callback](window.event);
};
el.attachEvent('on' + event, el[event + callback]);
}
}
function clearWarningOnInput(inputId, warningId) {
var el= document.getElementById(inputId);
addEvent(el, 'input', function() {
var cl = document.getElementById(warningId).classList;
if (!cl.contains('hidden-warning')) {
cl.add('hidden-warning');
}
});
}
|
Fix invalid annotation. The type of `self` in base class should be left to be deduced to the child type. | """Context manager base class man-in-the-middling the global stdout."""
import sys
class Error(Exception):
"""Base class for all exception of this module."""
class InvalidUsageError(Error):
"""Error raised on incorrect API uses."""
class StdoutInterceptor():
"""Context manager base class man-in-the-middling the global stdout."""
def __init__(self):
self._original_stdout = None
def __enter__(self):
"""Replaces global stdout and starts printing status after last write."""
self._original_stdout = sys.stdout
sys.stdout = self
return self
def __exit__(self, exc_type, exc_value, traceback) -> None:
"""Terminate this TaskManager and restore global stdout."""
del exc_type, exc_value, traceback # Unused.
if self._original_stdout is None:
raise InvalidUsageError(
"Object must be used as a context manager, in a `with:` statement.")
sys.stdout = self._original_stdout
@property
def stdout(self):
"""Returns the original stdout this class is replacing."""
if self._original_stdout is None:
raise InvalidUsageError(
"Object must be used as a context manager, in a `with:` statement.")
return self._original_stdout
| """Context manager base class man-in-the-middling the global stdout."""
import sys
class Error(Exception):
"""Base class for all exception of this module."""
class InvalidUsageError(Error):
"""Error raised on incorrect API uses."""
class StdoutInterceptor():
"""Context manager base class man-in-the-middling the global stdout."""
def __init__(self):
self._original_stdout = None
def __enter__(self) -> 'StdoutInterceptor':
"""Replaces global stdout and starts printing status after last write."""
self._original_stdout = sys.stdout
sys.stdout = self
return self
def __exit__(self, exc_type, exc_value, traceback) -> None:
"""Terminate this TaskManager and restore global stdout."""
del exc_type, exc_value, traceback # Unused.
if self._original_stdout is None:
raise InvalidUsageError(
"Object must be used as a context manager, in a `with:` statement.")
sys.stdout = self._original_stdout
@property
def stdout(self):
"""Returns the original stdout this class is replacing."""
if self._original_stdout is None:
raise InvalidUsageError(
"Object must be used as a context manager, in a `with:` statement.")
return self._original_stdout
|
Fix the way it uses the 'src' dir so the package is no longer installed as 'src'.
Note that although there is this fancy package_dir renaming
functionality available to setup.py, and it will work if you do a
setup.py install, it doesn't work properly when you run setup.py
develop. | import setuptools
from src.version import __VERSION_STR__
setuptools.setup(
name='powser',
version=__VERSION_STR__,
description=(
'Front-end package manager inspired by bower utilizing cdnjs. '
'See https://github.com/JDeuce/powser for more.'
),
author='Josh Jaques',
author_email='[email protected]',
url='https://github.com/JDeuce/powser',
package_dir={'powser': 'src'},
packages=['powser'],
install_requires=open('requirements.txt').read().splitlines(),
license='MIT License',
zip_safe=False,
keywords='front-end package management cdnjs bower',
classifiers=[],
entry_points={
'console_scripts': [
'powser = powser.main:main'
]
}
)
| import setuptools
from src.version import __VERSION_STR__
setuptools.setup(
name='powser',
version=__VERSION_STR__,
description=(
'Front-end package manager inspired by bower utilizing cdnjs. '
'See https://github.com/JDeuce/powser for more.'
),
author='Josh Jaques',
author_email='[email protected]',
url='https://github.com/JDeuce/powser',
py_modules=['src'],
install_requires=open('requirements.txt').read().splitlines(),
license='MIT License',
zip_safe=False,
keywords='front-end package management cdnjs bower',
classifiers=[],
packages=setuptools.find_packages(),
entry_points={
'console_scripts': [
'powser = src.main:main'
]
}
)
|
Remove all permisson for contact API | from rest_framework import serializers
from rest_framework.views import APIView
from rest_framework.response import Response
from django import http
from .tasks import send_contact_form_inquiry
# Serializers define the API representation.
class ContactSerializer(serializers.Serializer):
email = serializers.EmailField()
name = serializers.CharField(max_length=255)
content = serializers.CharField()
source = serializers.CharField(max_length=255)
organization = serializers.CharField(max_length=255, required=False)
def create(self, validated_data):
return validated_data
class ContactAPIView(APIView):
authentication_classes = []
permission_classes = []
def post(self, request, *args, **kwargs):
serializer = ContactSerializer(data=request.data, context={'request': request})
serializer.is_valid(raise_exception=True)
# call async task to send email
send_contact_form_inquiry.delay(**serializer.data)
if request.GET.get('next') and not request.is_ajax():
# TODO should this be validated?
return http.HttpResponseRedirect(request.GET.get('next'))
data = {"status": "sent"}
return Response(data)
| from rest_framework import serializers
from rest_framework.views import APIView
from rest_framework.response import Response
from django import http
from .tasks import send_contact_form_inquiry
# Serializers define the API representation.
class ContactSerializer(serializers.Serializer):
email = serializers.EmailField()
name = serializers.CharField(max_length=255)
content = serializers.CharField()
source = serializers.CharField(max_length=255)
organization = serializers.CharField(max_length=255, required=False)
def create(self, validated_data):
return validated_data
class ContactAPIView(APIView):
permission_classes = ()
def post(self, request, *args, **kwargs):
serializer = ContactSerializer(data=request.data, context={'request': request})
serializer.is_valid(raise_exception=True)
# call async task to send email
send_contact_form_inquiry.delay(**serializer.data)
if request.GET.get('next') and not request.is_ajax():
# TODO should this be validated?
return http.HttpResponseRedirect(request.GET.get('next'))
data = {"status": "sent"}
return Response(data)
|
Add a words per line function | """Class to show file manipulations"""
import sys
original_file = open('wasteland.txt', mode='rt', encoding='utf-8')
file_to_write = open('wasteland-copy.txt', mode='wt', encoding='utf-8')
file_to_write.write("What are the roots that clutch, ")
file_to_write.write('what branches grow\n')
file_to_write.close()
file_reading = open('wasteland.txt', mode='rt', encoding='utf-8')
for line in file_reading.readlines():
print(line)
file_to_append = open('wasteland-copy.txt', mode='at', encoding='utf-8')
file_to_append.writelines(
['Son of man,\n',
'You cannot say, or guess, ',
'for you know only,\n',
'A heap of broken images, ',
'where the sun beats\n'])
file_to_append.close()
def words_per_line(flo):
return [len(line.split()) for line in flo.readlines()]
| """Class to show file manipulations"""
import sys
original_file = open('wasteland.txt', mode='rt', encoding='utf-8')
file_to_write = open('wasteland-copy.txt', mode='wt', encoding='utf-8')
file_to_write.write("What are the roots that clutch, ")
file_to_write.write('what branches grow\n')
file_to_write.close()
file_reading = open('wasteland.txt', mode='rt', encoding='utf-8')
for line in file_reading.readlines():
print(line)
file_to_append = open('wasteland-copy.txt', mode='at', encoding='utf-8')
file_to_append.writelines(
['Son of man,\n',
'You cannot say, or guess, ',
'for you know only,\n',
'A heap of broken images, ',
'where the sun beats\n'])
file_to_append.close() |
Update to use newer oauth style | import os
mylang = 'test'
family = 'wikipedia'
custom_path = os.path.expanduser('~/user-config.py')
if os.path.exists(custom_path):
with open(custom_path, 'rb') as f:
exec(compile(f.read(), custom_path, 'exec'), globals())
del f
# Clean up temp variables, since pwb issues a warning otherwise
# to help people catch misspelt config
del custom_path
# Things that should be non-easily-overridable
for fam in (
'wikipedia', 'commons', 'meta', 'wikiboots', 'wikimedia',
'wikiquote', 'wikisource', 'wikisource', 'wiktionary', 'wikiversity',
'wikidata', 'mediawiki'
):
usernames[fam]['*'] = os.environ['USER']
if 'ACCESS_KEY' in os.environ:
# If OAuth integration is available, take it
authenticate[fam]['*'] = (
os.environ['CLIENT_ID'],
os.environ['CLIENT_SECRET'],
os.environ['ACCESS_KEY'],
os.environ['ACCESS_SECRET']
)
del fam
| import os
mylang = 'test'
family = 'wikipedia'
custom_path = os.path.expanduser('~/user-config.py')
if os.path.exists(custom_path):
with open(custom_path, 'rb') as f:
exec(compile(f.read(), custom_path, 'exec'), globals())
del f
# Clean up temp variables, since pwb issues a warning otherwise
# to help people catch misspelt config
del custom_path
# Things that should be non-easily-overridable
for fam in (
'wikipedia', 'commons', 'meta', 'wikiboots', 'wikimedia',
'wikiquote', 'wikisource', 'wikisource', 'wiktionary', 'wikiversity',
'wikidata', 'mediawiki'
):
usernames[fam]['*'] = os.environ['USER']
del fam
# If OAuth integration is available, take it
if 'CLIENT_ID' in os.environ:
authenticate['*'] = (
os.environ['CLIENT_ID'],
os.environ['CLIENT_SECRET'],
os.environ['ACCESS_KEY'],
os.environ['ACCESS_SECRET']
)
|
Use spec reporter to know which specs hang | "use babel"
import Mocha from 'mocha'
import fs from 'fs-plus'
import {assert} from 'chai'
export default function (testPaths) {
global.assert = assert
const mocha = new Mocha({reporter: 'spec'})
for (let testPath of testPaths) {
if (fs.isDirectorySync(testPath)) {
for (let testFilePath of fs.listTreeSync(testPath)) {
if (/\.test\.(coffee|js)$/.test(testFilePath)) {
mocha.addFile(testFilePath)
}
}
} else {
mocha.addFile(testPath)
}
}
mocha.run(function (failures) {
if (failures === 0) {
process.exit(0)
} else {
process.exit(1)
}
})
}
| "use babel"
import Mocha from 'mocha'
import fs from 'fs-plus'
import {assert} from 'chai'
export default function (testPaths) {
global.assert = assert
const mocha = new Mocha({reporter: 'dot'})
for (let testPath of testPaths) {
if (fs.isDirectorySync(testPath)) {
for (let testFilePath of fs.listTreeSync(testPath)) {
if (/\.test\.(coffee|js)$/.test(testFilePath)) {
mocha.addFile(testFilePath)
}
}
} else {
mocha.addFile(testPath)
}
}
mocha.run(function (failures) {
if (failures === 0) {
process.exit(0)
} else {
process.exit(1)
}
})
}
|
Use explicit py-amqp transport instead of amqp in integration tests | from __future__ import absolute_import, unicode_literals
import os
import pytest
import kombu
from .common import BasicFunctionality
def get_connection(
hostname, port, vhost):
return kombu.Connection('pyamqp://{}:{}'.format(hostname, port))
@pytest.fixture()
def connection(request):
# this fixture yields plain connections to broker and TLS encrypted
return get_connection(
hostname=os.environ.get('RABBITMQ_HOST', 'localhost'),
port=os.environ.get('RABBITMQ_5672_TCP', '5672'),
vhost=getattr(
request.config, "slaveinput", {}
).get("slaveid", None),
)
@pytest.mark.env('py-amqp')
@pytest.mark.flaky(reruns=5, reruns_delay=2)
class test_PyAMQPBasicFunctionality(BasicFunctionality):
pass
| from __future__ import absolute_import, unicode_literals
import os
import pytest
import kombu
from .common import BasicFunctionality
def get_connection(
hostname, port, vhost):
return kombu.Connection('amqp://{}:{}'.format(hostname, port))
@pytest.fixture()
def connection(request):
# this fixture yields plain connections to broker and TLS encrypted
return get_connection(
hostname=os.environ.get('RABBITMQ_HOST', 'localhost'),
port=os.environ.get('RABBITMQ_5672_TCP', '5672'),
vhost=getattr(
request.config, "slaveinput", {}
).get("slaveid", None),
)
@pytest.mark.env('py-amqp')
@pytest.mark.flaky(reruns=5, reruns_delay=2)
class test_PyAMQPBasicFunctionality(BasicFunctionality):
pass
|
Call the methods only if they exist. | package org.torquebox.stomp.component;
import org.projectodd.stilts.stomp.StompException;
import org.projectodd.stilts.stomp.StompMessage;
import org.projectodd.stilts.stomplet.Stomplet;
import org.projectodd.stilts.stomplet.StompletConfig;
import org.projectodd.stilts.stomplet.Subscriber;
public class DirectStompletComponent implements Stomplet {
public DirectStompletComponent(XAStompletComponent component) {
this.component = component;
}
@Override
public void initialize(StompletConfig config) throws StompException {
this.component._callRubyMethodIfDefined( "configure", config );
}
@Override
public void destroy() throws StompException {
this.component._callRubyMethodIfDefined( "destroy" );
}
@Override
public void onMessage(StompMessage message) throws StompException {
this.component._callRubyMethodIfDefined( "on_message", message );
}
@Override
public void onSubscribe(Subscriber subscriber) throws StompException {
this.component._callRubyMethodIfDefined( "on_subscribe", subscriber );
}
@Override
public void onUnsubscribe(Subscriber subscriber) throws StompException {
this.component._callRubyMethodIfDefined( "on_unsubscribe", subscriber );
}
private XAStompletComponent component;
}
| package org.torquebox.stomp.component;
import org.projectodd.stilts.stomp.StompException;
import org.projectodd.stilts.stomp.StompMessage;
import org.projectodd.stilts.stomplet.Stomplet;
import org.projectodd.stilts.stomplet.StompletConfig;
import org.projectodd.stilts.stomplet.Subscriber;
public class DirectStompletComponent implements Stomplet {
public DirectStompletComponent(XAStompletComponent component) {
this.component = component;
}
@Override
public void initialize(StompletConfig config) throws StompException {
this.component._callRubyMethod( "configure", config );
}
@Override
public void destroy() throws StompException {
this.component._callRubyMethod( "destroy" );
}
@Override
public void onMessage(StompMessage message) throws StompException {
this.component._callRubyMethod( "on_message", message );
}
@Override
public void onSubscribe(Subscriber subscriber) throws StompException {
this.component._callRubyMethod( "on_subscribe", subscriber );
}
@Override
public void onUnsubscribe(Subscriber subscriber) throws StompException {
this.component._callRubyMethod( "on_unsubscribe", subscriber );
}
private XAStompletComponent component;
}
|
Update and try fix bug with migration | <?php
use yii\db\Migration;
class m160219_091156_createUser extends Migration
{
public function up()
{
$userName = 'webmaster';
$tableName = \dektrium\user\models\User::tableName();
$query = 'SELECT COUNT(*) FROM '.$tableName.' WHERE `username`=:username';
$count = \Yii::$app->db->createCommand($query, [':username'=>$userName])->queryScalar();
if($count>0)
return true;
$user = \Yii::createObject([
'class' => \dektrium\user\models\User::className(),
'scenario' => 'create',
'username' => $userName,
'password' => $userName,
'email' => $userName.'@yii2enterprise.dev',
]);
return $user->create();
}
public function down()
{
echo "m160219_091156_createUser cannot be reverted.\n";
return false;
}
/*
// Use safeUp/safeDown to run migration code within a transaction
public function safeUp()
{
}
public function safeDown()
{
}
*/
}
| <?php
use yii\db\Migration;
class m160219_091156_createUser extends Migration
{
public function up()
{
$userName = 'webmaster';
$tableName = \dektrium\user\models\User::tableName();
$query = 'SELECT COUNT(*) FROM '.$tableName.' WHERE `username`=:username';
$count = Yii::$app->db->createCommand($query, [':username'=>$userName])->queryScalar();
if($count>0)
return true;
$user = \Yii::createObject([
'class' => \dektrium\user\models\User::className(),
'scenario' => 'create',
'username' => $userName,
'password' => $userName,
'email' => $userName.'@yii2enterprise.dev',
]);
return $user->create();
}
public function down()
{
echo "m160219_091156_createUser cannot be reverted.\n";
return false;
}
/*
// Use safeUp/safeDown to run migration code within a transaction
public function safeUp()
{
}
public function safeDown()
{
}
*/
}
|
Increase datagrid icon column width | /*
* Copyright 2016 Crown Copyright
*
* 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 stroom.data.client.presenter;
public final class ColumnSizeConstants {
public static final int CHECKBOX_COL = 16;
public static final int ICON_COL = 23;
public static final int SMALL_COL = 70;
public static final int MEDIUM_COL = 100;
public static final int BIG_COL = 400;
public static final int DATE_COL = 160;
private ColumnSizeConstants() {
// Constants.
}
}
| /*
* Copyright 2016 Crown Copyright
*
* 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 stroom.data.client.presenter;
public final class ColumnSizeConstants {
public static final int CHECKBOX_COL = 16;
public static final int ICON_COL = 20;
public static final int SMALL_COL = 70;
public static final int MEDIUM_COL = 100;
public static final int BIG_COL = 400;
public static final int DATE_COL = 160;
private ColumnSizeConstants() {
// Constants.
}
}
|
Add manual method to trigger dialogs | package tv.rocketbeans.supermafiosi.core;
import java.util.ArrayList;
import java.util.List;
import com.badlogic.gdx.InputAdapter;
import tv.rocketbeans.supermafiosi.i18n.Bundle;
public class DialogManager extends InputAdapter {
private List<Dialog> dialogs = new ArrayList<Dialog>();
private Dialog currentDialog;
public void addDialog(String dialogKey, String avatarKey) {
dialogs.add(new Dialog(Bundle.translations.get(dialogKey), avatarKey));
}
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
return nextDialog();
}
public boolean nextDialog() {
if (dialogs.size() > 0) {
currentDialog = dialogs.remove(0);
return true;
} else {
currentDialog = null;
}
return false;
}
public Dialog getCurrentDialog() {
return currentDialog;
}
}
| package tv.rocketbeans.supermafiosi.core;
import java.util.ArrayList;
import java.util.List;
import com.badlogic.gdx.InputAdapter;
import tv.rocketbeans.supermafiosi.i18n.Bundle;
public class DialogManager extends InputAdapter {
private List<Dialog> dialogs = new ArrayList<Dialog>();
private Dialog currentDialog;
public void addDialog(String dialogKey, String avatarKey) {
dialogs.add(new Dialog(Bundle.translations.get(dialogKey), avatarKey));
}
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
if (dialogs.size() > 0) {
currentDialog = dialogs.remove(0);
return true;
} else {
currentDialog = null;
}
return false;
}
public Dialog getCurrentDialog() {
return currentDialog;
}
}
|
Moderator: Update name being sent to the server
Update the name being sent to the server to be the
name that was put into the currentName variable. | var socket = io();
//var verifyNameFormState = false;
socket.on('moderate name', function(msg){
$('#currentName').text(msg);
});
$('#accept').click(function(e){
// Prevent JavaScript from doing normal functionality
e.preventDefault();
// Serialize the name and whether the name is valid
var nameInfo = JSON.stringify([$('#currentName').text(), true]);
// Emit a message to accept the current name
socket.emit('add name', nameInfo);
// Disable form after first submission
$('form').unbind('accept');
$('form').accept(function(e){ e.preventDefault(); });
});
$('#decline').click(function(e){
// Prevent JavaScript from doing normal functionality
e.preventDefault();
// Serialize the name and whether the name is valid
var nameInfo = JSON.stringify([$('#currentName').text(), false]);
// Emit a message to accept the current name
socket.emit('add name', nameInfo);
// Disable form after first submission
$('form').unbind('decline');
$('form').decline(function(e){ e.preventDefault(); });
});
| var socket = io();
//var verifyNameFormState = false;
socket.on('moderate name', function(msg){
$('#currentName').text(msg);
});
$('#accept').click(function(e){
// Prevent JavaScript from doing normal functionality
e.preventDefault();
// Serialize the name and whether the name is valid
var nameInfo = JSON.stringify({msg, true});
// Emit a message to accept the current name
socket.emit('add name', nameInfo);
// Disable form after first submission
$('form').unbind('accept');
$('form').accept(function(e){ e.preventDefault(); });
});
$('#decline').click(function(e){
// Prevent JavaScript from doing normal functionality
e.preventDefault();
// Serialize the name and whether the name is valid
var nameInfo = JSON.stringify({msg, false});
// Emit a message to accept the current name
socket.emit('add name', nameInfo);
// Disable form after first submission
$('form').unbind('decline');
$('form').decline(function(e){ e.preventDefault(); });
});
|
Remove size keyword when generating netlist | #!/usr/bin/env python
from distutils.core import setup
setup(name='lcapy',
version='0.21.6',
description='Symbolic linear circuit analysis',
author='Michael Hayes',
requires=['sympy', 'numpy', 'scipy'],
author_email='[email protected]',
url='https://github.com/mph-/lcapy',
download_url='https://github.com/mph-/lcapy',
py_modules=['lcapy.core', 'lcapy.netlist', 'lcapy.oneport', 'lcapy.twoport', 'lcapy.threeport', 'lcapy.schematic', 'lcapy.mna', 'lcapy.plot', 'lcapy.latex', 'lcapy.grammar', 'lcapy.parser', 'lcapy.schemcpts', 'lcapy.schemmisc', 'lcapy.mnacpts', 'lcapy.sympify', 'lcapy.acdc', 'lcapy.network', 'lcapy.circuit', 'lcapy.netfile', 'lcapy.system', 'lcapy.laplace'],
scripts=['scripts/schtex.py'],
license='LGPL'
)
| #!/usr/bin/env python
from distutils.core import setup
setup(name='lcapy',
version='0.21.5',
description='Symbolic linear circuit analysis',
author='Michael Hayes',
requires=['sympy', 'numpy', 'scipy'],
author_email='[email protected]',
url='https://github.com/mph-/lcapy',
download_url='https://github.com/mph-/lcapy',
py_modules=['lcapy.core', 'lcapy.netlist', 'lcapy.oneport', 'lcapy.twoport', 'lcapy.threeport', 'lcapy.schematic', 'lcapy.mna', 'lcapy.plot', 'lcapy.latex', 'lcapy.grammar', 'lcapy.parser', 'lcapy.schemcpts', 'lcapy.schemmisc', 'lcapy.mnacpts', 'lcapy.sympify', 'lcapy.acdc', 'lcapy.network', 'lcapy.circuit', 'lcapy.netfile', 'lcapy.system', 'lcapy.laplace'],
scripts=['scripts/schtex.py'],
license='LGPL'
)
|
Add the learnerCanLoginWithNoPassword at the default facility config. | // a name for every URL pattern
const PageNames = {
CLASS_MGMT_PAGE: 'CLASS_MGMT_PAGE',
CLASS_EDIT_MGMT_PAGE: 'CLASS_EDIT_MGMT_PAGE',
CLASS_ENROLL_MGMT_PAGE: 'CLASS_ENROLL_MGMT_PAGE',
USER_MGMT_PAGE: 'USER_MGMT_PAGE',
DATA_EXPORT_PAGE: 'DATA_EXPORT_PAGE',
FACILITY_CONFIG_PAGE: 'FACILITY_CONFIG_PAGE',
};
// modal names
const Modals = {
CREATE_CLASS: 'CREATE_CLASS',
DELETE_CLASS: 'DELETE_CLASS',
EDIT_CLASS_NAME: 'EDIT_CLASS_NAME',
REMOVE_USER: 'REMOVE_USER',
CONFIRM_ENROLLMENT: 'CONFIRM_ENROLLMENT',
CREATE_USER: 'CREATE_USER',
EDIT_USER: 'EDIT_USER',
RESET_USER_PASSWORD: 'RESET_USER_PASSWORD',
DELETE_USER: 'DELETE_USER',
};
const defaultFacilityConfig = {
learnerCanEditUsername: true,
learnerCanEditName: true,
learnerCanEditPassword: true,
learnerCanSignUp: true,
learnerCanDeleteAccount: true,
learnerCanLoginWithNoPassword: false,
};
const notificationTypes = {
PAGELOAD_FAILURE: 'PAGELOAD_FAILURE',
SAVE_FAILURE: 'SAVE_FAILURE',
SAVE_SUCCESS: 'SAVE_SUCCESS',
};
export { PageNames, Modals, defaultFacilityConfig, notificationTypes };
| // a name for every URL pattern
const PageNames = {
CLASS_MGMT_PAGE: 'CLASS_MGMT_PAGE',
CLASS_EDIT_MGMT_PAGE: 'CLASS_EDIT_MGMT_PAGE',
CLASS_ENROLL_MGMT_PAGE: 'CLASS_ENROLL_MGMT_PAGE',
USER_MGMT_PAGE: 'USER_MGMT_PAGE',
DATA_EXPORT_PAGE: 'DATA_EXPORT_PAGE',
FACILITY_CONFIG_PAGE: 'FACILITY_CONFIG_PAGE',
};
// modal names
const Modals = {
CREATE_CLASS: 'CREATE_CLASS',
DELETE_CLASS: 'DELETE_CLASS',
EDIT_CLASS_NAME: 'EDIT_CLASS_NAME',
REMOVE_USER: 'REMOVE_USER',
CONFIRM_ENROLLMENT: 'CONFIRM_ENROLLMENT',
CREATE_USER: 'CREATE_USER',
EDIT_USER: 'EDIT_USER',
RESET_USER_PASSWORD: 'RESET_USER_PASSWORD',
DELETE_USER: 'DELETE_USER',
};
const defaultFacilityConfig = {
learnerCanEditUsername: true,
learnerCanEditName: true,
learnerCanEditPassword: true,
learnerCanSignUp: true,
learnerCanDeleteAccount: true,
};
const notificationTypes = {
PAGELOAD_FAILURE: 'PAGELOAD_FAILURE',
SAVE_FAILURE: 'SAVE_FAILURE',
SAVE_SUCCESS: 'SAVE_SUCCESS',
};
export { PageNames, Modals, defaultFacilityConfig, notificationTypes };
|
Remove this test case for now... still segfaulting for some crazy reason... | var $ = require('../')
, assert = require('assert')
$.import('Foundation')
$.NSAutoreleasePool('alloc')('init')
// Subclass 'NSObject', creating a new class named 'NRTest'
var NRTest = $.NSObject.extend('NRTest')
, counter = 0
// Add a new method to the NRTest class responding to the "description" selector
NRTest.addMethod('description', '@@:', function (self, _cmd) {
counter++
console.log(_cmd)
return $.NSString('stringWithUTF8String', 'test')
})
// Finalize the class so the we can make instances of it
NRTest.register()
// Create an instance
var instance = NRTest('alloc')('init')
// call [instance description] in a variety of ways (via toString())
console.log(instance('description')+'')
console.log(instance.toString())
//console.log(String(instance)) // now this one segfaults? WTF!?!?!
console.log(''+instance)
console.log(instance+'')
console.log(instance)
assert.equal(counter, 5)
| var $ = require('../')
, assert = require('assert')
$.import('Foundation')
$.NSAutoreleasePool('alloc')('init')
// Subclass 'NSObject', creating a new class named 'NRTest'
var NRTest = $.NSObject.extend('NRTest')
, counter = 0
// Add a new method to the NRTest class responding to the "description" selector
NRTest.addMethod('description', '@@:', function (self, _cmd) {
counter++
console.log(_cmd)
return $.NSString('stringWithUTF8String', 'test')
})
// Finalize the class so the we can make instances of it
NRTest.register()
// Create an instance
var instance = NRTest('alloc')('init')
// call [instance description] in a variety of ways (via toString())
console.log(instance('description')+'')
console.log(instance.toString())
console.log(String(instance))
console.log(''+instance)
console.log(instance+'')
console.log(instance)
assert.equal(counter, 6)
|
Fix the `release` step of deploy
lol | from fabric.api import cd, run, sudo, env, roles, execute
from datetime import datetime
env.roledefs = {
'webuser': ['[email protected]'],
'sudoer': ['[email protected]'],
}
env.hosts = ['andrewlorente.com']
def deploy():
release_id = datetime.now().strftime("%Y%m%d%H%M%S")
execute(build, release_id)
execute(release)
@roles('webuser')
def build(release_id):
releases_dir = "/u/apps/bloge/releases/"
run("git clone -q https://github.com/AndrewLorente/bloge.git " +
releases_dir + release_id)
with cd(releases_dir + release_id):
run("cabal update")
run("cabal install --constraint 'template-haskell installed' --dependencies-only --force-reinstall -v")
run("cabal configure")
run("cabal build")
run("ln -nfs /u/apps/bloge/releases/{0} "
"/u/apps/bloge/current".format(release_id))
@roles('sudoer')
def release():
sudo("initctl restart bloge")
| from fabric.api import cd, run, sudo, env, roles, execute
from datetime import datetime
env.roledefs = {
'webuser': ['[email protected]'],
'sudoer': ['[email protected]'],
}
env.hosts = ['andrewlorente.com']
def deploy():
release_id = datetime.now().strftime("%Y%m%d%H%M%S")
execute(build, release_id)
release(release)
@roles('webuser')
def build(release_id):
releases_dir = "/u/apps/bloge/releases/"
run("git clone -q https://github.com/AndrewLorente/bloge.git " +
releases_dir + release_id)
with cd(releases_dir + release_id):
run("cabal update")
run("cabal install --constraint 'template-haskell installed' --dependencies-only --force-reinstall -v")
run("cabal configure")
run("cabal build")
run("ln -nfs /u/apps/bloge/releases/{0} "
"/u/apps/bloge/current".format(release_id))
@roles('sudoer')
def release(*args):
sudo("initctl restart bloge")
|
Fix bug when creating a cache request responses to convert had failed. | package com.yo1000.vis.component.scheduler;
import com.yo1000.vis.model.data.RequestHistory;
import com.yo1000.vis.model.service.RequestHistoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
/**
* Created by yoichi.kikuchi on 2015/06/26.
*/
@Component
public class TaskScheduler {
private static final Logger LOGGER = LoggerFactory.getLogger(TaskScheduler.class);
@Autowired
private RequestHistoryService requestHistoryService;
@Autowired
private RestTemplate restTemplate;
@Scheduled(cron = "0 */20 8-23 * * 1-5")
public void renewCache() {
for (RequestHistory history : this.getRequestHistoryService().getHistories()) {
try {
this.getRestTemplate().getForObject(history.getUrl(), String.class);
}
catch (Exception e) {
LOGGER.warn(e.getMessage(), e);
}
}
}
protected RequestHistoryService getRequestHistoryService() {
return requestHistoryService;
}
protected RestTemplate getRestTemplate() {
return restTemplate;
}
}
| package com.yo1000.vis.component.scheduler;
import com.yo1000.vis.model.data.RequestHistory;
import com.yo1000.vis.model.service.RequestHistoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
/**
* Created by yoichi.kikuchi on 2015/06/26.
*/
@Component
public class TaskScheduler {
private static final Logger LOGGER = LoggerFactory.getLogger(TaskScheduler.class);
@Autowired
private RequestHistoryService requestHistoryService;
@Autowired
private RestTemplate restTemplate;
@Scheduled(cron = "0 */20 8-23 * * 1-5")
public void renewCache() {
for (RequestHistory history : this.getRequestHistoryService().getHistories()) {
try {
this.getRestTemplate().getForObject(history.getUrl(), Void.class);
}
catch (Exception e) {
LOGGER.warn(e.getMessage(), e);
}
}
}
protected RequestHistoryService getRequestHistoryService() {
return requestHistoryService;
}
protected RestTemplate getRestTemplate() {
return restTemplate;
}
}
|
Fix pip install failing due to wtforms monkeypatch | # This file is part of Indico.
# Copyright (C) 2002 - 2018 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# Indico is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Indico; if not, see <http://www.gnu.org/licenses/>.
from indico.util.mimetypes import register_custom_mimetypes
__version__ = '2.1-dev'
register_custom_mimetypes()
# monkeypatch for https://github.com/wtforms/wtforms/issues/373
def _patch_wtforms_sqlalchemy():
from wtforms.ext.sqlalchemy import fields
from sqlalchemy.orm.util import identity_key
def get_pk_from_identity(obj):
key = identity_key(instance=obj)[1]
return u':'.join(map(unicode, key))
fields.get_pk_from_identity = get_pk_from_identity
try:
_patch_wtforms_sqlalchemy()
except ImportError as exc:
# pip seems to run this sometimes while uninstalling an old sqlalchemy version
print 'Could not monkeypatch wtforms', exc
finally:
del _patch_wtforms_sqlalchemy
| # This file is part of Indico.
# Copyright (C) 2002 - 2018 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# Indico is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Indico; if not, see <http://www.gnu.org/licenses/>.
from indico.util.mimetypes import register_custom_mimetypes
__version__ = '2.1-dev'
register_custom_mimetypes()
# monkeypatch for https://github.com/wtforms/wtforms/issues/373
def _patch_wtforms_sqlalchemy():
from wtforms.ext.sqlalchemy import fields
from sqlalchemy.orm.util import identity_key
def get_pk_from_identity(obj):
key = identity_key(instance=obj)[1]
return u':'.join(map(unicode, key))
fields.get_pk_from_identity = get_pk_from_identity
_patch_wtforms_sqlalchemy()
del _patch_wtforms_sqlalchemy
|
Fix file headers for missing BSD license.
git-svn-id: fe6d842192ccfb78748eb71580d1ce65f168b559@1713 9830eeb5-ddf4-0310-9ef7-f4b9a3e3227e | /*
* Copyright (C) 2009 XStream Committers.
* All rights reserved.
*
* The software in this package is published under the terms of the BSD
* style license a copy of which has been included with this distribution in
* the LICENSE.txt file.
*
* Created on 15. August 2009 by Joerg Schaible
*/
package com.thoughtworks.xstream.io.xml;
/**
* A XmlFriendlyNameCoder to support backward compatibility with XStream 1.1.
*
* @author Jörg Schaible
* @since upcoming
*/
public class XStream11NameCoder extends XmlFriendlyNameCoder {
/**
* {@inheritDoc} Noop implementation that does not decode. Used for XStream 1.1
* compatibility.
*/
public String decodeAttribute(String attributeName) {
return attributeName;
}
/**
* {@inheritDoc} Noop implementation that does not decode. Used for XStream 1.1
* compatibility.
*/
public String decodeNode(String elementName) {
return elementName;
}
}
| /*
* Copyright (C) 2009 XStream Committers.
* All rights reserved.
*
* Created on 15. August 2009 by Joerg Schaible
*/
package com.thoughtworks.xstream.io.xml;
/**
* A XmlFriendlyNameCoder to support backward compatibility with XStream 1.1.
*
* @author Jörg Schaible
* @since upcoming
*/
public class XStream11NameCoder extends XmlFriendlyNameCoder {
/**
* {@inheritDoc} Noop implementation that does not decode. Used for XStream 1.1
* compatibility.
*/
public String decodeAttribute(String attributeName) {
return attributeName;
}
/**
* {@inheritDoc} Noop implementation that does not decode. Used for XStream 1.1
* compatibility.
*/
public String decodeNode(String elementName) {
return elementName;
}
}
|
Use find_packages for package discovery | import os
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), 'README.markdown')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-paiji2-weather',
version='0.1',
packages=find_packages(),
include_package_data=True,
description='A simple weather app',
long_description=README,
url='https://github.com/rezometz/django-paiji2-weather',
author='Supelec Rezo Metz',
author_email='[email protected]',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
| import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.markdown')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-paiji2-weather',
version='0.1',
packages=['paiji2_weather'],
include_package_data=True,
description='A simple weather app',
long_description=README,
url='https://github.com/rezometz/django-paiji2-weather',
author='Supelec Rezo Metz',
author_email='[email protected]',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
|
Comment out GUI - maintain compilable submission | package reversi.GUI;
/*
* Possibly use "GridLayout" class.
* Not sure of the limits, still checking.
*/
import java.awt.*;
import javax.swing.*;
/*
public class guiBoard extends JFrame {
//DisplayGui();
}*/
/*
* Variable will allow switching between menu display and game board display
*/
/*private void variableGameState( int state) {
switch (gameState)
case 0:
//TODO: Display everything
case 1:
//TODO: Display menu
case 2:
//TODO: Display board
//TODO: Display game
//TODO: Display pieces (sprites)
}*/
/*
* Paint method based on variable state
*/
//public void DisplayGUI(Graphics2D gfx) {
//int gameState;
//if(gameState = 0)
/*
* Draw/redraw: variableGameState(0);
*/
//else if(gameState = 1)
/*
* Draw/redraw: varaibleGameState(1);
*/
//else if(gameState = 2)
/*
* Draw/redraw: variableGameState(2);
*/
//GridLayout reversiLayout = newGridLayout(8, 8);
//addComponentsToPane(getContentPane());
//setSize(800, 800);
//setVisible(true);
//}
//private void addComponentsToPane( Container contentPane) {
//} | package reversi.GUI;
/*
* Possibly use "GridLayout" class.
* Not sure of the limits, still checking.
*/
import java.awt.*;
import javax.swing.*;
public class guiBoard extends JFrame {
DisplayGui();
}
/*
* Variable will allow switching between menu display and game board display
*/
private void variableGameState( int state) {
switch (gameState)
case 0:
//TODO: Display everything
case 1:
//TODO: Display menu
case 2:
//TODO: Display board
//TODO: Display game
//TODO: Display pieces (sprites)
}
/*
* Paint method based on variable state
*/
public void DisplayGUI(Graphics2D gfx) {
int gameState;
if(gameState = 0)
/*
* Draw/redraw: variableGameState(0);
*/
else if(gameState = 1)
/*
* Draw/redraw: varaibleGameState(1);
*/
else if(gameState = 2)
/*
* Draw/redraw: variableGameState(2);
*/
//GridLayout reversiLayout = newGridLayout(8, 8);
//addComponentsToPane(getContentPane());
//setSize(800, 800);
setVisible(true);
}
private void addComponentsToPane( Container contentPane) {
} |
Add valid module name test case | import unittest
import kyoto.server
import kyoto.tests.dummy
import kyoto.client
class ServiceTestCase(unittest.TestCase):
def setUp(self):
self.address = ('localhost', 1337)
self.server = kyoto.server.BertRPCServer([kyoto.tests.dummy])
self.server.start()
self.service = kyoto.client.Service(self.address, ":dummy")
def test_invalid_module_name_type(self):
with self.assertRaises(ValueError):
service = kyoto.client.Service(self.address, "dummy")
service = kyoto.client.Service(self.address, ":dummy")
def test_sync_request(self):
response = self.service.call(":echo", ["hello"])
self.assertEqual(response, "hello?")
def test_async_request(self):
response = self.service.cast(":echo", ["hello"])
self.assertEqual(response, None)
def tearDown(self):
self.server.stop()
| import unittest
import kyoto.server
import kyoto.tests.dummy
import kyoto.client
class ServiceTestCase(unittest.TestCase):
def setUp(self):
self.address = ('localhost', 1337)
self.server = kyoto.server.BertRPCServer([kyoto.tests.dummy])
self.server.start()
self.service = kyoto.client.Service(self.address, ":dummy")
def test_invalid_service_name_type(self):
with self.assertRaises(ValueError):
service = kyoto.client.Service(self.address, "dummy")
def test_sync_request(self):
response = self.service.call(":echo", ["hello"])
self.assertEqual(response, "hello?")
def test_async_request(self):
response = self.service.cast(":echo", ["hello"])
self.assertEqual(response, None)
def tearDown(self):
self.server.stop()
|
Add blank lines according to hound | from panoptes_client.panoptes import (
Panoptes,
PanoptesAPIException,
PanoptesObject,
LinkResolver,
)
from panoptes_client.project import Project
class Avatar(PanoptesObject):
_api_slug = 'avatar'
_link_slug = 'avatars'
_edit_attributes = ()
@classmethod
def http_get(cls, path, params={}, headers={}):
project = params.pop('project')
# print()
# print(Project.url(project.id))
# print()
avatar_response = Panoptes.client().get(
Project.url(project.id) + cls.url(path),
params,
headers,
)
print(avatar_response.raw)
return avatar_response
LinkResolver.register(Avatar)
LinkResolver.register(Avatar, 'avatar')
| from panoptes_client.panoptes import (
Panoptes,
PanoptesAPIException,
PanoptesObject,
LinkResolver,
)
from panoptes_client.project import Project
class Avatar(PanoptesObject):
_api_slug = 'avatar'
_link_slug = 'avatars'
_edit_attributes = ()
@classmethod
def http_get(cls, path, params={}, headers={}):
project = params.pop('project')
# print()
# print(Project.url(project.id))
# print()
avatar_response = Panoptes.client().get(
Project.url(project.id) + cls.url(path),
params,
headers,
)
print(avatar_response.raw)
return avatar_response
LinkResolver.register(Avatar)
LinkResolver.register(Avatar, 'avatar')
|
Rename `initialize_episode` --> `__call__` in `composer.Initializer`
PiperOrigin-RevId: 234775654 | # Copyright 2018 The dm_control Authors.
#
# 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.
# ============================================================================
"""Module defining the abstract initializer."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import abc
import six
@six.add_metaclass(abc.ABCMeta)
class Initializer(object):
"""The abstract base class for an initializer."""
@abc.abstractmethod
def __call__(self, physics, random_state):
raise NotImplementedError
| # Copyright 2018 The dm_control Authors.
#
# 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.
# ============================================================================
"""Module defining the abstract initializer."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import abc
import six
@six.add_metaclass(abc.ABCMeta)
class Initializer(object):
"""The abstract base class for an initializer."""
@abc.abstractmethod
def initialize_episode(self, physics, random_state):
raise NotImplementedError
|
Set data cache home directory to ~/.cache/paddle/dataset | import hashlib
import os
import shutil
import urllib2
__all__ = ['DATA_HOME', 'download']
DATA_HOME = os.path.expanduser('~/.cache/paddle/dataset')
if not os.path.exists(DATA_HOME):
os.makedirs(DATA_HOME)
def download(url, md5):
filename = os.path.split(url)[-1]
assert DATA_HOME is not None
filepath = os.path.join(DATA_HOME, md5)
if not os.path.exists(filepath):
os.makedirs(filepath)
__full_file__ = os.path.join(filepath, filename)
def __file_ok__():
if not os.path.exists(__full_file__):
return False
md5_hash = hashlib.md5()
with open(__full_file__, 'rb') as f:
for chunk in iter(lambda: f.read(4096), b""):
md5_hash.update(chunk)
return md5_hash.hexdigest() == md5
while not __file_ok__():
response = urllib2.urlopen(url)
with open(__full_file__, mode='wb') as of:
shutil.copyfileobj(fsrc=response, fdst=of)
return __full_file__
| import hashlib
import os
import shutil
import urllib2
__all__ = ['DATA_HOME', 'download']
DATA_HOME = os.path.expanduser('~/.cache/paddle_data_set')
if not os.path.exists(DATA_HOME):
os.makedirs(DATA_HOME)
def download(url, md5):
filename = os.path.split(url)[-1]
assert DATA_HOME is not None
filepath = os.path.join(DATA_HOME, md5)
if not os.path.exists(filepath):
os.makedirs(filepath)
__full_file__ = os.path.join(filepath, filename)
def __file_ok__():
if not os.path.exists(__full_file__):
return False
md5_hash = hashlib.md5()
with open(__full_file__, 'rb') as f:
for chunk in iter(lambda: f.read(4096), b""):
md5_hash.update(chunk)
return md5_hash.hexdigest() == md5
while not __file_ok__():
response = urllib2.urlopen(url)
with open(__full_file__, mode='wb') as of:
shutil.copyfileobj(fsrc=response, fdst=of)
return __full_file__
|
Write the extraction script properly. | #!/usr/bin/env python
'''Extract the momentum distribution from an analysed DMQMC simulation.'''
import pandas as pd
import numpy as np
import sys
def main(args):
if (len(sys.argv) < 2):
print ("Usage: extract_n_k.py file bval")
sys.exit()
bval = float(sys.argv[2])
data = pd.read_csv(sys.argv[1], sep=r'\s+').groupby('Beta').get_group(bval)
mom = [c for c in data.columns.values if 'n_' in c and '_error' not in c]
mome = [c for c in data.columns.values if 'n_' in c and '_error' in c]
vals = [float(c.split('_')[1]) for c in mom]
n_k = (data[mom].transpose()).values
n_k_error = (data[mome].transpose()).values
n_k_error[np.isnan(n_k_error)] = 0
frame = pd.DataFrame({'Beta': bval, 'k': vals, 'n_k': n_k.ravel(), 'n_k_error':
n_k_error.ravel()})
print (frame.to_string(index=False))
if __name__ == '__main__':
main(sys.argv[1:])
| #!/usr/bin/env python
'''Extract the momentum distribution from a analysed DMQMC simulation.'''
import pandas as pd
import numpy as np
import sys
# [review] - JSS: use if __name__ == '__main__' and functions so code can easily be reused in another script if necessary.
if (len(sys.argv) < 2):
print ("Usage: extract_n_k.py file bval")
sys.exit()
bval = float(sys.argv[2])
data = pd.read_csv(sys.argv[1], sep=r'\s+').groupby('Beta').get_group(bval)
mom = [c for c in data.columns.values if 'n_' in c and '_error' not in c]
mome = [c for c in data.columns.values if 'n_' in c and '_error' in c]
vals = [float(c.split('_')[1]) for c in mom]
n_k = (data[mom].transpose()).values
n_k_error = (data[mome].transpose()).values
n_k_error[np.isnan(n_k_error)] = 0
frame = pd.DataFrame({'Beta': bval, 'k': vals, 'n_k': n_k.ravel(), 'n_k_error':
n_k_error.ravel()})
print (frame.to_string(index=False))
|
Revert "Add verbose flag to compiler options (testing)."
This reverts commit 2406e30851b65cd78981eecd76d966fb17259fa4. | ##
# Template file for site configuration - copy it to site_cfg.py:
# $ cp site_cfg_template.py site_cfg.py
# Force python version (e.g. '2.4'), or left 'auto' for autodetection.
python_version = 'auto'
# Operating system - one of 'posix', 'windows' or None for automatic
# determination.
system = None
# Extra flags added to the flags supplied by distutils to compile C
# extension modules.
compile_flags = '-g -O2'
# Extra flags added to the flags supplied by distutils to link C
# extension modules.
link_flags = ''
# Can be '' or one or several from '-DDEBUG_FMF', '-DDEBUG_MESH'. For
# developers internal use only.
debug_flags = ''
# Sphinx documentation uses numpydoc extension. Set the path here in case it is
# not installed in a standard location.
numpydoc_path = None
# True for a release, False otherwise. If False, current git commit hash
# is appended to version string, if the sources are in a repository.
is_release = False
# Tetgen executable path.
tetgen_path = '/usr/bin/tetgen'
| ##
# Template file for site configuration - copy it to site_cfg.py:
# $ cp site_cfg_template.py site_cfg.py
# Force python version (e.g. '2.4'), or left 'auto' for autodetection.
python_version = 'auto'
# Operating system - one of 'posix', 'windows' or None for automatic
# determination.
system = None
# Extra flags added to the flags supplied by distutils to compile C
# extension modules.
compile_flags = '-g -O2 -v'
# Extra flags added to the flags supplied by distutils to link C
# extension modules.
link_flags = ''
# Can be '' or one or several from '-DDEBUG_FMF', '-DDEBUG_MESH'. For
# developers internal use only.
debug_flags = ''
# Sphinx documentation uses numpydoc extension. Set the path here in case it is
# not installed in a standard location.
numpydoc_path = None
# True for a release, False otherwise. If False, current git commit hash
# is appended to version string, if the sources are in a repository.
is_release = False
# Tetgen executable path.
tetgen_path = '/usr/bin/tetgen'
|
Check the length of the screencap before indexing into it | import logging
import re
import time
class TransportAsync:
async def transport(self, connection):
cmd = "host:transport:{}".format(self.serial)
await connection.send(cmd)
return connection
async def shell(self, cmd, timeout=None):
conn = await self.create_connection(timeout=timeout)
cmd = "shell:{}".format(cmd)
await conn.send(cmd)
result = await conn.read_all()
await conn.close()
return result.decode('utf-8')
async def sync(self):
conn = await self.create_connection()
cmd = "sync:"
await conn.send(cmd)
return conn
async def screencap(self):
async with await self.create_connection() as conn:
cmd = "shell:/system/bin/screencap -p"
await conn.send(cmd)
result = await conn.read_all()
if result and len(result) > 5 and result[5] == 0x0d:
return result.replace(b'\r\n', b'\n')
else:
return result
| import logging
import re
import time
class TransportAsync:
async def transport(self, connection):
cmd = "host:transport:{}".format(self.serial)
await connection.send(cmd)
return connection
async def shell(self, cmd, timeout=None):
conn = await self.create_connection(timeout=timeout)
cmd = "shell:{}".format(cmd)
await conn.send(cmd)
result = await conn.read_all()
await conn.close()
return result.decode('utf-8')
async def sync(self):
conn = await self.create_connection()
cmd = "sync:"
await conn.send(cmd)
return conn
async def screencap(self):
async with await self.create_connection() as conn:
cmd = "shell:/system/bin/screencap -p"
await conn.send(cmd)
result = await conn.read_all()
if result[5] == 0x0d:
return result.replace(b'\r\n', b'\n')
else:
return result
|
Exclude test folder from package
DHC-1102
Ignore the test directory when looking for python packages to
avoid having the files installed
Change-Id: Ia30e821109c0f75f0f0c51bb995b2099aa30e063
Signed-off-by: Rosario Di Somma <[email protected]> | from setuptools import setup, find_packages
setup(
name='akanda-rug',
version='0.1.5',
description='Akanda Router Update Generator manages tenant routers',
author='DreamHost',
author_email='[email protected]',
url='http://github.com/dreamhost/akanda-rug',
license='BSD',
install_requires=[
'netaddr>=0.7.5',
'httplib2>=0.7.2',
'python-quantumclient>=2.1',
'oslo.config'
],
namespace_packages=['akanda'],
packages=find_packages(exclude=['test']),
include_package_data=True,
zip_safe=False,
entry_points={
'console_scripts': [
'akanda-rug-service=akanda.rug.service:main'
]
},
)
| from setuptools import setup, find_packages
setup(
name='akanda-rug',
version='0.1.5',
description='Akanda Router Update Generator manages tenant routers',
author='DreamHost',
author_email='[email protected]',
url='http://github.com/dreamhost/akanda-rug',
license='BSD',
install_requires=[
'netaddr>=0.7.5',
'httplib2>=0.7.2',
'python-quantumclient>=2.1',
'oslo.config'
],
namespace_packages=['akanda'],
packages=find_packages(),
include_package_data=True,
zip_safe=False,
entry_points={
'console_scripts': [
'akanda-rug-service=akanda.rug.service:main'
]
},
)
|
Support UTF-8 for encoding/decoding widget links. | angular.module("Prometheus.services").factory('UrlConfigDecoder', function($location) {
return function(defaultHash) {
var hash = $location.hash() || defaultHash;
if (!hash) {
return {};
}
// Decodes UTF-8
// https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64.btoa#Unicode_Strings
var configJSON = unescape(decodeURIComponent(window.atob(hash)));
var config = JSON.parse(configJSON);
return config;
};
});
angular.module("Prometheus.services").factory('UrlHashEncoder', ["UrlConfigDecoder", function(UrlConfigDecoder) {
return function(config) {
var urlConfig = UrlConfigDecoder();
for (var o in config) {
urlConfig[o] = config[o];
}
var configJSON = JSON.stringify(urlConfig);
// Encodes UTF-8
// https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64.btoa#Unicode_Strings
return window.btoa(encodeURIComponent(escape(configJSON)));
};
}]);
angular.module("Prometheus.services").factory('UrlConfigEncoder', ["$location", "UrlHashEncoder", function($location, UrlHashEncoder) {
return function(config) {
$location.hash(UrlHashEncoder(config));
};
}]);
angular.module("Prometheus.services").factory('UrlVariablesDecoder', function($location) {
return function() {
return $location.search();
};
});
| angular.module("Prometheus.services").factory('UrlConfigDecoder', function($location) {
return function(defaultHash) {
var hash = $location.hash() || defaultHash;
if (!hash) {
return {};
}
var configJSON = atob(hash);
var config = JSON.parse(configJSON);
return config;
};
});
angular.module("Prometheus.services").factory('UrlHashEncoder', ["UrlConfigDecoder", function(UrlConfigDecoder) {
return function(config) {
var urlConfig = UrlConfigDecoder();
for (var o in config) {
urlConfig[o] = config[o];
}
var configJSON = JSON.stringify(urlConfig);
return btoa(configJSON);
};
}]);
angular.module("Prometheus.services").factory('UrlConfigEncoder', ["$location", "UrlHashEncoder", function($location, UrlHashEncoder) {
return function(config) {
$location.hash(UrlHashEncoder(config));
};
}]);
angular.module("Prometheus.services").factory('UrlVariablesDecoder', function($location) {
return function() {
return $location.search();
};
});
|
[MOD] Server: Reduce delays for invalid passwords | package org.basex.server;
import org.basex.util.*;
import org.basex.util.hash.*;
/**
* This class delays blocked clients.
*
* @author BaseX Team 2005-18, BSD License
* @author Christian Gruen
*/
public final class ClientBlocker {
/** Temporarily blocked clients. */
private final TokenIntMap blocked = new TokenIntMap();
/**
* Registers the client and delays the process.
* @param client client address
*/
public synchronized void delay(final byte[] client) {
int delay = blocked.get(client);
delay = delay == -1 ? 1 : Math.min(delay, 1024) << 1;
blocked.put(client, delay);
while(--delay > 0) Performance.sleep(100);
}
/**
* Resets the login delay after successful login.
* @param client client address
*/
public synchronized void remove(final byte[] client) {
blocked.remove(client);
}
}
| package org.basex.server;
import org.basex.util.*;
import org.basex.util.hash.*;
/**
* This class delays blocked clients.
*
* @author BaseX Team 2005-18, BSD License
* @author Christian Gruen
*/
public final class ClientBlocker {
/** Temporarily blocked clients. */
private final TokenIntMap blocked = new TokenIntMap();
/**
* Registers the client and delays the process.
* @param client client address
*/
public synchronized void delay(final byte[] client) {
int delay = blocked.get(client);
delay = delay == -1 ? 1 : Math.min(delay, 1024) << 1;
blocked.put(client, delay);
while(--delay > 0) Performance.sleep(1000);
}
/**
* Resets the login delay after successful login.
* @param client client address
*/
public synchronized void remove(final byte[] client) {
blocked.remove(client);
}
}
|
Change 'init' to true on each save. | import { Meteor } from 'meteor/meteor';
import { check } from 'meteor/check';
import { settingsLive } from './collections';
import defaultSettings from './defaultSettings';
import { checkSiteIdOwnership, checkUserLoggedIn } from '../utils';
Meteor.methods({
saveSettings(settings) {
const userId = this.userId;
const name = settings.woronaInfo.name;
const siteId = settings.woronaInfo.siteId;
check(name, String);
check(siteId, String);
checkUserLoggedIn(userId);
checkSiteIdOwnership(siteId, userId);
const newSettingData = {};
Object.assign(newSettingData, settings);
delete newSettingData.woronaInfo;
newSettingData['woronaInfo.init'] = true;
const id = settingsLive.findOne({ 'woronaInfo.name': name, 'woronaInfo.siteId': siteId })._id;
return settingsLive.update(id, { $set: newSettingData });
},
initSettings(siteId) {
check(siteId, String);
defaultSettings.forEach(setting => {
const woronaInfo = Object.assign({}, setting.woronaInfo, { siteId });
settingsLive.insert(Object.assign({}, setting, { woronaInfo }));
});
},
});
| import { Meteor } from 'meteor/meteor';
import { check } from 'meteor/check';
import { settingsLive } from './collections';
import defaultSettings from './defaultSettings';
import { checkSiteIdOwnership, checkUserLoggedIn } from '../utils';
Meteor.methods({
saveSettings(settings) {
const userId = this.userId;
const name = settings.woronaInfo.name;
const siteId = settings.woronaInfo.siteId;
check(name, String);
check(siteId, String);
checkUserLoggedIn(userId);
checkSiteIdOwnership(siteId, userId);
const newSettingData = {};
Object.assign(newSettingData, settings);
delete newSettingData.woronaInfo;
const id = settingsLive.findOne({ 'woronaInfo.name': name, 'woronaInfo.siteId': siteId })._id;
return settingsLive.update(id, { $set: newSettingData });
},
initSettings(siteId) {
check(siteId, String);
defaultSettings.forEach(setting => {
const woronaInfo = Object.assign({}, setting.woronaInfo, { siteId });
settingsLive.insert(Object.assign({}, setting, { woronaInfo }));
});
},
});
|
Fix for running exported function instead of result of last statement. | "use strict"
var JavaScriptPlaygroundEditor = require("./JavaScriptPlaygroundEditor.js")
, vm = require("vm")
var JavaScriptPlayground = module.exports = function (playgroundElement, jsStubText) {
this._playgroundElem = playgroundElement
var jsEditorElement = document.createElement("div")
jsEditorElement.style.width = "100%"
jsEditorElement.style.height = "100%"
this._playgroundElem.appendChild(jsEditorElement)
this._jsEditor = new JavaScriptPlaygroundEditor(jsEditorElement, jsStubText)
this._jsEditor.on("changeValidJS", this._handleJSChange.bind(this))
}
JavaScriptPlayground.prototype._handleJSChange = function (event) {
var context = {
"require": require,
"module": { "exports": {} }
}
vm.runInNewContext(event.documentText(), context)
context.module.exports.call(undefined, "bar")
try {
}
catch (e) {
console.log(e)
}
}
| "use strict"
var JavaScriptPlaygroundEditor = require("./JavaScriptPlaygroundEditor.js")
, vm = require("vm")
var JavaScriptPlayground = module.exports = function (playgroundElement, jsStubText) {
this._playgroundElem = playgroundElement
var jsEditorElement = document.createElement("div")
jsEditorElement.style.width = "100%"
jsEditorElement.style.height = "100%"
this._playgroundElem.appendChild(jsEditorElement)
this._jsEditor = new JavaScriptPlaygroundEditor(jsEditorElement, jsStubText)
this._jsEditor.on("changeValidJS", this._handleJSChange.bind(this))
}
JavaScriptPlayground.prototype._handleJSChange = function (event) {
try {
var result = vm.runInNewContext(event.documentText(), {
"require": require,
"module": { "exports": {} }
})
result("bar")
}
catch (e) {
console.log(e)
}
}
|
Use new dmagellan worker tarball (854e51d) | # run this with python -i
import dask, distributed
from distributed import Client
from distributed.deploy.adaptive import Adaptive
from dask_condor import HTCondorCluster
import logging, os
logging.basicConfig(level=0)
logging.getLogger("distributed.comm.tcp").setLevel(logging.ERROR)
logging.getLogger("distributed.deploy.adaptive").setLevel(logging.WARNING)
worker_tarball="dask_condor_worker_dmagellan.854e51d.SL6.tar.gz"
if os.path.exists(os.path.join('/squid/matyas', worker_tarball)):
worker_tarball = "http://proxy.chtc.wisc.edu/SQUID/matyas/" + worker_tarball
elif not os.path.exists(worker_tarball):
worker_tarball = "http://research.cs.wisc.edu/~matyas/dask_condor/" + worker_tarball
htc = HTCondorCluster(memory_per_worker=4096, update_interval=10000, worker_tarball=worker_tarball, logdir=".log")
cli = Client(htc)
sch = htc.scheduler
print("htc={0}\ncli={1}\nsch={2}".format(htc,cli,sch))
| # run this with python -i
import dask, distributed
from distributed import Client
from distributed.deploy.adaptive import Adaptive
from dask_condor import HTCondorCluster
import logging, os
logging.basicConfig(level=0)
logging.getLogger("distributed.comm.tcp").setLevel(logging.ERROR)
logging.getLogger("distributed.deploy.adaptive").setLevel(logging.WARNING)
worker_tarball="dask_condor_worker_dmagellan.SL6.tar.gz"
if os.path.exists(os.path.join('/squid/matyas', worker_tarball)):
worker_tarball = "http://proxy.chtc.wisc.edu/SQUID/matyas/" + worker_tarball
elif not os.path.exists(worker_tarball):
worker_tarball = "http://research.cs.wisc.edu/~matyas/dask_condor/" + worker_tarball
htc = HTCondorCluster(memory_per_worker=4096, update_interval=10000, worker_tarball=worker_tarball, logdir=".log")
cli = Client(htc)
sch = htc.scheduler
print("htc={0}\ncli={1}\nsch={2}".format(htc,cli,sch))
|
Apply latest changes in FWBundle recipe
See https://github.com/symfony/recipes/pull/611 | <?php
use Symfony\Component\Dotenv\Dotenv;
require dirname(__DIR__).'/vendor/autoload.php';
// Load cached env vars if the .env.local.php file exists
// Run "composer dump-env prod" to create it (requires symfony/flex >=1.2)
if (is_array($env = @include dirname(__DIR__).'/.env.local.php')) {
foreach ($env as $k => $v) {
$_ENV[$k] = $_ENV[$k] ?? (isset($_SERVER[$k]) && 0 !== strpos($k, 'HTTP_') ? $_SERVER[$k] : $v);
}
} elseif (!class_exists(Dotenv::class)) {
throw new RuntimeException('Please run "composer require symfony/dotenv" to load the ".env" files configuring the application.');
} else {
// load all the .env files
(new Dotenv(false))->loadEnv(dirname(__DIR__).'/.env');
}
$_SERVER += $_ENV;
$_SERVER['APP_ENV'] = $_ENV['APP_ENV'] = ($_SERVER['APP_ENV'] ?? $_ENV['APP_ENV'] ?? null) ?: 'dev';
$_SERVER['APP_DEBUG'] = $_SERVER['APP_DEBUG'] ?? $_ENV['APP_DEBUG'] ?? 'prod' !== $_SERVER['APP_ENV'];
$_SERVER['APP_DEBUG'] = $_ENV['APP_DEBUG'] = (int) $_SERVER['APP_DEBUG'] || filter_var($_SERVER['APP_DEBUG'], FILTER_VALIDATE_BOOLEAN) ? '1' : '0';
| <?php
use Symfony\Component\Dotenv\Dotenv;
require dirname(__DIR__).'/vendor/autoload.php';
// Load cached env vars if the .env.local.php file exists
// Run "composer dump-env prod" to create it (requires symfony/flex >=1.2)
if (is_array($env = @include dirname(__DIR__).'/.env.local.php')) {
$_ENV += $env;
} elseif (!class_exists(Dotenv::class)) {
throw new RuntimeException('Please run "composer require symfony/dotenv" to load the ".env" files configuring the application.');
} else {
// load all the .env files
(new Dotenv(false))->loadEnv(dirname(__DIR__).'/.env');
}
$_SERVER += $_ENV;
$_SERVER['APP_ENV'] = $_ENV['APP_ENV'] = ($_SERVER['APP_ENV'] ?? $_ENV['APP_ENV'] ?? null) ?: 'dev';
$_SERVER['APP_DEBUG'] = $_SERVER['APP_DEBUG'] ?? $_ENV['APP_DEBUG'] ?? 'prod' !== $_SERVER['APP_ENV'];
$_SERVER['APP_DEBUG'] = $_ENV['APP_DEBUG'] = (int) $_SERVER['APP_DEBUG'] || filter_var($_SERVER['APP_DEBUG'], FILTER_VALIDATE_BOOLEAN) ? '1' : '0';
|
Switch to nose test runners - probably shouldn't use fabric in this project. | #!/usr/bin/env python
import os
from fabric.api import *
from fab_shared import (test, nose_test_runner, webpy_deploy as deploy,
setup, development, production, localhost, staging, restart_webserver,
rollback, lint, enable, disable, maintenancemode, rechef)
env.unit = "trinity"
env.path = "/var/tornado/%(unit)s" % env
env.scm = "[email protected]:bueda/%(unit)s.git" % env
env.scm_http_url = "http://github.com/bueda/%(unit)s" % env
env.root_dir = os.path.abspath(os.path.dirname(__file__))
env.pip_requirements = ["requirements/common.txt",]
env.pip_requirements_dev = ["requirements/dev.txt",]
env.pip_requirements_production = ["requirements/production.txt",]
env.test_runner = nose_test_runner
env.campfire_subdomain = 'bueda'
env.campfire_room = 'Development'
env.campfire_token = '63768eee94d96b7b18e2091f3919b2a2a3dcd12a'
| #!/usr/bin/env python
import os
from fabric.api import *
from fab_shared import (test, tornado_test_runner, tornado_deploy as deploy,
setup, development, production, localhost, staging, restart_webserver,
rollback, lint, enable,
disable, maintenancemode, rechef)
env.unit = "trinity"
env.path = "/var/tornado/%(unit)s" % env
env.scm = "[email protected]:bueda/%(unit)s.git" % env
env.scm_http_url = "http://github.com/bueda/%(unit)s" % env
env.root_dir = os.path.abspath(os.path.dirname(__file__))
env.pip_requirements = ["requirements/common.txt",]
env.pip_requirements_dev = ["requirements/dev.txt",]
env.pip_requirements_production = ["requirements/production.txt",]
env.test_runner = tornado_test_runner
env.campfire_subdomain = 'bueda'
env.campfire_room = 'Development'
env.campfire_token = '63768eee94d96b7b18e2091f3919b2a2a3dcd12a'
|
Remove unnecessary iframeResize option from multi-page-test-project |
var gulp = require('gulp');
var path = require('path');
var defs = [
{
title: 'Test Index Title',
path: '',
description: 'Test index description',
twitterImage: '20euro.png',
openGraphImage: '50euro.png',
schemaImage: '100euro.png'
},
{
path: '/subpage',
title: 'Test Subpage Title',
description: 'Test subpage description',
twitterImage: '100euro.png',
openGraphImage: '50euro.png',
schemaImage: '20euro.png'
}
];
var opts = {
publishFromFolder: 'dist',
assetContext: 'test-path/',
pageDefs: defs,
embedCodes: false,
entryPoint: path.resolve('src/js/entry-point.jsx'),
}
var builder = require('../../index.js'); // lucify-component-builder
builder(gulp, opts);
|
var gulp = require('gulp');
var path = require('path');
var defs = [
{
title: 'Test Index Title',
path: '',
description: 'Test index description',
twitterImage: '20euro.png',
openGraphImage: '50euro.png',
schemaImage: '100euro.png'
},
{
path: '/subpage',
title: 'Test Subpage Title',
description: 'Test subpage description',
twitterImage: '100euro.png',
openGraphImage: '50euro.png',
schemaImage: '20euro.png'
}
];
var opts = {
publishFromFolder: 'dist',
assetContext: 'test-path/',
pageDefs: defs,
embedCodes: false,
iframeResize: false,
entryPoint: path.resolve('src/js/entry-point.jsx'),
}
var builder = require('../../index.js'); // lucify-component-builder
builder(gulp, opts);
|
Update languages literals in subscription selector | define([], function() {
/**
* List of the key languages of the platform
*/
var languageList = {
en: 'English',
zh: '中文',
fr: 'Français',
id: 'Bahasa Indonesia',
pt_BR: 'Português',
es_MX: 'Español'
};
var languagesHelper = {
/**
* Returns the list of key languages
* @returns {Object} key languages list
*/
getList: function() {
return languageList;
},
/**
* Returns a list of the key languages
* with the selected option passed by param
* @param {string} selected language
* @returns {Array} list of languages with selection
*/
getListSelected: function(selectedLanguage) {
var langList = [];
for (var lang in languageList) {
langList.push({
key: lang,
name: languageList[lang],
selected: lang === selectedLanguage ? 'selected' : ''
});
}
return langList;
}
}
return languagesHelper;
});
| define([], function() {
/**
* List of the key languages of the platform
*/
var languageList = {
en: 'English',
zh: '中文',
fr: 'Français',
id: 'Bahasa Indonesia',
pt_BR: 'Português (Brasil)',
es_MX: 'Español (Mexico)'
};
var languagesHelper = {
/**
* Returns the list of key languages
* @returns {Object} key languages list
*/
getList: function() {
return languageList;
},
/**
* Returns a list of the key languages
* with the selected option passed by param
* @param {string} selected language
* @returns {Array} list of languages with selection
*/
getListSelected: function(selectedLanguage) {
var langList = [];
for (var lang in languageList) {
langList.push({
key: lang,
name: languageList[lang],
selected: lang === selectedLanguage ? 'selected' : ''
});
}
return langList;
}
}
return languagesHelper;
});
|
Rename parameter to match color component name
git-svn-id: ef215b97ec449bc9c69e2ae1448853f14b3d8f41@1648315 13f79535-47bb-0310-9956-ffa450edef68 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.apache.commons.imaging.color;
public final class ColorCieLab {
public final double L;
public final double a;
public final double b;
public ColorCieLab(final double L, final double a, final double b) {
this.L = L;
this.a = a;
this.b = b;
}
@Override
public String toString() {
return "{L: " + L + ", a: " + a + ", b: " + b + "}";
}
}
| /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.apache.commons.imaging.color;
public final class ColorCieLab {
public final double L;
public final double a;
public final double b;
public ColorCieLab(final double l, final double a, final double b) {
L = l;
this.a = a;
this.b = b;
}
@Override
public String toString() {
return "{L: " + L + ", a: " + a + ", b: " + b + "}";
}
}
|
Make sure `n` is defined and use `alert`
Checking that `n` is not undefined before calling `n.length` prevents an exception. Droplr now also overrides `console.log` (and other console functions) so changed it to `alert`. | // First dump
var amount = 100;
var coll = Droplr.DropList;
function fetchNext() {
coll.fetch({
data: {
type: coll.type,
amount: amount,
offset: coll.offset,
sortBy: coll.sortBy,
order: coll.order,
search: coll.search
},
update: !0,
remove: !1,
success: function(t, n) {
coll.offset += amount;
if (coll.offset === amount) {
alert('Loading... Press <enter> to continue.');
}
if (n && n.length !== 0) {
setTimeout(fetchNext, 100);
} else {
alert('Done! Now copy/paste and run the following command:');
alert('copy(JSON.stringify(coll.pluck(\'code\'), null, 2));alert("Drops successfully copied to clipboard!");')
}
}
})
}
fetchNext();
| // First dump
var amount = 100;
var coll = Droplr.DropList;
function fetchNext() {
coll.fetch({
data: {
type: coll.type,
amount: amount,
offset: coll.offset,
sortBy: coll.sortBy,
order: coll.order,
search: coll.search
},
update: !0,
remove: !1,
success: function(t, n) {
coll.offset += amount;
if (n.length !== 0) {
console.log('Loading...', coll.offset);
setTimeout(fetchNext, 100);
} else {
console.log('Done! Now copy/paste and run the following command:');
console.log('copy(JSON.stringify(coll.pluck(\'code\'), null, 2));console.log("Drops successfully copied to clipboard!");')
}
}
})
}
fetchNext();
|
Remove padding call from tutorial. | function makeBarChart() {
var xScale = new Plottable.OrdinalScale().rangeType("bands");
var yScale = new Plottable.LinearScale();
var xAxis = new Plottable.XAxis(xScale, "bottom", function(d) { return d; });
var yAxis = new Plottable.YAxis(yScale, "left");
var renderer = new Plottable.BarRenderer(barData, xScale, yScale)
.project("x", "category", xScale)
.project("y", "value", yScale)
.project("fill", function() { return "steelblue"; } );
var chart = new Plottable.Table([
[yAxis, renderer],
[null, xAxis ]
]);
chart.renderTo("#bar-chart");
}
| function makeBarChart() {
var xScale = new Plottable.OrdinalScale().rangeType("bands");
var yScale = new Plottable.LinearScale();
var xAxis = new Plottable.XAxis(xScale, "bottom", function(d) { return d; });
var yAxis = new Plottable.YAxis(yScale, "left");
var renderer = new Plottable.BarRenderer(barData, xScale, yScale)
.project("x", "category", xScale)
.project("y", "value", yScale)
.project("fill", function() { return "steelblue"; } );
yScale.padDomain();
var chart = new Plottable.Table([
[yAxis, renderer],
[null, xAxis ]
]);
chart.renderTo("#bar-chart");
}
|
Allow a null model for the NoDatabaseUserProvider | <?php
namespace Adldap\Laravel\Events;
use Adldap\Models\User;
use Illuminate\Contracts\Auth\Authenticatable;
class AuthenticatedWithCredentials
{
/**
* The authenticated LDAP user.
*
* @var User
*/
public $user;
/**
* The authenticated LDAP users model.
*
* @var Authenticatable
*/
public $model;
/**
* Constructor.
*
* @param User $user
* @param Authenticatable|null $model
*/
public function __construct(User $user, Authenticatable $model = null)
{
$this->user = $user;
$this->model = $model;
}
}
| <?php
namespace Adldap\Laravel\Events;
use Adldap\Models\User;
use Illuminate\Contracts\Auth\Authenticatable;
class AuthenticatedWithCredentials
{
/**
* The authenticated LDAP user.
*
* @var User
*/
public $user;
/**
* The authenticated LDAP users model.
*
* @var Authenticatable
*/
public $model;
/**
* Constructor.
*
* @param User $user
* @param Authenticatable $model
*/
public function __construct(User $user, Authenticatable $model)
{
$this->user = $user;
$this->model = $model;
}
}
|
Remove const that is not supported in older php versions | <?php
class myKuserUtils
{
const NON_EXISTING_USER_ID = -1;
const USERS_DELIMITER = ',';
const DOT_CHAR = '.';
const SPACE_CHAR = ' ';
public static function preparePusersToKusersFilter( $puserIdsCsv )
{
$kuserIdsArr = array();
$puserIdsArr = explode(self::USERS_DELIMITER, $puserIdsCsv);
$kuserArr = kuserPeer::getKuserByPartnerAndUids(kCurrentContext::getCurrentPartnerId(), $puserIdsArr);
foreach($kuserArr as $kuser)
{
$kuserIdsArr[] = $kuser->getId();
}
if(!empty($kuserIdsArr))
{
return implode(self::USERS_DELIMITER, $kuserIdsArr);
}
return self::NON_EXISTING_USER_ID; // no result will be returned if no puser exists
}
public static function startsWithSpecialChar($str)
{
return $str && in_array($str[0], array('+', '=', '-', '@', ','));
}
public static function sanitizeFields(array $values)
{
$sanitizedValues = array();
foreach ($values as $val)
{
$sanitizedVal = str_replace(self::DOT_CHAR, self::SPACE_CHAR, $val);
$sanitizedValues[] = $sanitizedVal;
}
return $sanitizedValues;
}
}
| <?php
class myKuserUtils
{
const SPECIAL_CHARS = array('+', '=', '-', '@', ',');
const NON_EXISTING_USER_ID = -1;
const USERS_DELIMITER = ',';
const DOT_CHAR = '.';
const SPACE_CHAR = ' ';
public static function preparePusersToKusersFilter( $puserIdsCsv )
{
$kuserIdsArr = array();
$puserIdsArr = explode(self::USERS_DELIMITER, $puserIdsCsv);
$kuserArr = kuserPeer::getKuserByPartnerAndUids(kCurrentContext::getCurrentPartnerId(), $puserIdsArr);
foreach($kuserArr as $kuser)
{
$kuserIdsArr[] = $kuser->getId();
}
if(!empty($kuserIdsArr))
{
return implode(self::USERS_DELIMITER, $kuserIdsArr);
}
return self::NON_EXISTING_USER_ID; // no result will be returned if no puser exists
}
public static function startsWithSpecialChar($str)
{
return $str && in_array($str[0], self::SPECIAL_CHARS);
}
public static function sanitizeFields(array $values)
{
$sanitizedValues = array();
foreach ($values as $val)
{
$sanitizedVal = str_replace(self::DOT_CHAR, self::SPACE_CHAR, $val);
$sanitizedValues[] = $sanitizedVal;
}
return $sanitizedValues;
}
}
|
Fix the metadata for posts. | """
"""
from string import Template
from paper_to_git.config import config
__all__ = [
'generate_metadata',
]
METADATA_TEMPLATE = Template("""\
---
title: "$title"
date: "$date"
---
""")
def generate_metadata(doc, metadata_type=None):
"""
Generate the appropriate metadata based on the type specified.
"""
if metadata_type is None:
metadata_type = config.metadata.type
if metadata_type == "yaml":
return generate_yaml_metadata(doc)
raise NotImplementedError
def generate_yaml_metadata(doc):
"""
Generate the YAML metadata to add on top of a PaperDoc when moving a
PaperDoc to a static site generator.
"""
return METADATA_TEMPLATE.safe_substitute(title=doc.title,
date=doc.last_updated)
| """
"""
from string import Template
from paper_to_git.config import config
__all__ = [
'generate_metadata',
]
METADATA_TEMPLATE = Template("""\
---
title: $title
date: $date
---
""")
def generate_metadata(doc, metadata_type=None):
"""
Generate the appropriate metadata based on the type specified.
"""
if metadata_type is None:
metadata_type = config.metadata.type
if metadata_type == "yaml":
return generate_yaml_metadata(doc)
raise NotImplementedError
def generate_yaml_metadata(doc):
"""
Generate the YAML metadata to add on top of a PaperDoc when moving a
PaperDoc to a static site generator.
"""
return METADATA_TEMPLATE.safe_substitute(title=doc.title,
date=doc.last_updated)
|
Change file logHandler to use configured path for log files | import config
import logging
import logging.handlers
# ######### Set up logging ##########
# log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG)
logger = logging.getLogger('bb_log')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
tfh = logging.handlers.TimedRotatingFileHandler(str.format('{0}/app.log', config.log_directory),
when='midnight', delay=False, encoding=None, backupCount=7)
tfh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter and add it to the handlers
formatterch = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s')
formattertfh = logging.Formatter('%(asctime)s [%(levelname)s] [%(name)s] %(message)s')
ch.setFormatter(formatterch)
tfh.setFormatter(formattertfh)
# add the handlers to logger
logger.addHandler(ch)
logger.addHandler(tfh) | import logging
import logging.handlers
# ######### Set up logging ##########
# log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG)
logger = logging.getLogger('bb_log')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
tfh = logging.handlers.TimedRotatingFileHandler('./logs/app.log', when='midnight', delay=False, encoding=None,
backupCount=7)
tfh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter and add it to the handlers
formatterch = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s')
formattertfh = logging.Formatter('%(asctime)s [%(levelname)s] [%(name)s] %(message)s')
ch.setFormatter(formatterch)
tfh.setFormatter(formattertfh)
# add the handlers to logger
logger.addHandler(ch)
logger.addHandler(tfh) |
Include a critical truthy value in asBool test | package backend
import (
"fmt"
"net/http"
"testing"
"github.com/stretchr/testify/assert"
)
type recordingHTTPTransport struct {
req *http.Request
}
func (t *recordingHTTPTransport) RoundTrip(req *http.Request) (*http.Response, error) {
t.req = req
return nil, fmt.Errorf("recording HTTP transport impl")
}
func TestAsBool(t *testing.T) {
for s, b := range map[string]bool{
"yes": true,
"on": true,
"1": true,
"boo": true,
"0": false,
"99": true,
"a": true,
"off": false,
"no": false,
"fafafaf": true,
"": false,
} {
assert.Equal(t, b, asBool(s))
}
}
| package backend
import (
"fmt"
"net/http"
"testing"
"github.com/stretchr/testify/assert"
)
type recordingHTTPTransport struct {
req *http.Request
}
func (t *recordingHTTPTransport) RoundTrip(req *http.Request) (*http.Response, error) {
t.req = req
return nil, fmt.Errorf("recording HTTP transport impl")
}
func TestAsBool(t *testing.T) {
for s, b := range map[string]bool{
"yes": true,
"on": true,
"1": true,
"boo": true,
"0": false,
"99": true,
"a": true,
"off": false,
"no": false,
"": false,
} {
assert.Equal(t, b, asBool(s))
}
}
|
Remove physician_us depends in first_databank | # -*- coding: utf-8 -*-
# © 2015 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
'name': 'First Databank',
'description': 'Provides base models for storage of First Databank data',
'version': '9.0.1.0.0',
'category': 'Connector',
'author': "LasLabs",
'license': 'AGPL-3',
'website': 'https://laslabs.com',
'depends': [
'medical_prescription_sale_stock',
'medical_insurance_us',
'medical_medicament_us',
# 'medical_patient_us',
# 'medical_physician_us',
'medical_pharmacy_us',
'medical_prescription_us',
'medical_prescription_sale_stock_us',
'medical_manufacturer',
],
'installable': True,
'application': False,
}
| # -*- coding: utf-8 -*-
# © 2015 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
'name': 'First Databank',
'description': 'Provides base models for storage of First Databank data',
'version': '9.0.1.0.0',
'category': 'Connector',
'author': "LasLabs",
'license': 'AGPL-3',
'website': 'https://laslabs.com',
'depends': [
'medical_prescription_sale_stock',
'medical_insurance_us',
'medical_medicament_us',
# 'medical_patient_us',
'medical_physician_us',
'medical_pharmacy_us',
'medical_prescription_us',
'medical_prescription_sale_stock_us',
'medical_manufacturer',
],
'installable': True,
'application': False,
}
|
Make sure to immediately do apt-get update when adding a repository |
from kokki import *
apt_list_path = '/etc/apt/sources.list.d/cloudera.list'
apt = (
"deb http://archive.cloudera.com/debian {distro}-cdh3 contrib\n"
"deb-src http://archive.cloudera.com/debian {distro}-cdh3 contrib\n"
).format(distro=env.system.lsb['codename'])
Execute("apt-get update", action="nothing")
Execute("curl -s http://archive.cloudera.com/debian/archive.key | sudo apt-key add -",
not_if = "(apt-key list | grep Cloudera > /dev/null)")
File(apt_list_path,
owner = "root",
group ="root",
mode = 0644,
content = apt,
notifies = [("run", env.resources["Execute"]["apt-get update"], True)])
|
from kokki import *
apt_list_path = '/etc/apt/sources.list.d/cloudera.list'
apt = (
"deb http://archive.cloudera.com/debian {distro}-cdh3 contrib\n"
"deb-src http://archive.cloudera.com/debian {distro}-cdh3 contrib\n"
).format(distro=env.system.lsb['codename'])
Execute("apt-get update", action="nothing")
Execute("curl -s http://archive.cloudera.com/debian/archive.key | sudo apt-key add -",
not_if = "(apt-key list | grep Cloudera > /dev/null)")
File(apt_list_path,
owner = "root",
group ="root",
mode = 0644,
content = apt,
notifies = [("run", env.resources["Execute"]["apt-get update"])])
|
Add Color math operations (add, multiply, multiplyScalar). | /*jshint bitwise:false*/
'use strict';
var lerp = require( './utils' ).lerp;
// RGB values are ints from [0, 255].
function Color( r, g, b ) {
this.r = r || 0;
this.g = g || 0;
this.b = b || 0;
}
Color.prototype.toString = function() {
return 'rgb(' +
( this.r | 0 ) + ', ' +
( this.g | 0 ) + ', ' +
( this.b | 0 ) +
')';
};
Color.prototype.add = function( color ) {
this.r += color.r;
this.g += color.g;
this.b += color.b;
return this;
};
Color.prototype.multiply = function( color ) {
this.r *= color.r;
this.g *= color.g;
this.b *= color.b;
return this;
};
Color.prototype.multiplyScalar = function( s ) {
this.r *= s;
this.g *= s;
this.b *= s;
return this;
};
Color.prototype.lerp = function( color, alpha ) {
this.r = lerp( this.r, color.r, alpha );
this.g = lerp( this.g, color.g, alpha );
this.b = lerp( this.b, color.b, alpha );
return this;
};
Color.prototype.copy = function( color ) {
this.r = color.r;
this.g = color.g;
this.b = color.b;
return this;
};
module.exports = Color;
| /*jshint bitwise:false*/
'use strict';
var lerp = require( './utils' ).lerp;
// RGB values are ints from [0, 255].
function Color( r, g, b ) {
this.r = r || 0;
this.g = g || 0;
this.b = b || 0;
}
Color.prototype.toString = function() {
return 'rgb(' +
( this.r | 0 ) + ', ' +
( this.g | 0 ) + ', ' +
( this.b | 0 ) +
')';
};
Color.prototype.lerp = function( color, alpha ) {
this.r = lerp( this.r, color.r, alpha );
this.g = lerp( this.g, color.g, alpha );
this.b = lerp( this.b, color.b, alpha );
return this;
};
Color.prototype.copy = function( color ) {
this.r = color.r;
this.g = color.g;
this.b = color.b;
return this;
};
module.exports = Color;
|
Allow typed predicate to handle nulls | /*
* #%L
* BroadleafCommerce Common Libraries
* %%
* Copyright (C) 2009 - 2013 Broadleaf Commerce
* %%
* 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.
* #L%
*/
package org.broadleafcommerce.common.util;
import org.apache.commons.collections.Predicate;
import java.lang.reflect.ParameterizedType;
/**
* A class that provides for a typed predicat
*
* @author Andre Azzolini (apazzolini)
*
* @param <T> the type of object the predicate uses
*/
@SuppressWarnings("unchecked")
public abstract class TypedPredicate<T> implements Predicate {
protected Class<T> clazz;
public TypedPredicate() {
clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
public boolean evaluate(Object value) {
if (value == null || clazz.isAssignableFrom(value.getClass())) {
return eval((T) value);
}
return false;
}
public abstract boolean eval(T value);
}
| /*
* #%L
* BroadleafCommerce Common Libraries
* %%
* Copyright (C) 2009 - 2013 Broadleaf Commerce
* %%
* 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.
* #L%
*/
package org.broadleafcommerce.common.util;
import org.apache.commons.collections.Predicate;
import java.lang.reflect.ParameterizedType;
/**
* A class that provides for a typed predicat
*
* @author Andre Azzolini (apazzolini)
*
* @param <T> the type of object the predicate uses
*/
@SuppressWarnings("unchecked")
public abstract class TypedPredicate<T> implements Predicate {
protected Class<T> clazz;
public TypedPredicate() {
clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
public boolean evaluate(Object value) {
if (clazz.isAssignableFrom(value.getClass())) {
return eval((T) value);
}
return false;
}
public abstract boolean eval(T value);
}
|
Drop <pre> to make long commands readable. | package termite
import (
"fmt"
"http"
)
func (me *WorkerDaemon) httpHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "<html><head><title>Termite worker</head></title>")
fmt.Fprintf(w, "<h1>Termite worker status</h1>")
fmt.Fprintf(w, "<body>")
me.masterMapMutex.Lock()
defer me.masterMapMutex.Unlock()
for k, v := range me.masterMap {
fmt.Fprintf(w, "<h2>Mirror</h2><p><tt>%s</tt>\n", k)
v.httpHandler(w, r)
}
fmt.Fprintf(w, "</body></html>")
}
func (me *Mirror) httpHandler(w http.ResponseWriter, r *http.Request) {
me.fuseFileSystemsMutex.Lock()
defer me.fuseFileSystemsMutex.Unlock()
for _, v := range me.workingFileSystems {
fmt.Fprintf(w, "<p>FS:\n%s\n", v)
}
fmt.Fprintf(w, "<p>%d unused filesystems.", len(me.fuseFileSystems))
}
func (me *WorkerDaemon) ServeHTTPStatus(port int) {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
me.httpHandler(w, r)
})
http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
}
| package termite
import (
"fmt"
"http"
)
func (me *WorkerDaemon) httpHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "<html><head><title>Termite worker</head></title>")
fmt.Fprintf(w, "<h1>Termite worker status</h1>")
fmt.Fprintf(w, "<body><pre>")
me.masterMapMutex.Lock()
defer me.masterMapMutex.Unlock()
for k, v := range me.masterMap {
fmt.Fprintf(w, "\n******\nMirror: %s\n\n", k)
v.httpHandler(w, r)
}
fmt.Fprintf(w, "</pre></body></html>")
}
func (me *Mirror) httpHandler(w http.ResponseWriter, r *http.Request) {
me.fuseFileSystemsMutex.Lock()
defer me.fuseFileSystemsMutex.Unlock()
for _, v := range me.workingFileSystems {
fmt.Fprintf(w, "FS:\n%s\n", v)
}
fmt.Fprintf(w, "%d unused filesystems.", len(me.fuseFileSystems))
}
func (me *WorkerDaemon) ServeHTTPStatus(port int) {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
me.httpHandler(w, r)
})
http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
}
|
Add getter for the fluid handler | package info.u_team.u_team_core.container;
import info.u_team.u_team_core.api.fluid.IFluidHandlerModifiable;
import net.minecraftforge.fluids.FluidStack;
public class FluidSlot {
private final IFluidHandlerModifiable fluidHandler;
private final int index;
private final int x;
private final int y;
public int slotNumber;
public FluidSlot(IFluidHandlerModifiable fluidHandler, int index, int x, int y) {
this.fluidHandler = fluidHandler;
this.index = index;
this.x = x;
this.y = y;
}
public boolean isFluidValid(FluidStack stack) {
if (stack.isEmpty()) {
return false;
}
return fluidHandler.isFluidValid(index, stack);
}
public FluidStack getStack() {
return fluidHandler.getFluidInTank(index);
}
public void putStack(FluidStack stack) {
fluidHandler.setFluidInTank(index, stack);
}
public int getSlotCapacity() {
return fluidHandler.getTankCapacity(index);
}
public IFluidHandlerModifiable getFluidHandler() {
return fluidHandler;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public boolean isEnabled() {
return true;
}
}
| package info.u_team.u_team_core.container;
import info.u_team.u_team_core.api.fluid.IFluidHandlerModifiable;
import net.minecraftforge.fluids.FluidStack;
public class FluidSlot {
private final IFluidHandlerModifiable fluidHandler;
private final int index;
private final int x;
private final int y;
public int slotNumber;
public FluidSlot(IFluidHandlerModifiable fluidHandler, int index, int x, int y) {
this.fluidHandler = fluidHandler;
this.index = index;
this.x = x;
this.y = y;
}
public boolean isFluidValid(FluidStack stack) {
if (stack.isEmpty()) {
return false;
}
return fluidHandler.isFluidValid(index, stack);
}
public FluidStack getStack() {
return fluidHandler.getFluidInTank(index);
}
public void putStack(FluidStack stack) {
fluidHandler.setFluidInTank(index, stack);
}
public int getSlotCapacity() {
return fluidHandler.getTankCapacity(index);
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public boolean isEnabled() {
return true;
}
}
|
Use argparse instead of sys.argv | #! /usr/bin/env python3
import sys
import argparse
from gitaccount import GitAccount
def main():
parser = argparse.ArgumentParser(
prog='gitcloner',
description='Clone all the repositories from a github user/org\naccount to the current directory')
group = parser.add_mutually_exclusive_group()
group.add_argument('-u', '--user', help='For user accounts [DEFAULT]',
action='store_true')
group.add_argument('-o', '--org', help='For organization accounts',
action='store_true')
parser.add_argument('name', help='name of the user / organization')
args = parser.parse_args()
if not(args.user or args.org):
args.user = True
print('Default account type is user account')
if args.user:
print('Username: {}'.format(args.name))
accType = 'user'
else:
print('Organization: {}'.format(args.name))
accType = 'org'
account = GitAccount(accType, args.name)
account.cloneRepos()
if __name__ == '__main__':
main()
| #! /usr/bin/env python3
import sys
from gitaccount import GitAccount
def main():
if len(sys.argv) < 2:
print("""Usage:
gitcloner.py [OPTION] [NAME]
OPTIONS:
-u - for user repositories
-o - for organization repositories
NAME:
Username or Organization Name
""")
sys.exit(1)
args = sys.argv[1:3]
repoType, name = args
if repoType == '-u':
repoType = 'user'
elif repoType == '-o':
repoType = 'org'
else:
raise ValueError()
account = GitAccount(repoType, name)
account.cloneRepos()
if __name__ == '__main__':
main()
|
Disable idleTimer on iOS for appified apps | /*
* This is a template used when TiShadow "appifying" a titanium project.
* See the README.
*/
Titanium.App.idleTimerDisabled = true;
var TiShadow = require("/api/TiShadow");
var Compression = require('ti.compression');
// Need to unpack the bundle on a first load;
var path_name = "{{app_name}}".replace(/ /g,"_");
var target = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, path_name);
if (!target.exists()) {
target.createDirectory();
Compression.unzip(Ti.Filesystem.applicationDataDirectory + "/" + path_name, Ti.Filesystem.resourcesDirectory + "/" + path_name + '.zip',true);
}
//Call home
TiShadow.connect({
proto: "{{proto}}",
host : "{{host}}",
port : "{{port}}",
room : "{{room}}",
name : Ti.Platform.osname + ", " + Ti.Platform.version + ", " + Ti.Platform.address
});
//Launch the app
TiShadow.launchApp(path_name);
| /*
* This is a template used when TiShadow "appifying" a titanium project.
* See the README.
*/
var TiShadow = require("/api/TiShadow");
var Compression = require('ti.compression');
// Need to unpack the bundle on a first load;
var path_name = "{{app_name}}".replace(/ /g,"_");
var target = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, path_name);
if (!target.exists()) {
target.createDirectory();
Compression.unzip(Ti.Filesystem.applicationDataDirectory + "/" + path_name, Ti.Filesystem.resourcesDirectory + "/" + path_name + '.zip',true);
}
//Call home
TiShadow.connect({
proto: "{{proto}}",
host : "{{host}}",
port : "{{port}}",
room : "{{room}}",
name : Ti.Platform.osname + ", " + Ti.Platform.version + ", " + Ti.Platform.address
});
//Launch the app
TiShadow.launchApp(path_name);
|
Add Retrofit to licenses list. | package com.levibostian.pantrypirate.model;
import com.levibostian.pantrypirate.vo.License;
import java.util.ArrayList;
public class LicensesModel {
private ArrayList<License> mLicenses;
public LicensesModel() {
mLicenses = new ArrayList<License>();
setUpLicenses();
}
private void setUpLicenses() {
mLicenses.add(new License("Android-RobotoTextView", "https://github.com/johnkil/Android-RobotoTextView"));
mLicenses.add(new License("Tomáš Procházka ImageView", "https://gist.github.com/tprochazka/5486822"));
mLicenses.add(new License("ListViewAnimations", "https://github.com/nhaarman/ListViewAnimations"));
mLicenses.add(new License("EnhancedListView", "https://github.com/timroes/EnhancedListView"));
mLiencses.add(new License("Retrofit", "https://square.github.io/retrofit/"));
}
public ArrayList<License> getLicenses() {
return mLicenses;
}
public License getLicense(int position) {
return mLicenses.get(position);
}
}
| package com.levibostian.pantrypirate.model;
import com.levibostian.pantrypirate.vo.License;
import java.util.ArrayList;
public class LicensesModel {
private ArrayList<License> mLicenses;
public LicensesModel() {
mLicenses = new ArrayList<License>();
setUpLicenses();
}
private void setUpLicenses() {
mLicenses.add(new License("Android-RobotoTextView", "https://github.com/johnkil/Android-RobotoTextView"));
mLicenses.add(new License("Tomáš Procházka ImageView", "https://gist.github.com/tprochazka/5486822"));
mLicenses.add(new License("ListViewAnimations", "https://github.com/nhaarman/ListViewAnimations"));
mLicenses.add(new License("EnhancedListView", "https://github.com/timroes/EnhancedListView"));
}
public ArrayList<License> getLicenses() {
return mLicenses;
}
public License getLicense(int position) {
return mLicenses.get(position);
}
}
|
Remove react devtools exact path | const { app, BrowserWindow } = require('electron');
//Window settings
const WINDOW_WIDTH = 1280;
const WINDOW_HEIGHT = 720;
const WINDOW_FRAME = false;
const WINDOW_SHOW = true;
const WINDOW_FOCUS = true;
const WINDOW_THICK_FRAME = true;
const WINDOW_BACKGROUND_COLOR = '#141B23';
//Set window params
const setWindowParams = () => {
return new BrowserWindow({
width: WINDOW_WIDTH,
height: WINDOW_HEIGHT,
minWidth: WINDOW_WIDTH,
minHeight: WINDOW_HEIGHT,
frame: WINDOW_FRAME,
backgroundColor: WINDOW_BACKGROUND_COLOR,
thickFrame: WINDOW_THICK_FRAME,
focusable: WINDOW_FOCUS,
show: WINDOW_SHOW,
});
};
//Start app
app.on('ready', () => {
let mainWindow = setWindowParams();
mainWindow.openDevTools({ detached: true });
mainWindow.setResizable(true);
mainWindow.loadURL('http://localhost:3000/');
});
//Close app
app.on('window-all-closed', () => {
app.quit();
});
| const { app, BrowserWindow } = require('electron');
//Window settings
const WINDOW_WIDTH = 1280;
const WINDOW_HEIGHT = 720;
const WINDOW_FRAME = false;
const WINDOW_SHOW = true;
const WINDOW_FOCUS = true;
const WINDOW_THICK_FRAME = true;
const WINDOW_BACKGROUND_COLOR = '#141B23';
//Set window params
const setWindowParams = () => {
return new BrowserWindow({
width: WINDOW_WIDTH,
height: WINDOW_HEIGHT,
minWidth: WINDOW_WIDTH,
minHeight: WINDOW_HEIGHT,
frame: WINDOW_FRAME,
backgroundColor: WINDOW_BACKGROUND_COLOR,
thickFrame: WINDOW_THICK_FRAME,
focusable: WINDOW_FOCUS,
show: WINDOW_SHOW,
});
};
//Start app
app.on('ready', () => {
let mainWindow = setWindowParams();
mainWindow.openDevTools({ detached: true });
BrowserWindow.addDevToolsExtension(
'C:\\Users\\Jenster\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Extensions\\fmkadmapgofadopljbjfkapdkoienihi\\3.2.3_0'
);
mainWindow.setResizable(true);
mainWindow.loadURL('http://localhost:3000/');
});
//Close app
app.on('window-all-closed', () => {
app.quit();
});
|
Handle null tags when getting video
- Grpc doesn't allow null for fields and cassandra may return null for tags | import Promise from 'bluebird';
import { GetVideoResponse, VideoLocationType } from './protos';
import { toCassandraUuid, toProtobufTimestamp, toProtobufUuid } from '../common/protobuf-conversions';
import { NotFoundError } from '../common/grpc-errors';
import { getCassandraClient } from '../../common/cassandra';
/**
* Gets the details of a specific video from the catalog.
*/
export function getVideo(call, cb) {
return Promise.try(() => {
let { request } = call;
let client = getCassandraClient();
let requestParams = [
toCassandraUuid(request.videoId)
];
return client.executeAsync('SELECT * FROM videos WHERE videoid = ?', requestParams);
})
.then(resultSet => {
let row = resultSet.first();
if (row === null) {
throw new NotFoundError(`A video with id ${request.videoId.value} was not found`);
}
return new GetVideoResponse({
videoId: toProtobufUuid(row.videoid),
userId: toProtobufUuid(row.userid),
name: row.name,
description: row.description,
location: row.location,
locationType: row.location_type,
tags: row.tags === null ? [] : row.tags,
addedDate: toProtobufTimestamp(row.added_date)
});
})
.asCallback(cb);
}; | import Promise from 'bluebird';
import { GetVideoResponse, VideoLocationType } from './protos';
import { toCassandraUuid, toProtobufTimestamp, toProtobufUuid } from '../common/protobuf-conversions';
import { NotFoundError } from '../common/grpc-errors';
import { getCassandraClient } from '../../common/cassandra';
/**
* Gets the details of a specific video from the catalog.
*/
export function getVideo(call, cb) {
return Promise.try(() => {
let { request } = call;
let client = getCassandraClient();
let requestParams = [
toCassandraUuid(request.videoId)
];
return client.executeAsync('SELECT * FROM videos WHERE videoid = ?', requestParams);
})
.then(resultSet => {
let row = resultSet.first();
if (row === null) {
throw new NotFoundError(`A video with id ${request.videoId.value} was not found`);
}
return new GetVideoResponse({
videoId: toProtobufUuid(row.videoid),
userId: toProtobufUuid(row.userid),
name: row.name,
description: row.description,
location: row.location,
locationType: row.location_type,
tags: row.tags,
addedDate: toProtobufTimestamp(row.added_date)
});
})
.asCallback(cb);
}; |
Update linkset preview to use POST not GET | <?php defined('SYSPATH') OR die('No direct script access.');
/**
*
* @package BoomCMS
* @category Chunks
* @category Controllers
* @author Rob Taylor
* @copyright Hoop Associates
*/
class Boom_Controller_Cms_Chunk_Linkset extends Boom_Controller_Cms_Chunk
{
public function action_edit()
{
$this->template = View::factory('boom/editor/slot/linkset', array(
'page' => $this->page,
));
}
public function action_preview()
{
// Instantiate a linkset model
$model = new Model_Chunk_Linkset;
// Get the linkset data from the query string.
$data = $this->request->post();
if (isset($data['data']['links']))
{
// urldecode() to the link urls
foreach ($data['data']['links'] as & $link)
{
$link['url'] = urldecode($link['url']);
}
// Add the links to the linkset model.
$model->links($data['data']['links']);
}
// Create a chunk with the linkset model.
$chunk = new Chunk_Linkset($this->page, $model, $data['slotname'], TRUE);
$chunk->template($data['template']);
// Display the chunk.
$this->response->body($chunk->execute());
}
}
| <?php defined('SYSPATH') OR die('No direct script access.');
/**
*
* @package BoomCMS
* @category Chunks
* @category Controllers
* @author Rob Taylor
* @copyright Hoop Associates
*/
class Boom_Controller_Cms_Chunk_Linkset extends Boom_Controller_Cms_Chunk
{
public function action_edit()
{
$this->template = View::factory('boom/editor/slot/linkset', array(
'page' => $this->page,
));
}
public function action_preview()
{
// Instantiate a linkset model
$model = new Model_Chunk_Linkset;
// Get the linkset data from the query string.
// TODO: POST would be better for linksets, slideshows already use POST.
$query = $this->request->query();
if (isset($query['data']['links']))
{
// urldecode() to the link urls
foreach ($query['data']['links'] as & $link)
{
$link['url'] = urldecode($link['url']);
}
// Add the links to the linkset model.
$model->links($query['data']['links']);
}
// Create a chunk with the linkset model.
$chunk = new Chunk_Linkset($this->page, $model, $query['slotname'], TRUE);
$chunk->template($query['template']);
// Display the chunk.
$this->response->body($chunk->execute());
}
} |
Add documentation and tidy up a bit
git-svn-id: 52ad764cdf1b64a6e804f4e5ad13917d3c4b2253@349151 13f79535-47bb-0310-9956-ffa450edef68 | /*
* Copyright 2001-2005 The Apache Software Foundation.
*
* 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.apache.jmeter.util;
/**
* @version $Revision$
*/
public final class StringUtilities {
/**
* Private constructor to prevent instantiation.
*/
private StringUtilities() {
}
/**
* Replace all patterns in a String
*
* @see String.replaceAll(regex,replacement) - JDK1.4 only
*
* @param input - string to be transformed
* @param pattern - pattern to replace
* @param sub - replacement
* @return the updated string
*/
public static String substitute(final String input, final String pattern, final String sub) {
StringBuffer ret = new StringBuffer(input.length());
int start = 0;
int index = -1;
final int length = pattern.length();
while ((index = input.indexOf(pattern, start)) >= start) {
ret.append(input.substring(start, index));
ret.append(sub);
start = index + length;
}
ret.append(input.substring(start));
return ret.toString();
}
}
| /*
* Copyright 2001-2005 The Apache Software Foundation.
*
* 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.apache.jmeter.util;
/**
* @version $Revision$
*/
public final class StringUtilities {
public static String substitute(String input, String pattern, String sub) {
StringBuffer ret = new StringBuffer();
int start = 0;
int index = -1;
while ((index = input.indexOf(pattern, start)) >= start) {
ret.append(input.substring(start, index));
ret.append(sub);
start = index + pattern.length();
}
ret.append(input.substring(start));
return ret.toString();
}
/**
* Private constructor to prevent instantiation.
*/
private StringUtilities() {
}
}
|
Fix failing test due to change in taskmanager name | package seedu.manager.commons.core;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import seedu.manager.commons.core.Config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ConfigTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void toString_defaultObject_stringReturned() {
String defaultConfigAsString = "App title : Task Ninja\n" +
"Current log level : INFO\n" +
"Preference file Location : preferences.json\n" +
"Local data file location : data/taskmanager.xml\n" +
"TaskManager name : Task Ninja";
assertEquals(defaultConfigAsString, new Config().toString());
}
@Test
public void equalsMethod(){
Config defaultConfig = new Config();
assertFalse(defaultConfig.equals(null));
assertTrue(defaultConfig.equals(defaultConfig));
}
}
| package seedu.manager.commons.core;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import seedu.manager.commons.core.Config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ConfigTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void toString_defaultObject_stringReturned() {
String defaultConfigAsString = "App title : Task Ninja\n" +
"Current log level : INFO\n" +
"Preference file Location : preferences.json\n" +
"Local data file location : data/taskmanager.xml\n" +
"TaskManager name : MyTaskManager";
assertEquals(defaultConfigAsString, new Config().toString());
}
@Test
public void equalsMethod(){
Config defaultConfig = new Config();
assertFalse(defaultConfig.equals(null));
assertTrue(defaultConfig.equals(defaultConfig));
}
}
|
Add Exclude Formats to skip | $(function() {
$('form').preventDoubleSubmission();
$('form').on('submit', function(e){
$(this).find('button').text('Processing...')
});
select_profiles_tab_from_url_hash();
disable_modal_links();
});
function disable_modal_links(){
if( !bootstrap_enabled() ){
$("a[data-toggle='modal'").hide();
}
}
function bootstrap_enabled(){
return (typeof $().modal == 'function');
}
function select_profiles_tab_from_url_hash(){
if( window.location.hash == '#profiles' ){
$('#my-profiles-tab a').tab('show');
}
}
// jQuery plugin to prevent double submission of forms
jQuery.fn.preventDoubleSubmission = function() {
$(this).on('submit',function(e){
var $form = $(this);
if ($form.data('submitted') === true) {
// Previously submitted - don't submit again
e.preventDefault();
} else {
// Mark it so that the next submit can be ignored
$form.data('submitted', true);
}
});
// Keep chainability
return this;
};
| $(function() {
$('form').preventDoubleSubmission();
$('form').on('submit', function(e){
$(this).find('button').text('Processing...')
});
select_profiles_tab_from_url_hash();
disable_modal_links();
});
function disable_modal_links(){
if( !bootstrap_enabled() ){
$("a[data-toggle='modal'").hide();
}
}
function bootstrap_enabled(){
return (typeof $().modal == 'function');
}
function select_profiles_tab_from_url_hash(){
if( window.location.hash == '#profiles' ){
$('#profiles-tab a').tab('show');
}
}
// jQuery plugin to prevent double submission of forms
jQuery.fn.preventDoubleSubmission = function() {
$(this).on('submit',function(e){
var $form = $(this);
if ($form.data('submitted') === true) {
// Previously submitted - don't submit again
e.preventDefault();
} else {
// Mark it so that the next submit can be ignored
$form.data('submitted', true);
}
});
// Keep chainability
return this;
};
|
Fix missing call to Params | package handle
import (
"github.com/smotti/ircx"
"github.com/smotti/tad/config"
"github.com/smotti/tad/report"
"github.com/sorcix/irc"
)
// CmdHostOs handles the CMD_HOST_OS bot command, by sending back data about
// the hosts operating system gathered by CFEngine.
func CmdHostOs(s ircx.Sender, m *irc.Message) {
report := report.HostInfo{
Filename: config.HostInfoReport,
}
var msg string
if err := report.Read(); err != nil {
msg = "Failed to read report file"
} else {
msg = report.Os.ToString()
}
s.Send(&irc.Message{
Command: irc.PRIVMSG,
Params: Params(m),
Trailing: msg,
})
}
// CmdHostId handle the CMD_HOST_ID bot command.
func CmdHostId(s ircx.Sender, m *irc.Message) {
report := report.HostInfo{
Filename: config.HostInfoReport,
}
var msg string
if err := report.Read(); err != nil {
msg = "Failed to read report file"
} else {
msg = report.Identity.ToString()
}
s.Send(&irc.Message{
Command: irc.PRIVMSG,
Params: Params(m),
Trailing: msg,
})
}
| package handle
import (
"github.com/smotti/ircx"
"github.com/smotti/tad/config"
"github.com/smotti/tad/report"
"github.com/sorcix/irc"
)
// CmdHostOs handles the CMD_HOST_OS bot command, by sending back data about
// the hosts operating system gathered by CFEngine.
func CmdHostOs(s ircx.Sender, m *irc.Message) {
report := report.HostInfo{
Filename: config.HostInfoReport,
}
var msg string
if err := report.Read(); err != nil {
msg = "Failed to read report file"
} else {
msg = report.Os.ToString()
}
s.Send(&irc.Message{
Command: irc.PRIVMSG,
Trailing: msg,
})
}
// CmdHostId handle the CMD_HOST_ID bot command.
func CmdHostId(s ircx.Sender, m *irc.Message) {
report := report.HostInfo{
Filename: config.HostInfoReport,
}
var msg string
if err := report.Read(); err != nil {
msg = "Failed to read report file"
} else {
msg = report.Identity.ToString()
}
s.Send(&irc.Message{
Command: irc.PRIVMSG,
Trailing: msg,
})
}
|
Revert "Replace browser history for detail page when movie is deleted"
This reverts commit 3d1c57b5a9830682e8a3c12cc46db64f83848679. | angular.module('jamm')
.controller('MovieDetailController', function ($scope, MovieService, $stateParams, $state) {
var movies = MovieService.movies;
var movieId = $stateParams.id;
if (movieId) {
$scope.originalMovie = _.find(movies, { id: movieId });
$scope.movie = _.cloneDeep($scope.originalMovie);
}
$scope.isModified = false;
$scope.$watch('movie', function (value) {
$scope.isModified = !_.isEqual(value, $scope.originalMovie);
}, true);
$scope.save = function() {
_.assign($scope.originalMovie, $scope.movie);
$scope.isModified = false;
};
$scope.discard = function() {
$scope.movie = _.cloneDeep($scope.originalMovie);
};
$scope.delete = function () {
_.remove(movies, { id: $scope.originalMovie.id });
$('#confirmDeleteModal').on('hidden.bs.modal', function () {
$state.go('movies');
});
$('#confirmDeleteModal').modal('hide');
};
});
| angular.module('jamm')
.controller('MovieDetailController', function ($scope, MovieService, $stateParams, $state) {
var movies = MovieService.movies;
var movieId = $stateParams.id;
if (movieId) {
$scope.originalMovie = _.find(movies, { id: movieId });
$scope.movie = _.cloneDeep($scope.originalMovie);
}
$scope.isModified = false;
$scope.$watch('movie', function (value) {
$scope.isModified = !_.isEqual(value, $scope.originalMovie);
}, true);
$scope.save = function() {
_.assign($scope.originalMovie, $scope.movie);
$scope.isModified = false;
};
$scope.discard = function() {
$scope.movie = _.cloneDeep($scope.originalMovie);
};
$scope.delete = function () {
_.remove(movies, { id: $scope.originalMovie.id });
$('#confirmDeleteModal').on('hidden.bs.modal', function () {
$state.go('movies', null, { location: 'replace' });
});
$('#confirmDeleteModal').modal('hide');
};
});
|
Fix issue with ‘respect user's privacy’ code!
It’s Js and not PHP, stupid! | <?php ///////////////////////////////////////////////////////
// ----------------------------------------------------------
// SNIPPET
// ----------------------------------------------------------
// Google analytics.js
// ----------------------------------------------------------
// Enable and set analytics ID/API KEY in config.php
// ----------------------------------------------------------
// Respect user's privacy:
// https://blog.j15h.nu/web-analytics-privacy/
// ----------------------------------------------------------
/////////////////////////////////////////////////////////////
// ----------------------------------------------------------
// Google Universal Analytics
// ----------------------------------------------------------
if (c::get('google.analytics') == true && c::get('google.analytics.id') != 'TRACKING ID IS NOT SET'): ?>
<script>
// Respect user's privacy
if ('navigator.doNotTrack' != 'yes' && 'navigator.doNotTrack' != '1' && 'navigator.msDoNotTrack' != '1') {
window.ga=function(){ga.q.push(arguments)};ga.q=[];ga.l=+new Date;ga('create','<?php echo c::get("google.analytics.id", "TRACKING ID IS NOT SET"); ?>','<?php echo str::after($site->url(), '://'); ?>');ga('set', 'anonymizeIp', true);ga('set', 'forceSSL', true);ga('send','pageview');
}
</script>
<script src="https://www.google-analytics.com/analytics.js" async defer></script>
<?php else: ?>
<!-- NO TRACKING SET! -->
<?php endif; ?>
| <?php ///////////////////////////////////////////////////////
// ----------------------------------------------------------
// SNIPPET
// ----------------------------------------------------------
// Google analytics.js
// ----------------------------------------------------------
// Enable and set analytics ID/API KEY in config.php
// ----------------------------------------------------------
/////////////////////////////////////////////////////////////
// ----------------------------------------------------------
// Google Universal Analytics
// ----------------------------------------------------------
if (c::get('google.analytics') == true && c::get('google.analytics.id') != 'TRACKING ID IS NOT SET'):
// Respect user's privacy (https://blog.j15h.nu/web-analytics-privacy/)
if ('navigator.doNotTrack' != 'yes' && 'navigator.doNotTrack' != '1' && 'navigator.msDoNotTrack' != '1'): ?>
<script>window.ga=function(){ga.q.push(arguments)};ga.q=[];ga.l=+new Date;ga('create','<?php echo c::get("google.analytics.id", "TRACKING ID IS NOT SET"); ?>','<?php echo str::after($site->url(), '://'); ?>');ga('set', 'anonymizeIp', true);ga('set', 'forceSSL', true);ga('send','pageview')</script>
<script src="https://www.google-analytics.com/analytics.js" async defer></script>
<?php endif; ?>
<?php else: ?>
<!-- NO TRACKING SET! -->
<?php endif; ?>
|
Fix the PF themes used in the default UX/UI selection. | package router;
import javax.servlet.http.HttpServletRequest;
import org.skyve.impl.web.UserAgent.UserAgentType;
import org.skyve.metadata.router.UxUi;
import org.skyve.metadata.router.UxUiSelector;
public class DefaultUxUiSelector implements UxUiSelector {
private static final UxUi PHONE = new UxUi("phone", "water");
private static final UxUi TABLET = new UxUi("tablet", "omega");
private static final UxUi DESKTOP = new UxUi("desktop", "casablanca");
private static final UxUi EXTERNAL = new UxUi("external", "omega");
@Override
public UxUi select(UserAgentType userAgentType, HttpServletRequest request) {
switch (userAgentType) {
case phone:
return PHONE;
case tablet:
return TABLET;
case desktop:
return DESKTOP;
default:
return EXTERNAL;
}
}
}
| package router;
import javax.servlet.http.HttpServletRequest;
import org.skyve.impl.web.UserAgent.UserAgentType;
import org.skyve.metadata.router.UxUi;
import org.skyve.metadata.router.UxUiSelector;
public class DefaultUxUiSelector implements UxUiSelector {
private static final UxUi PHONE = new UxUi("phone", "water");
private static final UxUi TABLET = new UxUi("tablet", "omega");
private static final UxUi DESKTOP = new UxUi("desktop", "omega");
private static final UxUi EXTERNAL = new UxUi("external", "casablanca");
@Override
public UxUi select(UserAgentType userAgentType, HttpServletRequest request) {
switch (userAgentType) {
case phone:
return PHONE;
case tablet:
return TABLET;
case desktop:
return DESKTOP;
default:
return EXTERNAL;
}
}
}
|
Use api without rate limit for example | import * as Github from './api/github';
import * as Wikipedia from './api/wikipedia';
import { createDatastore, registerApi, registerMiddleware, build } from 'datastore';
import * as Caching from 'caching';
function run() {
let datastore = createDatastore();
datastore = registerMiddleware('Caching', Caching, datastore);
datastore = registerApi('Github', Github, datastore);
datastore = registerApi('Wikipedia', Wikipedia, datastore);
datastore = build(datastore);
const res = datastore.Wikipedia.getAllPosts();
res.then((x) => {
setTimeout(() => {
datastore.Wikipedia.getSingle({id: 1}).then((x) => console.log(x));
}, 1000);
});
}
run();
| import * as Github from './api/github';
import * as Wikipedia from './api/wikipedia';
import { createDatastore, registerApi, registerMiddleware, build } from 'datastore';
import * as Caching from 'caching';
function run() {
let datastore = createDatastore();
datastore = registerMiddleware('Caching', Caching, datastore);
datastore = registerApi('Github', Github, datastore);
datastore = registerApi('Wikipedia', Wikipedia, datastore);
datastore = build(datastore);
const res = datastore.Github.getRepos();
res.then((x) => {
setTimeout(() => {
datastore.Github.getRepos().then((x) => console.log(x));
}, 1000);
setTimeout(() => {
datastore.Github.getRepo({id: 1379780}).then((x) => console.log(x));
}, 500);
});
}
run();
|
Reset apollo store when logging out
fbshipit-source-id: 957b820 | import Analytics from '../api/Analytics';
import LocalStorage from '../storage/LocalStorage';
import ApolloClient from '../api/ApolloClient';
import Auth0Api from '../api/Auth0Api';
export default {
setSession(session) {
return async (dispatch) => {
await LocalStorage.saveSessionAsync(session);
return dispatch({
type: 'setSession',
payload: session,
});
};
},
signOut(options = {}) {
return async (dispatch) => {
const shouldResetApolloStore = options.shouldResetApolloStore || true;
const session = await LocalStorage.getSessionAsync();
if (session) {
await Auth0Api.signOutAsync(session.sessionSecret);
}
await LocalStorage.removeSessionAsync();
await LocalStorage.clearHistoryAsync();
Analytics.track(Analytics.events.USER_LOGGED_OUT);
Analytics.identify(null);
if (shouldResetApolloStore) {
ApolloClient.resetStore();
}
return dispatch({
type: 'signOut',
payload: null,
});
};
},
};
| import Analytics from '../api/Analytics';
import LocalStorage from '../storage/LocalStorage';
import ApolloClient from '../api/ApolloClient';
import Auth0Api from '../api/Auth0Api';
export default {
setSession(session) {
return async (dispatch) => {
await LocalStorage.saveSessionAsync(session);
return dispatch({
type: 'setSession',
payload: session,
});
};
},
signOut(options = {}) {
return async (dispatch) => {
const { shouldResetApolloStore } = options.shouldResetApolloStore || true;
const session = await LocalStorage.getSessionAsync();
if (session) {
await Auth0Api.signOutAsync(session.sessionSecret);
}
await LocalStorage.removeSessionAsync();
await LocalStorage.clearHistoryAsync();
Analytics.track(Analytics.events.USER_LOGGED_OUT);
Analytics.identify(null);
if (shouldResetApolloStore) {
ApolloClient.resetStore();
}
return dispatch({
type: 'signOut',
payload: null,
});
};
},
};
|
Make test_multi_keyframe demonstrate what it's supposed to
I was testing a cache that wasn't behaving correctly for
unrelated reasons. | import os
import shutil
import pytest
from LiSE.engine import Engine
from LiSE.examples.kobold import inittest
def test_keyframe_load_init(tempdir):
"""Can load a keyframe at start of branch, including locations"""
eng = Engine(tempdir)
inittest(eng)
eng.branch = 'new'
eng.snap_keyframe()
eng.close()
eng = Engine(tempdir)
assert 'kobold' in eng.character['physical'].thing
assert (0, 0) in eng.character['physical'].place
assert (0, 1) in eng.character['physical'].portal[0, 0]
eng.close()
def test_multi_keyframe(tempdir):
eng = Engine(tempdir)
inittest(eng)
eng.snap_keyframe()
tick0 = eng.tick
eng.turn = 1
del eng.character['physical'].place[3, 3]
eng.snap_keyframe()
tick1 = eng.tick
eng.close()
eng = Engine(tempdir)
eng._load_at('trunk', 0, tick0+1)
assert eng._nodes_cache.keyframe['physical', ]['trunk'][0][tick0]\
!= eng._nodes_cache.keyframe['physical', ]['trunk'][1][tick1]
| import os
import shutil
import pytest
from LiSE.engine import Engine
from LiSE.examples.kobold import inittest
def test_keyframe_load_init(tempdir):
"""Can load a keyframe at start of branch, including locations"""
eng = Engine(tempdir)
inittest(eng)
eng.branch = 'new'
eng.snap_keyframe()
eng.close()
eng = Engine(tempdir)
assert 'kobold' in eng.character['physical'].thing
assert (0, 0) in eng.character['physical'].place
assert (0, 1) in eng.character['physical'].portal[0, 0]
eng.close()
def test_multi_keyframe(tempdir):
eng = Engine(tempdir)
inittest(eng, kobold_pos=(9, 9))
eng.snap_keyframe()
tick0 = eng.tick
eng.turn = 1
eng.character['physical'].thing['kobold']['location'] = (3, 3)
eng.snap_keyframe()
tick1 = eng.tick
eng.close()
eng = Engine(tempdir)
eng._load_at('trunk', 0, tick0+1)
assert eng._things_cache.keyframe['physical']['trunk'][0][tick0]\
!= eng._things_cache.keyframe['physical']['trunk'][1][tick1]
|
Remove error from the struct, since its uneeded. | package main
import (
"fmt"
"strings"
)
type APRSPacket struct {
Callsign string
PacketType string
Latitude string
Longitude string
Altitude string
GPSTime string
RawData string
Symbol string
Heading string
PHG string
Speed string
Destination string
Status string
WindDirection string
WindSpeed string
WindGust string
WeatherTemp string
RainHour string
RainDay string
RainMidnight string
Humidity string
Pressure string
Luminosity string
Snowfall string
Raincounter string
}
func ParseAPRSPacket(input string) (p APRSPacket, e error) {
if input == "" {
e = fmt.Errorf("Could not parse the packet because the packet line is blank")
return p, e
}
if !strings.HasPrefix(input, ">") {
e = fmt.Errorf("This libary does not support this kind of packet.")
return p, e
}
return p, e
}
| package main
import (
"fmt"
"strings"
)
type APRSPacket struct {
Callsign string
PacketType string
Latitude string
Longitude string
Altitude string
GPSTime string
RawData string
Symbol string
Heading string
PHG string
Speed string
Destination string
Status string
WindDirection string
WindSpeed string
WindGust string
WeatherTemp string
RainHour string
RainDay string
RainMidnight string
Humidity string
Pressure string
Luminosity string
Snowfall string
Raincounter string
Error string
}
func ParseAPRSPacket(input string) (p APRSPacket, e error) {
if input == "" {
e = fmt.Errorf("Could not parse the packet because the packet line is blank")
return p, e
}
if !strings.HasPrefix(input, ">") {
e = fmt.Errorf("This libary does not support this kind of packet.")
return p, e
}
return p, e
}
|
Insert custom commands through the getCommands() function. | <?php
/**
* @version $Id$
* @category Nooku
* @package Nooku_Server
* @subpackage Users
* @copyright Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net).
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://www.nooku.org
*/
/**
* Users Toolbar Class
*
* @author Gergo Erdosi <http://nooku.assembla.com/profile/gergoerdosi>
* @category Nooku
* @package Nooku_Server
* @subpackage Users
*/
class ComUsersControllerToolbarUsers extends ComDefaultControllerToolbarDefault
{
public function getCommands()
{
$this->addSeperator()
->addEnable()
->addDisable();
return parent::getCommands();
}
} | <?php
/**
* @version $Id$
* @category Nooku
* @package Nooku_Server
* @subpackage Users
* @copyright Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net).
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://www.nooku.org
*/
/**
* Users Toolbar Class
*
* @author Gergo Erdosi <http://nooku.assembla.com/profile/gergoerdosi>
* @category Nooku
* @package Nooku_Server
* @subpackage Users
*/
class ComUsersControllerToolbarUsers extends ComDefaultControllerToolbarDefault
{
public function __construct(KConfig $config)
{
parent::__construct($config);
$this->addSeperator()
->addEnable()
->addDisable();
}
} |
Connect protractor directly with browsers | 'use strict';
var gulpConfig = require(__dirname + '/../gulpfile').config;
var sessionPage = require(__dirname + '/e2e/pages/session');
exports.config = {
allScriptsTimeout: 90000,
// Connect directly to chrome and firefox
// Solves issues with stalled Sellenium server
// https://github.com/angular/protractor/blob/master/docs/server-setup.md#connecting-directly-to-browser-drivers
directConnect: true,
specs: [
'e2e/**/*.js'
],
multiCapabilities: [{
'browserName': 'chrome',
'chromeOptions' : {
args: ['--lang=en',
'--window-size=1024,800']
},
}, {
'browserName': 'chrome',
'chromeOptions' : {
args: ['--lang=en',
'--window-size=350,650']
},
}],
baseUrl: 'http://' + gulpConfig.serverTest.host + ':' + gulpConfig.serverTest.port + '/',
framework: 'jasmine2',
jasmineNodeOpts: {
defaultTimeoutInterval: 2500000
},
suites: {
session: 'e2e/session.js'
},
onPrepare: function() {
var registerPage = new sessionPage.Register();
registerPage.get();
registerPage.register();
return browser.driver.executeScript('return window.innerWidth >= 992;').then((desktop) => {
global.isDesktop = desktop;
});
}
};
| 'use strict';
var gulpConfig = require(__dirname + '/../gulpfile').config;
var sessionPage = require(__dirname + '/e2e/pages/session');
exports.config = {
allScriptsTimeout: 90000,
specs: [
'e2e/**/*.js'
],
multiCapabilities: [{
'browserName': 'chrome',
'chromeOptions' : {
args: ['--lang=en',
'--window-size=1024,800']
},
}, {
'browserName': 'chrome',
'chromeOptions' : {
args: ['--lang=en',
'--window-size=350,650']
},
}],
baseUrl: 'http://' + gulpConfig.serverTest.host + ':' + gulpConfig.serverTest.port + '/',
framework: 'jasmine2',
jasmineNodeOpts: {
defaultTimeoutInterval: 2500000
},
suites: {
session: 'e2e/session.js'
},
onPrepare: function() {
var registerPage = new sessionPage.Register();
registerPage.get();
registerPage.register();
return browser.driver.executeScript('return window.innerWidth >= 992;').then((desktop) => {
global.isDesktop = desktop;
});
}
};
|
Remove ID from default GameObjects | package net.mueller_martin.turirun;
import java.util.HashMap;
import java.util.ArrayList;
import net.mueller_martin.turirun.gameobjects.GameObject;
/**
* Created by DM on 06.11.15.
*/
public class ObjectController {
private HashMap<Integer,GameObject> objs_map = new HashMap<Integer,GameObject>();
private ArrayList<GameObject> objs = new ArrayList<GameObject>();
public void addObject(GameObject obj) {
objs.add(obj);
}
public void addObject(int id, GameObject obj) {
obj.id = id;
objs_map.put(id, obj);
objs.add(obj);
}
public void removeObject(GameObject obj) {
objs_map.remove(obj.id);
objs.remove(obj);
}
public ArrayList<GameObject> getObjects() {
return objs;
}
public GameObject getObject(int id) {
return objs_map.get(id);
}
}
| package net.mueller_martin.turirun;
import java.util.HashMap;
import java.util.ArrayList;
import net.mueller_martin.turirun.gameobjects.GameObject;
/**
* Created by DM on 06.11.15.
*/
public class ObjectController {
private static int next_id = 0;
private HashMap<Integer,GameObject> objs_map = new HashMap<Integer,GameObject>();
private ArrayList<GameObject> objs = new ArrayList<GameObject>();
public void addObject(GameObject obj) {
this.next_id++;
int id = next_id;
obj.id = next_id;
objs_map.put(id, obj);
objs.add(obj);
}
public void removeObject(GameObject obj) {
objs_map.remove(obj.id);
objs.remove(obj);
}
public ArrayList<GameObject> getObjects() {
return objs;
}
public GameObject getObject(int id) {
return objs_map.get(id);
}
}
|
Use flush and fsync to ensure data is written to disk | """Main Module of PDF Splitter"""
import argparse
import os
from PyPDF2 import PdfFileWriter
from Util import all_pdf_files_in_directory, split_on_condition, concat_pdf_pages
parser = \
argparse.ArgumentParser(
description='Split all the pages of multiple PDF files in a directory by document number'
)
parser.add_argument(
'directory',
metavar='PATH',
type=str,
help='path to a directory'
)
def width_greater_than_height(page):
box = page.mediaBox
return box.getWidth() > box.getHeight()
if __name__ == '__main__':
args = parser.parse_args()
all_pdf_files = all_pdf_files_in_directory(args.directory)
opened_files = map(lambda path: open(path, 'rb'), all_pdf_files)
all_pages = concat_pdf_pages(opened_files)
for idx, pages in enumerate(split_on_condition(all_pages, predicate=width_greater_than_height), start=1):
pdf_writer = PdfFileWriter()
map(pdf_writer.addPage, pages)
output_filename = '{0:05}.pdf'.format(idx)
with open(output_filename, 'wb') as output_file:
pdf_writer.write(output_file)
output_file.flush()
os.fsync(output_file.fileno())
map(lambda f: f.close, opened_files)
| """Main Module of PDF Splitter"""
import argparse
from PyPDF2 import PdfFileWriter
from Util import all_pdf_files_in_directory, split_on_condition, concat_pdf_pages
parser = \
argparse.ArgumentParser(
description='Split all the pages of multiple PDF files in a directory by document number'
)
parser.add_argument(
'directory',
metavar='PATH',
type=str,
help='path to a directory'
)
def width_greater_than_height(page):
box = page.mediaBox
return box.getWidth() > box.getHeight()
if __name__ == '__main__':
args = parser.parse_args()
all_pdf_files = all_pdf_files_in_directory(args.directory)
opened_files = map(lambda path: open(path, 'rb'), all_pdf_files)
all_pages = concat_pdf_pages(opened_files)
for idx, pages in enumerate(split_on_condition(all_pages, predicate=width_greater_than_height), start=1):
pdf_writer = PdfFileWriter()
map(pdf_writer.addPage, pages)
output_filename = '{0:05}.pdf'.format(idx)
with open(output_filename, 'wb') as output_file:
pdf_writer.write(output_file)
map(lambda f: f.close, opened_files)
|
Add comments to Path Bounds tests. | module('Path Bounds');
test('path.bounds', function() {
var doc = new Doc();
var path = new Path([
new Segment(new Point(121, 334), new Point(-19, 38), new Point(30.7666015625, -61.53369140625)),
new Segment(new Point(248, 320), new Point(-42, -74), new Point(42, 74)),
new Segment(new Point(205, 420.94482421875), new Point(66.7890625, -12.72802734375), new Point(-79, 15.05517578125))
]);
// Test both closed and open paths, as the bounds for them differ
path.closed = false;
var bounds = path.bounds;
compareRectangles(bounds, { x: 121, y: 275.06796, width: 149.49304, height: 145.87686 });
// Test both closed and open paths, as the bounds for them differ
path.closed = true;
var bounds = path.bounds;
compareRectangles(bounds, { x: 114.82726, y: 275.06796, width: 155.66579, height: 148.12778 });
});
| module('Path Bounds');
test('path.bounds', function() {
var doc = new Doc();
var path = new Path([
new Segment(new Point(121, 334), new Point(-19, 38), new Point(30.7666015625, -61.53369140625)),
new Segment(new Point(248, 320), new Point(-42, -74), new Point(42, 74)),
new Segment(new Point(205, 420.94482421875), new Point(66.7890625, -12.72802734375), new Point(-79, 15.05517578125))
]);
path.closed = false;
var bounds = path.bounds;
compareRectangles(bounds, { x: 121, y: 275.06796, width: 149.49304, height: 145.87686 });
path.closed = true;
var bounds = path.bounds;
compareRectangles(bounds, { x: 114.82726, y: 275.06796, width: 155.66579, height: 148.12778 });
});
|
devlogin: Fix handling of fragments in the URL.
When a fragment (i.e. section starting with `#`) is present in the URL
when landing the development login page, dev-login.js used to append
it to the appends it to the `formaction` attribute of all the input
tag present in the `dev_login.html`.
This made sense before 139cb8026f7310e1cca53fbed5609f8d7e85dc37, which
adjusted the structure of how `next` was passed.
To fix this, we adjust the JavaScript login to set the `next` hidden
input instead.
fixes #16215 | "use strict";
$(() => {
// This code will be executed when the user visits /login and
// dev_login.html is rendered.
if ($("[data-page-id='dev-login']").length > 0) {
if (window.location.hash.substring(0, 1) === "#") {
/* We append the location.hash to the input field with name next so that URL can be
preserved after user is logged in. See this:
https://stackoverflow.com/questions/5283395/url-hash-is-persisting-between-redirects */
$("input[name='next']").each(function () {
const new_value = $(this).attr("value") + window.location.hash;
$(this).attr("value", new_value);
});
}
}
});
| "use strict";
$(() => {
// This code will be executed when the user visits /login and
// dev_login.html is rendered.
if ($("[data-page-id='dev-login']").length > 0) {
if (window.location.hash.substring(0, 1) === "#") {
/* We append the location.hash to the formaction so that URL can be
preserved after user is logged in. See this:
https://stackoverflow.com/questions/5283395/url-hash-is-persisting-between-redirects */
$("input[name='direct_email']").each(function () {
const new_formaction = $(this).attr("formaction") + "/" + window.location.hash;
$(this).attr("formaction", new_formaction);
});
}
}
});
|
Fix for checkboxes and descriptions | (function($){
$.entwine('ss', function($){
$('.field label.right, .field.span.description').entwine({
onadd:function() {
this.hide();
var field = this.closest('.field');
if (!field.hasClass('checkbox')) field.addClass('help-text');
}
});
$('.field.help-text label.left').entwine({
onmouseenter:function() {
var field = this.closest('.field'),
helpText = field.find('label.right').length ? field.find('label.right') : field.find('span.description'),
pop = $('<div class="help-pop"><div class="arrow"></div>' + helpText.html() + '</div>'),
pos = this.offset();
this.append(pop);
},
onmouseleave:function() {
var field = this.closest('.field');
field.find('.help-pop').remove();
}
});
});
})(jQuery); | (function($){
$.entwine('ss', function($){
$('.field label.right').entwine({
onadd:function() {
this.hide();
this.closest('.field').addClass('help-text');
}
});
$('.field.help-text label.left').entwine({
onmouseenter:function() {
var field = this.closest('.field'),
helpText = field.find('label.right'),
pop = $('<div class="help-pop"><div class="arrow"></div>' + helpText.html() + '</div>'),
pos = this.offset();
this.append(pop);
},
onmouseleave:function() {
var field = this.closest('.field');
field.find('.help-pop').remove();
}
});
});
})(jQuery); |
Use of peg interface in server | package com.adrienbrault.jastermind.server;
import com.adrienbrault.jastermind.model.CodePeg;
import com.adrienbrault.jastermind.model.Peg;
import java.net.Socket;
import java.util.Random;
/**
* Created by IntelliJ IDEA.
*
* @Author: adrienbrault
* @Date: 04/06/11 12:26
*/
public class CodeMakerService implements Runnable {
protected Socket socket;
protected CodePeg[] secretCode = new CodePeg[Peg.LINE_SIZE];
public CodeMakerService(Socket socket) {
this.socket = socket;
this.generateSecretCode();
}
protected void generateSecretCode() {
Random randomGenerator = new Random();
for (int i=0; i< Peg.LINE_SIZE; i++) {
int randomPegIndex = randomGenerator.nextInt(CodePeg.values().length);
this.secretCode[i] = CodePeg.values()[randomPegIndex];
}
}
@Override
public String toString() {
return super.toString() + " " + this.secretCode;
}
public void run() {
System.out.println(this);
}
}
| package com.adrienbrault.jastermind.server;
import com.adrienbrault.jastermind.model.CodePeg;
import java.net.Socket;
import java.util.Random;
/**
* Created by IntelliJ IDEA.
*
* @Author: adrienbrault
* @Date: 04/06/11 12:26
*/
public class CodeMakerService implements Runnable {
final static int CODE_SIZE = 4;
protected Socket socket;
protected CodePeg[] secretCode = new CodePeg[CODE_SIZE];
public CodeMakerService(Socket socket) {
this.socket = socket;
this.generateSecretCode();
}
protected void generateSecretCode() {
Random randomGenerator = new Random();
for (int i=0; i< CODE_SIZE; i++) {
int randomPegIndex = randomGenerator.nextInt(CodePeg.values().length);
this.secretCode[i] = CodePeg.values()[randomPegIndex];
}
}
@Override
public String toString() {
return super.toString() + " " + this.secretCode;
}
public void run() {
System.out.println(this);
}
}
|
Switch to Orion90's fork of the go portaudio wrapper, for fixes to run with go 1.6 | package main
import (
"github.com/Orion90/portaudio"
)
const playBufferSize = 8192
func playTune(tune []int32, sampleRate float64) error {
err := portaudio.Initialize()
if err != nil {
return err
}
defer portaudio.Terminate()
buffer := make([]int32, playBufferSize)
stream, err := portaudio.OpenDefaultStream(0, 1, sampleRate, len(buffer), &buffer)
if err != nil {
return err
}
defer stream.Close()
err = stream.Start()
if err != nil {
return err
}
defer stream.Stop()
for i := 0; i < len(tune); i += len(buffer) {
end := i + playBufferSize
if end > len(tune) {
copy(buffer, tune[i:])
} else {
copy(buffer, tune[i:end])
}
err = stream.Write()
if err != nil {
return err
}
}
return nil
}
| package main
import (
"github.com/gordonklaus/portaudio"
)
const playBufferSize = 8192
func playTune(tune []int32, sampleRate float64) error {
err := portaudio.Initialize()
if err != nil {
return err
}
defer portaudio.Terminate()
buffer := make([]int32, playBufferSize)
stream, err := portaudio.OpenDefaultStream(0, 1, sampleRate, len(buffer), &buffer)
if err != nil {
return err
}
defer stream.Close()
err = stream.Start()
if err != nil {
return err
}
defer stream.Stop()
for i := 0; i < len(tune); i += len(buffer) {
end := i + playBufferSize
if end > len(tune) {
copy(buffer, tune[i:])
} else {
copy(buffer, tune[i:end])
}
err = stream.Write()
if err != nil {
return err
}
}
return nil
}
|
Add the new modid field in the common construct bus register | package info.u_team.u_team_test.init;
import info.u_team.u_team_core.api.construct.*;
import info.u_team.u_team_core.util.registry.BusRegister;
import info.u_team.u_team_test.TestMod;
@Construct(modid = TestMod.MODID)
public class TestCommonBusRegister implements IModConstruct {
@Override
public void construct() {
BusRegister.registerMod(TestBiomes::registerMod);
BusRegister.registerMod(TestBlocks::registerMod);
BusRegister.registerMod(TestContainers::registerMod);
BusRegister.registerMod(TestEffects::registerMod);
BusRegister.registerMod(TestEnchantments::registerMod);
BusRegister.registerMod(TestEntityTypes::registerMod);
BusRegister.registerMod(TestGlobalLootModifiers::registerMod);
BusRegister.registerMod(TestItems::registerMod);
BusRegister.registerMod(TestModDimensions::registerMod);
BusRegister.registerMod(TestPotions::registerMod);
BusRegister.registerMod(TestSounds::registerMod);
BusRegister.registerMod(TestTileEntityTypes::registerMod);
}
}
| package info.u_team.u_team_test.init;
import info.u_team.u_team_core.api.construct.*;
import info.u_team.u_team_core.util.registry.BusRegister;
@Construct
public class TestCommonBusRegister implements IModConstruct {
@Override
public void construct() {
BusRegister.registerMod(TestBiomes::registerMod);
BusRegister.registerMod(TestBlocks::registerMod);
BusRegister.registerMod(TestContainers::registerMod);
BusRegister.registerMod(TestEffects::registerMod);
BusRegister.registerMod(TestEnchantments::registerMod);
BusRegister.registerMod(TestEntityTypes::registerMod);
BusRegister.registerMod(TestGlobalLootModifiers::registerMod);
BusRegister.registerMod(TestItems::registerMod);
BusRegister.registerMod(TestModDimensions::registerMod);
BusRegister.registerMod(TestPotions::registerMod);
BusRegister.registerMod(TestSounds::registerMod);
BusRegister.registerMod(TestTileEntityTypes::registerMod);
}
}
|
Add comment explaining why it is unnecessary to patch .catch | 'use strict';
function PromiseWrap() {}
module.exports = function patchPromise() {
const hooks = this._hooks;
const state = this._state;
const Promise = global.Promise;
/* As per ECMAScript 2015, .catch must be implemented by calling .then, as
* such we need needn't patch .catch as well. see:
* http://www.ecma-international.org/ecma-262/6.0/#sec-promise.prototype.catch
*/
const oldThen = Promise.prototype.then;
Promise.prototype.then = wrappedThen;
function makeWrappedHandler(fn, handle, uid) {
if ('function' !== typeof fn) return fn;
return function wrappedHandler() {
hooks.pre.call(handle);
try {
return fn.apply(this, arguments);
} finally {
hooks.post.call(handle);
hooks.destroy.call(null, uid);
}
};
}
function wrappedThen(onFulfilled, onRejected) {
if (!state.enabled) return oldThen.call(this, onFulfilled, onRejected);
const handle = new PromiseWrap();
const uid = --state.counter;
hooks.init.call(handle, 0, uid, null);
return oldThen.call(
this,
makeWrappedHandler(onFulfilled, handle, uid),
makeWrappedHandler(onRejected, handle, uid)
);
}
};
| 'use strict';
function PromiseWrap() {}
module.exports = function patchPromise() {
const hooks = this._hooks;
const state = this._state;
const Promise = global.Promise;
const oldThen = Promise.prototype.then;
Promise.prototype.then = wrappedThen;
function makeWrappedHandler(fn, handle, uid) {
if ('function' !== typeof fn) return fn;
return function wrappedHandler() {
hooks.pre.call(handle);
try {
return fn.apply(this, arguments);
} finally {
hooks.post.call(handle);
hooks.destroy.call(null, uid);
}
};
}
function wrappedThen(onFulfilled, onRejected) {
if (!state.enabled) return oldThen.call(this, onFulfilled, onRejected);
const handle = new PromiseWrap();
const uid = --state.counter;
hooks.init.call(handle, 0, uid, null);
return oldThen.call(
this,
makeWrappedHandler(onFulfilled, handle, uid),
makeWrappedHandler(onRejected, handle, uid)
);
}
};
|
Use stable dev/platforms for CI | # Copyright (c) 2014-present PlatformIO <[email protected]>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import subprocess
import sys
from platformio import util
def main():
platforms = json.loads(
subprocess.check_output(
["platformio", "platform", "search", "--json-output"]).decode())
for platform in platforms:
if platform['forDesktop']:
continue
# RISC-V GAP does not support Windows 86
if (util.get_systype() == "windows_x86"
and platform['name'] == "riscv_gap"):
continue
# unknown issue on Linux
if ("linux" in util.get_systype()
and platform['name'] == "aceinna_imu"):
continue
subprocess.check_call(
["platformio", "platform", "install", platform['name']])
if __name__ == "__main__":
sys.exit(main())
| # Copyright (c) 2014-present PlatformIO <[email protected]>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import subprocess
import sys
from platformio import util
def main():
platforms = json.loads(
subprocess.check_output(
["platformio", "platform", "search", "--json-output"]).decode())
for platform in platforms:
if platform['forDesktop']:
continue
# RISC-V GAP does not support Windows 86
if (util.get_systype() == "windows_x86"
and platform['name'] == "riscv_gap"):
continue
# unknown issue on Linux
if ("linux" in util.get_systype()
and platform['name'] == "aceinna_imu"):
continue
subprocess.check_call(
["platformio", "platform", "install", platform['repository']])
if __name__ == "__main__":
sys.exit(main())
|
Make it clear where we are getting LazySettings from | # coding: utf-8
import os
import pytest
from dynaconf.base import LazySettings
@pytest.fixture(scope='module')
def settings():
"""Settings fixture with some defaults"""
mode = 'TRAVIS' if os.environ.get('TRAVIS') else 'TEST'
os.environ['DYNA%s_HOSTNAME' % mode] = 'host.com'
os.environ['DYNA%s_PORT' % mode] = '@int 5000'
os.environ['DYNA%s_VALUE' % mode] = '@float 42.1'
os.environ['DYNA%s_ALIST' % mode] = '@json ["item1", "item2", "item3"]'
os.environ['DYNA%s_ADICT' % mode] = '@json {"key": "value"}'
os.environ['DYNA%s_DEBUG' % mode] = '@bool true'
os.environ['DYNA%s_TODELETE' % mode] = '@bool true'
os.environ['PROJECT1_HOSTNAME'] = 'otherhost.com'
sets = LazySettings(
LOADERS_FOR_DYNACONF=[
'dynaconf.loaders.env_loader',
'dynaconf.loaders.redis_loader'
],
DYNACONF_NAMESPACE="DYNA%s" % mode
)
sets.SIMPLE_BOOL = False
sets.configure()
return sets
| # coding: utf-8
import os
import pytest
from dynaconf import LazySettings
@pytest.fixture(scope='module')
def settings():
"""Settings fixture with some defaults"""
mode = 'TRAVIS' if os.environ.get('TRAVIS') else 'TEST'
os.environ['DYNA%s_HOSTNAME' % mode] = 'host.com'
os.environ['DYNA%s_PORT' % mode] = '@int 5000'
os.environ['DYNA%s_VALUE' % mode] = '@float 42.1'
os.environ['DYNA%s_ALIST' % mode] = '@json ["item1", "item2", "item3"]'
os.environ['DYNA%s_ADICT' % mode] = '@json {"key": "value"}'
os.environ['DYNA%s_DEBUG' % mode] = '@bool true'
os.environ['DYNA%s_TODELETE' % mode] = '@bool true'
os.environ['PROJECT1_HOSTNAME'] = 'otherhost.com'
sets = LazySettings(
LOADERS_FOR_DYNACONF=[
'dynaconf.loaders.env_loader',
'dynaconf.loaders.redis_loader'
],
DYNACONF_NAMESPACE="DYNA%s" % mode
)
sets.SIMPLE_BOOL = False
sets.configure()
return sets
|
Add session utility functions.
Re-implement power resource so it loads devices instead of systems | package com.intuso.housemate.client.v1_0.rest;
import com.intuso.housemate.client.v1_0.api.object.Device;
import com.intuso.housemate.client.v1_0.rest.model.Page;
import javax.ws.rs.*;
/**
* Created by tomc on 21/01/17.
*/
@Path("/power")
public interface PowerResource {
@GET
@Produces("application/json")
Page<Device.Data> list(@QueryParam("offset") @DefaultValue("0") int offset, @QueryParam("limit") @DefaultValue("20") int limit);
@GET
@Path("/{id}")
boolean isOn(@PathParam("id") String id);
@POST
@Path("/{id}/on")
void turnOn(@PathParam("id") String id);
@POST
@Path("/{id}/off")
void turnOff(@PathParam("id") String id);
}
| package com.intuso.housemate.client.v1_0.rest;
import com.intuso.housemate.client.v1_0.api.object.System;
import com.intuso.housemate.client.v1_0.rest.model.Page;
import javax.ws.rs.*;
/**
* Created by tomc on 21/01/17.
*/
@Path("/power")
public interface PowerResource {
@GET
@Produces("application/json")
Page<System.Data> list(@QueryParam("offset") @DefaultValue("0") int offset, @QueryParam("limit") @DefaultValue("20") int limit);
@GET
@Path("/{id}")
boolean isOn(@PathParam("id") String id);
@POST
@Path("/{id}/on")
void turnOn(@PathParam("id") String id);
@POST
@Path("/{id}/off")
void turnOff(@PathParam("id") String id);
}
|
Fix error in db config | <?php
require_once __DIR__.'/../vendor/autoload.php';
Kohana::modules(array(
'database' => MODPATH.'database',
'auth' => MODPATH.'auth',
'cache' => MODPATH.'cache',
'functest' => __DIR__.'/..',
'test' => __DIR__.'/../tests/testmodule',
));
Kohana::$config
->load('database')
->set(Kohana::TESTING, array(
'type' => 'PDO',
'connection' => array(
'dsn' => 'mysql:host=localhost;dbname=test-functest',
'username' => 'root',
'password' => '',
'persistent' => TRUE,
),
'table_prefix' => '',
'charset' => 'utf8',
'caching' => FALSE,
))
->set('pdo_test', array(
'type' => 'PDO',
'connection' => array(
'dsn' => 'mysql:host=localhost;dbname=test-functest',
'username' => 'root',
'password' => '',
'persistent' => TRUE,
),
'table_prefix' => '',
'charset' => 'utf8',
'caching' => FALSE,
));
| <?php
require_once __DIR__.'/../vendor/autoload.php';
Kohana::modules(array(
'database' => MODPATH.'database',
'auth' => MODPATH.'auth',
'cache' => MODPATH.'cache',
'functest' => __DIR__.'/..',
'test' => __DIR__.'/../tests/testmodule',
));
Kohana::$config
->load('database')
->set(Kohana::TESTING, array(
'type' => 'PDO',
'connection' => array(
'dsn' => 'mysql:host=localhost;db_name=test-functest',
'username' => 'root',
'password' => '',
'persistent' => TRUE,
),
'table_prefix' => '',
'charset' => 'utf8',
'caching' => FALSE,
))
->set('pdo_test', array(
'type' => 'PDO',
'connection' => array(
'dsn' => 'mysql:host=localhost;db_name=test-functest',
'username' => 'root',
'password' => '',
'persistent' => TRUE,
),
'table_prefix' => '',
'charset' => 'utf8',
'caching' => FALSE,
));
|
End of preview. Expand
in Dataset Viewer.
README.md exists but content is empty.
- Downloads last month
- 35