text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Add the ability to use the middleware decorator without arguments.
|
import functools
DEFAULT_HEADERS = frozenset(["origin", "x-requested-with", "content-type", "accept"])):
def wrap_cors(func=None, *, allow_origin='*', allow_headers=DEFAULT_HEADERS):
"""
A middleware that allow CORS calls, by adding the
headers Access-Control-Allow-Origin and Access-Control-Allow-Headers.
This middlware accepts two optional parameters `allow_origin` and
`allow_headers` for customization of the headers values. By default
will be `*` and a set of `[Origin, X-Requested-With, Content-Type, Accept]`
respectively.
"""
if func is None:
return functools.partial(wrap_cors,
allow_origin=allow_origin,
allow_headers=allow_headers)
_allow_headers = ", ".join(allow_headers)
@functools.wraps(func)
def wrapper(request, *args, **kwargs):
response = func(request, *args, **kwargs)
if not response.headers:
response.headers = {}
response.headers['Access-Control-Allow-Origin'] = allow_origin
response.headers['Access-Control-Allow-Headers'] = _allow_headers
return response
return wrapper
|
import functools
DEFAULT_HEADERS = frozenset(["origin", "x-requested-with", "content-type", "accept"])):
def wrap_cors(func=None, *, allow_origin='*', allow_headers=DEFAULT_HEADERS):
"""
A middleware that allow CORS calls, by adding the
headers Access-Control-Allow-Origin and Access-Control-Allow-Headers.
This middlware accepts two optional parameters `allow_origin` and
`allow_headers` for customization of the headers values. By default
will be `*` and a set of `[Origin, X-Requested-With, Content-Type, Accept]`
respectively.
"""
_allow_headers = ", ".join(allow_headers)
@functools.wraps(func)
def wrapper(request, *args, **kwargs):
response = func(request, *args, **kwargs)
if not response.headers:
response.headers = {}
response.headers['Access-Control-Allow-Origin'] = allow_origin
response.headers['Access-Control-Allow-Headers'] = _allow_headers
return response
return wrapper
|
Add test case for “/“
|
from farmfs.fs import normpath as _normalize
from farmfs.fs import userPath2Path as up2p
from farmfs.fs import Path
def test_normalize_abs():
assert _normalize("/") == "/"
assert _normalize("/a") == "/a"
assert _normalize("/a/") == "/a"
assert _normalize("/a/b") == "/a/b"
assert _normalize("/a/b/") == "/a/b"
assert _normalize("/a//b") == "/a/b"
assert _normalize("/a//b//") == "/a/b"
def test_normalize_relative():
assert _normalize("a") == "a"
assert _normalize("a/") == "a"
assert _normalize("a/b") == "a/b"
assert _normalize("a/b/") == "a/b"
assert _normalize("a//b") == "a/b"
assert _normalize("a//b//") == "a/b"
def test_userPath2Path():
assert up2p("c", Path("/a/b")) == Path("/a/b/c")
assert up2p("/c", Path("/a/b")) == Path("/c")
def test_cmp():
assert Path("/a/b") < Path("/a/c")
assert Path("/a/c") > Path("/a/b")
assert Path("/a/2") < Path("/b/1")
assert Path("/") < Path("/a")
|
from farmfs.fs import normpath as _normalize
from farmfs.fs import userPath2Path as up2p
from farmfs.fs import Path
def test_normalize_abs():
assert _normalize("/") == "/"
assert _normalize("/a") == "/a"
assert _normalize("/a/") == "/a"
assert _normalize("/a/b") == "/a/b"
assert _normalize("/a/b/") == "/a/b"
assert _normalize("/a//b") == "/a/b"
assert _normalize("/a//b//") == "/a/b"
def test_normalize_relative():
assert _normalize("a") == "a"
assert _normalize("a/") == "a"
assert _normalize("a/b") == "a/b"
assert _normalize("a/b/") == "a/b"
assert _normalize("a//b") == "a/b"
assert _normalize("a//b//") == "a/b"
def test_userPath2Path():
assert up2p("c", Path("/a/b")) == Path("/a/b/c")
assert up2p("/c", Path("/a/b")) == Path("/c")
def test_cmp():
assert Path("/a/b") < Path("/a/c")
assert Path("/a/c") > Path("/a/b")
assert Path("/a/2") < Path("/b/1")
|
Add a Provider/registry to test render method.
|
/**
* External dependencies
*/
import { render } from '@testing-library/react';
import PropTypes from 'prop-types';
/**
* WordPress dependencies
*/
import { RegistryProvider } from '@wordpress/data';
/**
* Internal dependencies
*/
import { createTestRegistry } from 'tests/js/utils';
// Override `@testing-library/react`'s render method with one that includes
// our data store.
const customRender = ( children, options = {} ) => {
const {
registry = createTestRegistry(),
...renderOptions
} = options;
return {
...render( (
<RegistryProvider value={ registry }>
{ children }
</RegistryProvider>
), renderOptions ),
registry,
};
};
// Export our own test utils from this file.
export * from 'tests/js/utils';
// Export @testing-library/react as normal.
export * from '@testing-library/react';
// Override @testing-library/react's render method with our own.
export { customRender as render };
|
/**
* External dependencies
*/
import { render } from '@testing-library/react';
import PropTypes from 'prop-types';
/**
* WordPress dependencies
*/
import { Fragment } from '@wordpress/element';
const TestProviders = ( { children } ) => {
return (
<Fragment>
{ children }
</Fragment>
);
};
TestProviders.defaultProps = {
children: undefined,
};
TestProviders.propTypes = {
children: PropTypes.node,
};
// custom render with the test provider component
const customRender = ( ui, options ) => {
return render( ui, { wrapper: TestProviders, ...options } );
};
// Export our own test utils from this file.
export * from 'tests/js/utils';
// Export @testing-library/react as normal.
export * from '@testing-library/react';
// Override @testing-library/react's render method with our own.
export { customRender as render };
|
Remove potential duplicate registration code
Was sometimes causing an error when importing the project
|
bl_info = {
'name': "Import: .EDM model files",
'description': "Importing of .EDM model files",
'author': "Nicholas Devenish",
'version': (0,0,1),
'blender': (2, 78, 0),
'location': "File > Import/Export > .EDM Files",
'category': 'Import-Export',
}
try:
import bpy
def register():
from .io_operators import register as importer_register
from .rna import register as rna_register
from .panels import register as panels_register
rna_register()
panels_register()
importer_register()
def unregister():
from .io_operators import unregister as importer_unregister
from .rna import unregister as rna_unregister
from .panels import unregister as panels_unregister
importer_unregister()
panels_unregister()
rna_unregister()
if __name__ == "__main__":
register()
except ImportError:
# Allow for now, as we might just want to import the sub-package
pass
|
bl_info = {
'name': "Import: .EDM model files",
'description': "Importing of .EDM model files",
'author': "Nicholas Devenish",
'version': (0,0,1),
'blender': (2, 78, 0),
'location': "File > Import/Export > .EDM Files",
'category': 'Import-Export',
}
try:
import bpy
def register():
from .io_operators import register as importer_register
from .rna import register as rna_register
from .panels import register as panels_register
rna_register()
panels_register()
importer_register()
bpy.utils.register_module(__name__)
def unregister():
from .io_operators import unregister as importer_unregister
from .rna import unregister as rna_unregister
from .panels import unregister as panels_unregister
importer_unregister()
panels_unregister()
rna_unregister()
bpy.utils.unregister_module(__name__)
if __name__ == "__main__":
register()
except ImportError:
# Allow for now, as we might just want to import the sub-package
pass
|
Add videos dict to Games.
|
from datetime import datetime
GAME_VIDEO_BASE_URL = "http://www.nfl.com/feeds-rs/videos/byGameCenter/{0}.json"
LIVE_UPDATE_BASE_URL = "http://www.nfl.com/liveupdate/game-center/{0}/{0}_gtd.json"
class Game(object):
def __init__(self, id_, h, v):
self.id_ = id_
self.date = self.id_[:-2]
self.home = h
self.vis = v
self.latest_play_id = ""
self.latest_clip_id = ""
self.videos = {}
def is_today(self):
return self.date == str((datetime.today()).strftime('%Y%m%d'))
def video_url(self):
return GAME_VIDEO_BASE_URL.format(self.id_)
def live_update_url(self):
return LIVE_UPDATE_BASE_URL.format(self.id_)
|
from datetime import datetime
GAME_VIDEO_BASE_URL = "http://www.nfl.com/feeds-rs/videos/byGameCenter/{0}.json"
LIVE_UPDATE_BASE_URL = "http://www.nfl.com/liveupdate/game-center/{0}/{0}_gtd.json"
class Game(object):
def __init__(self, id_, h, v):
self.id_ = id_
self.date = self.id_[:-2]
self.home = h
self.vis = v
self.latest_play_id = ""
self.latest_clip_id = ""
def is_today(self):
return self.date == str((datetime.today()).strftime('%Y%m%d'))
def video_url(self):
return GAME_VIDEO_BASE_URL.format(self.id_)
def live_update_url(self):
return LIVE_UPDATE_BASE_URL.format(self.id_)
|
Allow adding a select-where to symfony child-rows-serializer
|
<?php
namespace KwfBundle\Serializer\KwfModel\ColumnNormalizer;
use Kwf_Model_Row_Interface;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Serializer\SerializerAwareInterface;
class ChildRows implements ColumnNormalizerInterface, SerializerAwareInterface
{
/**
* @var SerializerInterface
*/
protected $serializer;
/**
* {@inheritdoc}
*/
public function setSerializer(SerializerInterface $serializer)
{
$this->serializer = $serializer;
}
public function normalize(Kwf_Model_Row_Interface $row, $column, array $settings, $format = null, array $context = array())
{
if (!isset($settings['rule'])) {
throw new \Exception("rule setting is required");
}
$select = new \Kwf_Model_Select(isset($settings['where']) ? $settings['where'] : array());
$rows = $row->getChildRows($settings['rule'], $select);
if (isset($settings['child_groups'])) {
$context['groups'] = $settings['child_groups'];
} else if (isset($settings['groups'])) {
$context['groups'] = $settings['groups'];
}
return $this->serializer->normalize($rows, $format, $context);
}
}
|
<?php
namespace KwfBundle\Serializer\KwfModel\ColumnNormalizer;
use Kwf_Model_Row_Interface;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Serializer\SerializerAwareInterface;
class ChildRows implements ColumnNormalizerInterface, SerializerAwareInterface
{
/**
* @var SerializerInterface
*/
protected $serializer;
/**
* {@inheritdoc}
*/
public function setSerializer(SerializerInterface $serializer)
{
$this->serializer = $serializer;
}
public function normalize(Kwf_Model_Row_Interface $row, $column, array $settings, $format = null, array $context = array())
{
if (!isset($settings['rule'])) {
throw new \Exception("rule setting is required");
}
$rows = $row->getChildRows($settings['rule']);
if (isset($settings['child_groups'])) {
$context['groups'] = $settings['child_groups'];
} else if (isset($settings['groups'])) {
$context['groups'] = $settings['groups'];
}
return $this->serializer->normalize($rows, $format, $context);
}
}
|
Allow nested directory creation with recursive switch addition
|
<?php
namespace App\Http\Controllers;
trait Writer
{
public function writeHtmlToDisk($content, $directory) {
$date = date('YmdHis');
$this->prepareDirectory($directory);
$directory = $directory . '/' . $date . '.html';
// try {
$file = fopen($directory, 'w');
fwrite($file, $content);
fclose($file);
// } catch (\Exception $e) {
// throw new \Symfony\Component\HttpKernel\Exception\HttpException('Write HTML failed');
// }
return true;
}
public function prepareDirectory($directory) {
try {
if(!is_dir($directory)) {
mkdir($directory, 0777, true);
}
}
catch(\Exception $e) {
throw new \Symfony\Component\HttpKernel\Exception\HttpException('Directory preparation failed!');
}
return true;
}
}
|
<?php
namespace App\Http\Controllers;
trait Writer
{
public function writeHtmlToDisk($content, $directory) {
$date = date('YmdHis');
$this->prepareDirectory($directory);
$directory = $directory . '/' . $date . '.html';
// try {
$file = fopen($directory, 'w');
fwrite($file, $content);
fclose($file);
// } catch (\Exception $e) {
// throw new \Symfony\Component\HttpKernel\Exception\HttpException('Write HTML failed');
// }
return true;
}
public function prepareDirectory($directory) {
try {
if(!is_dir($directory)) {
mkdir($directory);
}
}
catch(\Exception $e) {
throw new \Symfony\Component\HttpKernel\Exception\HttpException('Directory preparation failed!');
}
return true;
}
}
|
Fix tests broken by new log configuration option
|
from __future__ import absolute_import, division, print_function
import pytest
from screen19.screen import Screen19
def test_screen19_command_line_help_does_not_crash():
Screen19().run([])
def test_screen19(dials_data, tmpdir):
data_dir = dials_data("x4wide").strpath
with tmpdir.as_cwd():
Screen19().run([data_dir], set_up_logging=True)
logfile = tmpdir.join("screen19.log").read()
assert "screen19 successfully completed" in logfile
assert "photon incidence rate is outside the linear response region" in logfile
@pytest.mark.xfail(raises=ValueError, reason="LAPACK bug?")
def test_screen19_single_frame(dials_data, tmpdir):
# TODO Use a single frame with fewer than 80 reflections
image = dials_data("x4wide").join("X4_wide_M1S4_2_0001.cbf").strpath
with tmpdir.as_cwd():
Screen19().run([image], set_up_logging=True)
logfile = tmpdir.join("screen19.log").read()
assert "screen19 successfully completed" in logfile
|
from __future__ import absolute_import, division, print_function
import pytest
from screen19.screen import Screen19
def test_screen19_command_line_help_does_not_crash():
Screen19().run([])
def test_screen19(dials_data, tmpdir):
data_dir = dials_data("x4wide").strpath
with tmpdir.as_cwd():
Screen19().run([data_dir])
logfile = tmpdir.join("screen19.log").read()
assert "screen19 successfully completed" in logfile
assert "photon incidence rate is outside the linear response region" in logfile
@pytest.mark.xfail(raises=ValueError, reason="LAPACK bug?")
def test_screen19_single_frame(dials_data, tmpdir):
# TODO Use a single frame with fewer than 80 reflections
image = dials_data("x4wide").join("X4_wide_M1S4_2_0001.cbf").strpath
with tmpdir.as_cwd():
Screen19().run([image])
logfile = tmpdir.join("screen19.log").read()
assert "screen19 successfully completed" in logfile
|
Switch to development of next version.
|
try:
from setuptools import setup
except ImportError:
from distutils import setup
readme = open('README.rst', 'r')
README_TEXT = readme.read()
readme.close()
setup(
name='aniso8601',
version='0.60dev',
description='A library for parsing ISO 8601 strings.',
long_description=README_TEXT,
author='Brandon Nielsen',
author_email='nielsenb@jetfuse.net',
url='https://bitbucket.org/nielsenb/aniso8601',
packages=['aniso8601'],
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
|
try:
from setuptools import setup
except ImportError:
from distutils import setup
readme = open('README.rst', 'r')
README_TEXT = readme.read()
readme.close()
setup(
name='aniso8601',
version='0.50',
description='A library for parsing ISO 8601 strings.',
long_description=README_TEXT,
author='Brandon Nielsen',
author_email='nielsenb@jetfuse.net',
url='https://bitbucket.org/nielsenb/aniso8601',
packages=['aniso8601'],
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
|
Remove `ready` callback from module definition
It is now up to the user to wait to call `register` until
`document,body` exists.
|
INTERCEPT = (function () {
var selectors = {},
observer,
register;
function register(spec) {
if(typeof observer === 'undefined') init();
var selector = spec.selector;
if (!spec.new_only) {
$(spec.selector).each(function(i, element) {
spec.callback(element);
});
}
selectors[selector] = spec;
}
function toArray(collection) {
return Array.prototype.slice.call(collection);
}
function init() {
observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
toArray(mutation.addedNodes).forEach(function(node) {
Object.keys(selectors).forEach(function(selector) {
var callback = selectors[selector].callback;
if ($(node).is(selector) && callback) {
callback(node);
}
});
});
});
});
observer.observe(document.body, { childList: true, subtree: true });
}
return Object.freeze({
register: register,
observer: observer
});
}());
|
$(document).ready(function () {
INTERCEPT = (function () {
var selectors = {},
observer,
register;
function register(spec) {
if(typeof observer === 'undefined') init();
var selector = spec.selector;
if (!spec.new_only) {
$(spec.selector).each(function(i, element) {
spec.callback(element);
});
}
selectors[selector] = spec;
}
function toArray(collection) {
return Array.prototype.slice.call(collection);
}
function init() {
observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
toArray(mutation.addedNodes).forEach(function(node) {
Object.keys(selectors).forEach(function(selector) {
var callback = selectors[selector].callback;
if ($(node).is(selector) && callback) {
callback(node);
}
});
});
});
});
observer.observe(document.body, { childList: true, subtree: true });
}
return Object.freeze({
register: register,
observer: observer
});
}());
});
|
Fix set function with underscore isEqual
|
ReactiveArray;
this.ReactiveArray = ReactiveArray = function(value) {
var ifc, method, _addWrappedPrototypeMethod, _array, _arrayDep, _i, _len, _methods;
if (!(this instanceof ReactiveArray)) {
return new ReactiveArray;
}
check(value, Match.Optional(Array));
ifc = {};
_addWrappedPrototypeMethod = function(method) {
return ifc[method] = function() {
_arrayDep.changed();
return Array.prototype[method].apply(_array, arguments);
};
};
_array = value || [];
_arrayDep = new Tracker.Dependency;
_methods = ['pop', 'push', 'reverse', 'shift', 'sort', 'slice', 'unshift', 'splice'];
for (_i = 0, _len = _methods.length; _i < _len; _i++) {
method = _methods[_i];
_addWrappedPrototypeMethod(method);
}
ifc.get = function() {
if (Tracker.active) {
_arrayDep.depend();
}
return _array;
};
ifc.set = function(array) {
check(array, Array);
if (!_.isEqual(array, _array)) {
_array = array;
_arrayDep.changed();
}
};
ifc.pushArray = function(array) {
check(array, Array);
if (!!array.length) {
_array = _array.concat(array);
_arrayDep.changed();
}
};
ifc.getNonReactive = function() {
return _array;
};
return ifc;
};
|
ReactiveArray;
this.ReactiveArray = ReactiveArray = function(value) {
var ifc, method, _addWrappedPrototypeMethod, _array, _arrayDep, _i, _len, _methods;
if (!(this instanceof ReactiveArray)) {
return new ReactiveArray;
}
check(value, Match.Optional(Array));
ifc = {};
_addWrappedPrototypeMethod = function(method) {
return ifc[method] = function() {
_arrayDep.changed();
return Array.prototype[method].apply(_array, arguments);
};
};
_array = value || [];
_arrayDep = new Tracker.Dependency;
_methods = ['pop', 'push', 'reverse', 'shift', 'sort', 'slice', 'unshift', 'splice'];
for (_i = 0, _len = _methods.length; _i < _len; _i++) {
method = _methods[_i];
_addWrappedPrototypeMethod(method);
}
ifc.get = function() {
if (Tracker.active) {
_arrayDep.depend();
}
return _array;
};
ifc.set = function(array) {
check(array, Array);
if (_.intersection(array, _array).length != array.length || !array.length ) {
_array = array;
_arrayDep.changed();
}
};
ifc.pushArray = function(array) {
check(array, Array);
if (!!array.length) {
_array = _array.concat(array);
_arrayDep.changed();
}
};
ifc.getNonReactive = function() {
return _array;
};
return ifc;
};
|
Make locks tables begin with _locks_, not just _locks
|
/**
* Copyright 2016 Palantir Technologies
*
* Licensed under the BSD-3 License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.palantir.atlasdb.keyvalue.cassandra;
import java.util.Set;
import com.google.common.collect.ImmutableSet;
import com.palantir.atlasdb.AtlasDbConstants;
import com.palantir.atlasdb.keyvalue.api.TableReference;
class HiddenTables {
private TableReference lockTable;
private final Set<TableReference> hiddenTables;
static final String LOCK_TABLE_PREFIX = "_locks_";
HiddenTables() {
this.hiddenTables = ImmutableSet.of(
AtlasDbConstants.TIMESTAMP_TABLE,
AtlasDbConstants.METADATA_TABLE);
}
boolean isHidden(TableReference tableReference) {
return hiddenTables.contains(tableReference) || (tableReference != null && tableReference.equals(lockTable));
}
TableReference getLockTable() {
return lockTable;
}
void setLockTable(TableReference lockTable) {
this.lockTable = lockTable;
}
}
|
/**
* Copyright 2016 Palantir Technologies
*
* Licensed under the BSD-3 License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.palantir.atlasdb.keyvalue.cassandra;
import java.util.Set;
import com.google.common.collect.ImmutableSet;
import com.palantir.atlasdb.AtlasDbConstants;
import com.palantir.atlasdb.keyvalue.api.TableReference;
class HiddenTables {
private TableReference lockTable;
private final Set<TableReference> hiddenTables;
static final String LOCK_TABLE_PREFIX = "_locks";
HiddenTables() {
this.hiddenTables = ImmutableSet.of(
AtlasDbConstants.TIMESTAMP_TABLE,
AtlasDbConstants.METADATA_TABLE);
}
boolean isHidden(TableReference tableReference) {
return hiddenTables.contains(tableReference) || (tableReference != null && tableReference.equals(lockTable));
}
TableReference getLockTable() {
return lockTable;
}
void setLockTable(TableReference lockTable) {
this.lockTable = lockTable;
}
}
|
refactor: Add service to retrieve list of team for a user
|
/**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* 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 io.gravitee.repository.api;
import io.gravitee.repository.model.Member;
import io.gravitee.repository.model.Team;
import io.gravitee.repository.model.TeamRole;
import java.util.Set;
/**
* @author David BRASSELY (brasseld at gmail.com)
*/
public interface TeamMembershipRepository {
void addMember(String teamName, String username, TeamRole role);
void updateMember(String teamName, String username, TeamRole role);
void deleteMember(String teamName, String username);
Set<Member> listMembers(String teamName);
/**
* List {@link Team} where the user is a member.
*
* @param username The name used to identify a user.
* @return List of {@link Team}
*/
Set<Team> findByUser(String username);
}
|
/**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* 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 io.gravitee.repository.api;
import io.gravitee.repository.model.Member;
import io.gravitee.repository.model.TeamRole;
import java.util.Set;
/**
* @author David BRASSELY (brasseld at gmail.com)
*/
public interface TeamMembershipRepository {
void addMember(String teamName, String username, TeamRole role);
void updateMember(String teamName, String username, TeamRole role);
void deleteMember(String teamName, String username);
Set<Member> listMembers(String teamName);
}
|
Fix concurrency issue with Python 3.4 test
We have been seeing failures in parallel Py34
tests caused by the test database being set up more
than once.
The existing mechanism is not thread-safe.
Add a lock around the database setup to ensure
the it is ever executed by only one thread.
Partially implements: blueprint trove-python3
Change-Id: I68aba50d60b912384080911a6f78283f027c4ee3
|
# Copyright 2012 OpenStack 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.
import threading
from trove.common import cfg
from trove.db import get_db_api
from trove.db.sqlalchemy import session
CONF = cfg.CONF
DB_SETUP = None
LOCK = threading.Lock()
def init_db():
with LOCK:
global DB_SETUP
if not DB_SETUP:
db_api = get_db_api()
db_api.db_sync(CONF)
session.configure_db(CONF)
DB_SETUP = True
|
# Copyright 2012 OpenStack 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.
DB_SETUP = None
def init_db():
global DB_SETUP
if DB_SETUP:
return
from trove.common import cfg
from trove.db import get_db_api
from trove.db.sqlalchemy import session
CONF = cfg.CONF
db_api = get_db_api()
db_api.db_sync(CONF)
session.configure_db(CONF)
DB_SETUP = True
|
Add main routine to lambda handler
|
#!/usr/bin/env python2
from StringIO import StringIO
import boto3
from dmr_marc_users_cs750 import (
get_users, get_groups,
write_contacts_csv,
write_contacts_xlsx
)
def lambda_handler(event=None, context=None):
users = get_users()
csvo = StringIO()
write_contacts_csv(users, csvo)
s3 = boto3.client('s3')
s3.put_object(
Bucket='dmr-contacts', Key='DMR_contacts.csv',
Body=csvo.getvalue(), ContentType='text/csv', ACL='public-read')
csvo.close()
groups = get_groups()
xlsxo = StringIO()
write_contacts_xlsx(groups + users, xlsxo)
s3.put_object(
Bucket='dmr-contacts', Key='contacts-dci.xlsx',
Body=xlsxo.getvalue(),
ContentType=('application/'
'vnd.openxmlformats-officedocument.spreadsheetml.sheet'),
ACL='public-read')
xlsxo.close()
if __name__ == '__main__':
lambda_handler()
|
#!/usr/bin/env python2
from StringIO import StringIO
import boto3
from dmr_marc_users_cs750 import (
get_users, get_groups,
write_contacts_csv,
write_contacts_xlsx
)
def lambda_handler(event=None, context=None):
users = get_users()
csvo = StringIO()
write_contacts_csv(users, csvo)
s3 = boto3.client('s3')
s3.put_object(
Bucket='dmr-contacts', Key='DMR_contacts.csv',
Body=csvo.getvalue(), ContentType='text/csv', ACL='public-read')
csvo.close()
groups = get_groups()
xlsxo = StringIO()
write_contacts_xlsx(groups + users, xlsxo)
s3.put_object(
Bucket='dmr-contacts', Key='contacts-dci.xlsx',
Body=xlsxo.getvalue(),
ContentType=('application/'
'vnd.openxmlformats-officedocument.spreadsheetml.sheet'),
ACL='public-read')
xlsxo.close()
|
Fix articles list; now show all
|
<?php
namespace Rudolf\Modules\Articles\Roll\Admin;
use Rudolf\Modules\A_admin\AdminController;
use Rudolf\Modules\Articles\Roll;
use Rudolf\Component\Libs\Pagination;
class Controller extends AdminController
{
public function getList($page)
{
$page = $this->firstPageRedirect($page, 301, $location = '../../list');
$list = new Roll\Model();
$pagination = new Pagination($list->getTotalNumber('1=1'), $page);
$results = $list->getList($pagination);
$view = new View();
$view->setData($results, $pagination);
$view->setActive(['admin/articles', 'admin/articles/list']);
$view->render('admin');
}
}
|
<?php
namespace Rudolf\Modules\Articles\Roll\Admin;
use Rudolf\Modules\A_admin\AdminController;
use Rudolf\Modules\Articles\Roll;
use Rudolf\Component\Libs\Pagination;
class Controller extends AdminController
{
public function getList($page)
{
$page = $this->firstPageRedirect($page, 301, $location = '../../list');
$list = new Roll\Model();
$pagination = new Pagination($list->getTotalNumber(), $page);
$results = $list->getList($pagination);
$view = new View();
$view->setData($results, $pagination);
$view->setActive(['admin/articles', 'admin/articles/list']);
$view->render('admin');
}
}
|
Add a module to the __all__ list.
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2016 Jérémie DECOCK (http://www.jdhp.org)
# This script is provided under the terms and conditions of the MIT license:
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
__all__ = ['abstract_cleaning_algorithm',
'fft',
'null',
'null_ref',
'tailcut',
'tailcut_jd',
'wavelets_mrfilter',
'wavelets_mrtransform',
'inverse_transform_sampling']
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2016 Jérémie DECOCK (http://www.jdhp.org)
# This script is provided under the terms and conditions of the MIT license:
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
__all__ = ['abstract_cleaning_algorithm',
'fft',
'null',
'null_ref',
'tailcut',
'tailcut_jd',
'wavelets_mrfilter',
'wavelets_mrtransform']
|
Increase BDB test ID timeout: 20 to 150 ms
20 ms is too tightly tuned for some test environments
|
package com.thinkaurelius.titan.blueprints;
import com.thinkaurelius.titan.BerkeleyStorageSetup;
import com.thinkaurelius.titan.StorageSetup;
import com.thinkaurelius.titan.diskstorage.berkeleyje.BerkeleyJETx;
import com.thinkaurelius.titan.diskstorage.configuration.ModifiableConfiguration;
import com.thinkaurelius.titan.graphdb.configuration.GraphDatabaseConfiguration;
import java.time.Duration;
import java.util.Set;
/**
* @author Matthias Broecheler (me@matthiasb.com)
*/
public class BerkeleyGraphProvider extends AbstractTitanGraphProvider {
@Override
public ModifiableConfiguration getTitanConfiguration(String graphName, Class<?> test, String testMethodName) {
return BerkeleyStorageSetup.getBerkeleyJEConfiguration(StorageSetup.getHomeDir(graphName)).set(GraphDatabaseConfiguration.IDAUTHORITY_WAIT, Duration.ofMillis(150L));
}
@Override
public Set<Class> getImplementations() {
final Set<Class> implementations = super.getImplementations();
implementations.add(BerkeleyJETx.class);
return implementations;
}
}
|
package com.thinkaurelius.titan.blueprints;
import com.thinkaurelius.titan.BerkeleyStorageSetup;
import com.thinkaurelius.titan.StorageSetup;
import com.thinkaurelius.titan.diskstorage.berkeleyje.BerkeleyJETx;
import com.thinkaurelius.titan.diskstorage.configuration.ModifiableConfiguration;
import com.thinkaurelius.titan.graphdb.configuration.GraphDatabaseConfiguration;
import java.time.Duration;
import java.util.Set;
/**
* @author Matthias Broecheler (me@matthiasb.com)
*/
public class BerkeleyGraphProvider extends AbstractTitanGraphProvider {
@Override
public ModifiableConfiguration getTitanConfiguration(String graphName, Class<?> test, String testMethodName) {
return BerkeleyStorageSetup.getBerkeleyJEConfiguration(StorageSetup.getHomeDir(graphName)).set(GraphDatabaseConfiguration.IDAUTHORITY_WAIT, Duration.ofMillis(20));
}
@Override
public Set<Class> getImplementations() {
final Set<Class> implementations = super.getImplementations();
implementations.add(BerkeleyJETx.class);
return implementations;
}
}
|
Use a blocking queue rather than a list so that tests can wait for a message to have arrived.
|
/**
* Copyright (C) 2009 - 2010 by OpenGamma Inc.
*
* Please see distribution for license.
*/
package com.opengamma.transport;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.fudgemsg.FudgeContext;
import org.fudgemsg.FudgeMsgEnvelope;
/**
* Collects all Fudge message envelopes in an array for later analysis.
*
* @author kirk
*/
public class CollectingFudgeMessageReceiver implements FudgeMessageReceiver {
private final BlockingQueue<FudgeMsgEnvelope> _messages = new LinkedBlockingQueue<FudgeMsgEnvelope>();
@Override
public void messageReceived(FudgeContext fudgeContext, FudgeMsgEnvelope msgEnvelope) {
_messages.add(msgEnvelope);
}
public List<FudgeMsgEnvelope> getMessages() {
return new LinkedList<FudgeMsgEnvelope>(_messages);
}
public void clear() {
_messages.clear();
}
public FudgeMsgEnvelope waitForMessage(final long timeoutMillis) {
try {
return _messages.poll(timeoutMillis, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
return null;
}
}
}
|
/**
* Copyright (C) 2009 - 2010 by OpenGamma Inc.
*
* Please see distribution for license.
*/
package com.opengamma.transport;
import java.util.LinkedList;
import java.util.List;
import org.fudgemsg.FudgeContext;
import org.fudgemsg.FudgeMsgEnvelope;
/**
* Collects all Fudge message envelopes in an array for later analysis.
*
* @author kirk
*/
public class CollectingFudgeMessageReceiver implements FudgeMessageReceiver {
private final List<FudgeMsgEnvelope> _messages = new LinkedList<FudgeMsgEnvelope>();
@Override
public synchronized void messageReceived(FudgeContext fudgeContext,
FudgeMsgEnvelope msgEnvelope) {
_messages.add(msgEnvelope);
}
public List<FudgeMsgEnvelope> getMessages() {
return _messages;
}
public synchronized void clear() {
_messages.clear();
}
}
|
Test isexecutable check in utils.Shell
|
import helper
from rock import utils
from rock.exceptions import ConfigError
class UtilsTestCase(helper.unittest.TestCase):
def test_shell(self):
utils.Shell.run = lambda self: self
s = utils.Shell()
self.assertTrue(isinstance(s.__enter__(), utils.Shell))
s.write('ok')
s.__exit__(None, None, None)
self.assertEqual(s.stdin.getvalue(), 'ok\n')
def execl(*args):
self.assertEqual(len(args), 4)
self.assertEqual(args[0], '/bin/bash')
self.assertEqual(args[1], '-l')
self.assertEqual(args[2], '-c')
self.assertEqual(args[3], 'ok\n')
utils.os.execl = execl
s.__exit__('type', 'value', 'tracebook')
def test_noshell(self):
utils.ROCK_SHELL = '/tmp/hopefully-no-exists'
s = utils.Shell()
s.__enter__()
self.assertRaises(ConfigError, s.__exit__, 'type', 'value', 'tracebook')
|
import helper
from rock import utils
class UtilsTestCase(helper.unittest.TestCase):
def test_shell(self):
utils.Shell.run = lambda self: self
s = utils.Shell()
self.assertTrue(isinstance(s.__enter__(), utils.Shell))
s.write('ok')
s.__exit__(None, None, None)
self.assertEqual(s.stdin.getvalue(), 'ok\n')
def execl(*args):
self.assertEqual(len(args), 4)
self.assertEqual(args[0], '/bin/bash')
self.assertEqual(args[1], '-l')
self.assertEqual(args[2], '-c')
self.assertEqual(args[3], 'ok\n')
utils.os.execl = execl
s.__exit__('type', 'value', 'tracebook')
|
Use full form of ternary operator (PHP 5.2 compat)
|
<?php
/**
* Validates a boolean attribute
*
* HTMLPurifier 4.6.0 has broken support for boolean attributes, as reported
* in: http://htmlpurifier.org/phorum/read.php?3,7631,7631
* This issue has almost been fixed in 4.7.0, boolean attributes are properly
* parsed, but their values are not validated.
*/
class HTMLPurifier_AttrDef_HTML_Bool2 extends HTMLPurifier_AttrDef_HTML_Bool
{
/**
* @param string $string
* @param HTMLPurifier_Config $config
* @param HTMLPurifier_Context $context
* @return bool
*/
public function validate($string, $config, $context)
{
$name = strlen($this->name) ? $this->name : $context->get('CurrentAttr');
// boolean attribute validates if its value is either empty
// or case-insensitively equal to attribute name
return $string === '' || strcasecmp($name, $string) === 0;
}
/**
* @param string $string Name of attribute
* @return HTMLPurifier_AttrDef_HTML_Bool2
*/
public function make($string)
{
return new self($string);
}
}
// vim: et sw=4 sts=4
|
<?php
/**
* Validates a boolean attribute
*
* HTMLPurifier 4.6.0 has broken support for boolean attributes, as reported
* in: http://htmlpurifier.org/phorum/read.php?3,7631,7631
* This issue has almost been fixed in 4.7.0, boolean attributes are properly
* parsed, but their values are not validated.
*/
class HTMLPurifier_AttrDef_HTML_Bool2 extends HTMLPurifier_AttrDef_HTML_Bool
{
/**
* @param string $string
* @param HTMLPurifier_Config $config
* @param HTMLPurifier_Context $context
* @return bool
*/
public function validate($string, $config, $context)
{
$name = $this->name ? : $context->get('CurrentAttr');
// boolean attribute validates if its value is either empty
// or case-insensitively equal to attribute name
return $string === '' || strcasecmp($name, $string) === 0;
}
/**
* @param string $string Name of attribute
* @return HTMLPurifier_AttrDef_HTML_Bool2
*/
public function make($string)
{
return new self($string);
}
}
// vim: et sw=4 sts=4
|
Check Python version at runtime
|
# -*- coding: utf-8 -*-
import sys
PY2 = sys.version_info[0] == 2
if sys.version_info < (3, 3) and sys.version_info[:2] != (2, 7):
raise RuntimeError(
'vdirsyncer only works on Python versions 2.7.x and 3.3+'
)
if PY2: # pragma: no cover
import urlparse
from urllib import \
quote as urlquote, \
unquote as urlunquote
text_type = unicode # flake8: noqa
iteritems = lambda x: x.iteritems()
itervalues = lambda x: x.itervalues()
else: # pragma: no cover
import urllib.parse as urlparse
urlquote = urlparse.quote
urlunquote = urlparse.unquote
text_type = str
iteritems = lambda x: x.items()
itervalues = lambda x: x.values()
def with_metaclass(meta, *bases):
'''Original code from six, by Benjamin Peterson.'''
class metaclass(meta):
def __new__(cls, name, this_bases, d):
return meta(name, bases, d)
return type.__new__(metaclass, 'temporary_class', (), {})
|
# -*- coding: utf-8 -*-
import sys
PY2 = sys.version_info[0] == 2
if PY2: # pragma: no cover
import urlparse
from urllib import \
quote as urlquote, \
unquote as urlunquote
text_type = unicode # flake8: noqa
iteritems = lambda x: x.iteritems()
itervalues = lambda x: x.itervalues()
else: # pragma: no cover
import urllib.parse as urlparse
urlquote = urlparse.quote
urlunquote = urlparse.unquote
text_type = str
iteritems = lambda x: x.items()
itervalues = lambda x: x.values()
def with_metaclass(meta, *bases):
'''Original code from six, by Benjamin Peterson.'''
class metaclass(meta):
def __new__(cls, name, this_bases, d):
return meta(name, bases, d)
return type.__new__(metaclass, 'temporary_class', (), {})
|
Throw proper DOMException on abort
|
(function(self) {
'use strict';
if (self.AbortController) {
return;
}
class AbortController {
constructor() {
this.signal = {};
}
abort() {
if (this.signal.__internalOnCancel) {
this.signal.__internalOnCancel();
}
}
}
const realFetch = fetch;
const abortableFetch = (input, init) => {
let isAborted = false;
if (init && init.signal) {
init.signal.__internalOnCancel = () => {
isAborted = true;
};
delete init.signal;
}
return realFetch(input, init).then(r => {
if (isAborted) {
throw new DOMException('Aborted', 'AbortError');
}
return r;
});
};
self.fetch = abortableFetch;
self.AbortController = AbortController;
})(typeof self !== 'undefined' ? self : this);
|
(function(self) {
'use strict';
if (self.AbortController) {
return;
}
class AbortController {
constructor() {
this.signal = {};
}
abort() {
if (this.signal.__internalOnCancel) {
this.signal.__internalOnCancel();
}
}
}
const realFetch = fetch;
const abortableFetch = (input, init) => {
let isAborted = false;
if (init && init.signal) {
init.signal.__internalOnCancel = () => {
isAborted = true;
};
delete init.signal;
}
return realFetch(input, init).then(r => {
if (isAborted) {
throw { name: 'AbortError' };
}
return r;
});
};
self.fetch = abortableFetch;
self.AbortController = AbortController;
})(typeof self !== 'undefined' ? self : this);
|
Fix error if the user hasn't verified their email
The Discord API returns null for an unverified email. The panel requries an email to be set, therefore we set the email to a randomly generated one based on a pattern if the user doesn't have an email set.
|
<?php
namespace App;
use Carbon\Carbon;
use Keygen;
class UserRepository {
public function getUser($request) {
$user = $request->user;
$expiresIn = Carbon::now();
$expiresIn->addSecond($request->expiresIn);
return User::updateOrCreate(['id' => $request->id], [
'id' => $request->id,
'username' => $user['username'],
'email' => ($request->email == null) ? 'unverified-' . substr($user['username'], 0, 3) . '-' . Keygen::alphanum(10)->generate() . '@kirbot' : $request->email,
'refresh_token' => $request->refreshToken,
'token_type' => in_array('guilds', explode(' ', $request->accessTokenResponseBody['scope'])) ? 'NAME_SERVERS' : 'NAME_ONLY',
'token' => $request->token,
'expires_in' => $expiresIn->toDateTimeString()
]);
}
}
|
<?php
namespace App;
use Carbon\Carbon;
class UserRepository {
public function getUser($request) {
$user = $request->user;
$expiresIn = Carbon::now();
$expiresIn->addSecond($request->expiresIn);
return User::updateOrCreate(['id' => $request->id], [
'id' => $request->id,
'username' => $user['username'],
'email' => $request->email,
'refresh_token' => $request->refreshToken,
'token_type' => in_array('guilds', explode(' ', $request->accessTokenResponseBody['scope']))? 'NAME_SERVERS' : 'NAME_ONLY',
'token' => $request->token,
'expires_in' => $expiresIn->toDateTimeString()
]);
}
}
|
Make external api to a factory function
|
"use strict";
window.ArethusaExternalApi = function () {
var obj = {};
obj.isArethusaLoaded = function() {
try {
angular.module('arethusa');
} catch(err) {
return false;
}
};
// I guess it might come to this sort of guarding close, so that other plugin
// can implement this safely. We just ask if arethusa is loaded and proceed -
// if it's not, we provide a mock object that just does nothing.
if (obj.isArethusaLoaded) {
angular.element(document.body).ready(function() {
obj.injector = angular.element(document.body).injector();
obj.state = obj.injector.get('state');
obj.fireEvent = function(token, category, oldVal, newVal) {
obj.state.fireEvent(token, category, oldVal, newVal);
};
});
} else {
// tbd - BlackHole object
}
return obj;
};
|
"use strict";
window.ArethusaExternalApi = (function () {
var obj = {};
obj.isArethusaLoaded = function() {
try {
angular.module('arethusa');
} catch(err) {
return false;
}
};
// I guess it might come to this sort of guarding close, so that other plugin
// can implement this safely. We just ask if arethusa is loaded and proceed -
// if it's not, we provide a mock object that just does nothing.
if (obj.isArethusaLoaded) {
angular.element(document.body).ready(function() {
obj.state = angular.element(document.body).injector().get('state');
console.log(obj.state);
});
//obj.state = injector().get('state');
//obj.fireEvent = function(token, category, oldVal, newVal) {
//obj.state.fireEvent(token, category, oldVal, newVal);
//};
} else {
// tbd - BlackHole object
}
return obj;
}());
|
Use proper syntax for boolean attributes
|
package com.gurkensalat.osm.repository;
import com.gurkensalat.osm.entity.LinkedPlace;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import javax.transaction.Transactional;
@RepositoryRestResource(collectionResourceRel = "linkedPlace", path = "linkedPlace")
public interface LinkedPlaceRepository extends PagingAndSortingRepository<LinkedPlace, Long>
{
Iterable<LinkedPlace> findAllByOsmId(@Param("OSM_ID") String osmId);
Iterable<LinkedPlace> findAllByDitibCode(@Param("DITIB_CODE") String ditibCode);
@Modifying
@Transactional
@Query("update LinkedPlace set valid = false")
void invalidateAll();
@Modifying
@Transactional
@Query("delete from LinkedPlace where valid = false")
void deleteAllInvalid();
}
|
package com.gurkensalat.osm.repository;
import com.gurkensalat.osm.entity.LinkedPlace;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import javax.transaction.Transactional;
@RepositoryRestResource(collectionResourceRel = "linkedPlace", path = "linkedPlace")
public interface LinkedPlaceRepository extends PagingAndSortingRepository<LinkedPlace, Long>
{
Iterable<LinkedPlace> findAllByOsmId(@Param("OSM_ID") String osmId);
Iterable<LinkedPlace> findAllByDitibCode(@Param("DITIB_CODE") String ditibCode);
@Modifying
@Transactional
@Query("update LinkedPlace set valid = 'f'")
void invalidateAll();
@Modifying
@Transactional
@Query("delete from LinkedPlace where valid = 'f'")
void deleteAllInvalid();
}
|
Fix char test to only run on test/none.
Change-Id: I8f5ac5a6e7399ce2fdbe78d07ae24deaa1d7532d
Reviewed-on: http://gerrit.sjc.cloudera.com:8080/4326
Tested-by: jenkins
Reviewed-by: Alex Behm <fe1626037acfc2dc542d2aa723a6d14f2464a20c@cloudera.com>
|
#!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
#
import logging
import pytest
from copy import copy
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestStringQueries(ImpalaTestSuite):
@classmethod
def get_workload(cls):
return 'functional-query'
def setup_method(self, method):
self.__cleanup_char_tables()
self.__create_char_tables()
def teardown_method(self, method):
self.__cleanup_char_tables()
def __cleanup_char_tables(self):
self.client.execute('drop table if exists functional.test_char_tmp');
self.client.execute('drop table if exists functional.test_varchar_tmp');
def __create_char_tables(self):
self.client.execute(
'create table if not exists functional.test_varchar_tmp (vc varchar(5))')
self.client.execute(
'create table if not exists functional.test_char_tmp (c char(5))')
@classmethod
def add_test_dimensions(cls):
super(TestStringQueries, cls).add_test_dimensions()
cls.TestMatrix.add_dimension(
create_exec_option_dimension(disable_codegen_options=[True]))
cls.TestMatrix.add_constraint(lambda v:\
v.get_value('table_format').file_format in ['text'] and
v.get_value('table_format').compression_codec in ['none'])
def test_varchar(self, vector):
self.run_test_case('QueryTest/chars', vector)
|
#!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
#
import logging
import pytest
from copy import copy
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestStringQueries(ImpalaTestSuite):
@classmethod
def get_workload(cls):
return 'functional-query'
def setup_method(self, method):
self.__cleanup_char_tables()
self.__create_char_tables()
def teardown_method(self, method):
self.__cleanup_char_tables()
def __cleanup_char_tables(self):
self.client.execute('drop table if exists functional.test_char_tmp');
self.client.execute('drop table if exists functional.test_varchar_tmp');
def __create_char_tables(self):
self.client.execute(
'create table if not exists functional.test_varchar_tmp (vc varchar(5))')
self.client.execute(
'create table if not exists functional.test_char_tmp (c char(5))')
@classmethod
def add_test_dimensions(cls):
super(TestStringQueries, cls).add_test_dimensions()
cls.TestMatrix.add_dimension(
create_exec_option_dimension(disable_codegen_options=[True]))
cls.TestMatrix.add_constraint(lambda v:\
v.get_value('table_format').file_format in ['text'])
def test_varchar(self, vector):
self.run_test_case('QueryTest/chars', vector)
|
Use Fake redis for tests.
|
import os
from roku import Roku
from app.core.messaging import Receiver
from app.core.servicemanager import ServiceManager
from app.services.tv_remote.service import RokuScanner, RokuTV
class TestRokuScanner(object):
@classmethod
def setup_class(cls):
os.environ["USE_FAKE_REDIS"] = "TRUE"
cls.service_manager = ServiceManager(None)
cls.service_manager.start_services(["messaging"])
@classmethod
def teardown_class(cls):
del os.environ["USE_FAKE_REDIS"]
cls.service_manager.stop()
def test_basic_discovery(self):
roku1 = Roku("abc")
scanner = RokuScanner("/devices", scan_interval=10)
scanner.discover_devices = lambda: [roku1]
scanner.get_device_id = lambda: "deviceid"
scanner.start()
receiver = Receiver("/devices")
msg = receiver.receive()
expected = {
"deviceid": {
"device_id": "deviceid",
"device_command_queue": "devices/tv/command",
"device_commands": RokuTV(None, None).read_commands()
}
}
assert msg == expected
|
from roku import Roku
from app.core.messaging import Receiver
from app.core.servicemanager import ServiceManager
from app.services.tv_remote.service import RokuScanner, RokuTV
class TestRokuScanner(object):
@classmethod
def setup_class(cls):
cls.service_manager = ServiceManager(None)
cls.service_manager.start_services(["messaging"])
@classmethod
def teardown_class(cls):
cls.service_manager.stop()
def test_basic_discovery(self):
roku1 = Roku("abc")
scanner = RokuScanner("/devices", scan_interval=10)
scanner.discover_devices = lambda: [roku1]
scanner.get_device_id = lambda: "deviceid"
scanner.start()
receiver = Receiver("/devices")
msg = receiver.receive()
expected = {
"deviceid": {
"device_id": "deviceid",
"device_command_queue": "devices/tv/command",
"device_commands": RokuTV(None, None).read_commands()
}
}
assert msg == expected
|
Add t5x.losses to public API.
PiperOrigin-RevId: 417631806
|
# Copyright 2021 The T5X 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.
"""Import API modules."""
import t5x.adafactor
import t5x.checkpoints
import t5x.decoding
import t5x.gin_utils
import t5x.losses
import t5x.models
import t5x.multihost_utils
import t5x.partitioning
import t5x.state_utils
import t5x.train_state
import t5x.trainer
import t5x.utils
# Version number.
from t5x.version import __version__
# TODO(adarob): Move clients to t5x.checkpointing and rename
# checkpoints.py to checkpointing.py
checkpointing = t5x.checkpoints
|
# Copyright 2021 The T5X 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.
"""Import API modules."""
import t5x.adafactor
import t5x.checkpoints
import t5x.decoding
import t5x.gin_utils
import t5x.models
import t5x.multihost_utils
import t5x.partitioning
import t5x.state_utils
import t5x.train_state
import t5x.trainer
import t5x.utils
# Version number.
from t5x.version import __version__
# TODO(adarob): Move clients to t5x.checkpointing and rename
# checkpoints.py to checkpointing.py
checkpointing = t5x.checkpoints
|
gles: Add GLenum_GL_UNSIGNED_INT_2_10_10_10_REV case to DataTypeSize()
|
// Copyright (C) 2017 Google Inc.
//
// 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 gles
import "fmt"
// DataTypeSize returns the size in bytes of the the specified data type.
func DataTypeSize(t GLenum) int {
switch t {
case GLenum_GL_BYTE,
GLenum_GL_UNSIGNED_BYTE:
return 1
case GLenum_GL_SHORT,
GLenum_GL_UNSIGNED_SHORT,
GLenum_GL_HALF_FLOAT_ARB,
GLenum_GL_HALF_FLOAT_OES:
return 2
case GLenum_GL_FIXED,
GLenum_GL_FLOAT,
GLenum_GL_UNSIGNED_INT,
GLenum_GL_UNSIGNED_INT_2_10_10_10_REV:
return 4
default:
panic(fmt.Errorf("Unknown data type %v", t))
}
}
|
// Copyright (C) 2017 Google Inc.
//
// 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 gles
import "fmt"
// DataTypeSize returns the size in bytes of the the specified data type.
func DataTypeSize(t GLenum) int {
switch t {
case GLenum_GL_BYTE:
return 1
case GLenum_GL_UNSIGNED_BYTE:
return 1
case GLenum_GL_SHORT:
return 2
case GLenum_GL_UNSIGNED_SHORT:
return 2
case GLenum_GL_HALF_FLOAT_ARB:
return 2
case GLenum_GL_HALF_FLOAT_OES:
return 2
case GLenum_GL_FIXED:
return 4
case GLenum_GL_FLOAT:
return 4
case GLenum_GL_UNSIGNED_INT:
return 4
default:
panic(fmt.Errorf("Unknown data type %v", t))
}
}
|
Fix rtestricted route showing modal
|
import React from 'react';
import { connect } from 'react-redux';
import { withRouter } from 'react-router';
import { showModalWindow } from 'actions/ModalActions';
import CheckAuth from 'components/CheckAuth';
const RestrictedWrapper = (WrappedComponent) => {
const Restricted = withRouter(React.createClass({
componentWillMount () {
const { me, location, router } = this.props;
if (__CLIENT__ && !me.id) {
if (location.action === 'POP') {
router.replace(
`/auth/login?next=${encodeURIComponent(location.pathname)}`
);
} else {
router.goBack();
this.props.showModalWindow({ type: 'auth' }, location);
}
}
},
render () {
return (
<CheckAuth me={this.props.me}>
<WrappedComponent {...this.props} />
</CheckAuth>
);
}
}));
const mapStateToProps = (state) => (state);
const mapDispatchToProps = (dispatch) => {
return { showModalWindow: (type, location) => dispatch(showModalWindow(type, location)) };
};
return connect(
mapStateToProps,
mapDispatchToProps
)(Restricted);
};
export default RestrictedWrapper;
|
import React from 'react';
import { connect } from 'react-redux';
import { withRouter } from 'react-router';
import { showModalWindow } from 'actions/ModalActions';
import CheckAuth from 'components/CheckAuth';
const RestrictedWrapper = (WrappedComponent) => {
const Restricted = withRouter(React.createClass({
componentWillMount () {
const { me, location, router } = this.props;
if (__CLIENT__ && !me.id) {
if (location.action === 'POP') {
router.replace(
`/auth/login?next=${encodeURIComponent(location.pathname)}`
);
} else {
router.goBack();
this.props.showModalWindow('auth', location);
}
}
},
render () {
return (
<CheckAuth me={this.props.me}>
<WrappedComponent {...this.props} />
</CheckAuth>
);
}
}));
const mapStateToProps = (state) => (state);
const mapDispatchToProps = (dispatch) => {
return { showModalWindow: (type, location) => dispatch(showModalWindow(type, location)) };
};
return connect(
mapStateToProps,
mapDispatchToProps
)(Restricted);
};
export default RestrictedWrapper;
|
[testsuite] Remove trailing characters from command output.
When running the test suite on macOS with Python 3 we noticed a
difference in behavior between Python 2 and Python 3 for
seven.get_command_output. The output contained a newline with Python 3,
but not for Python 2. This resulted in an invalid SDK path passed to the
compiler.
Differential revision: https://reviews.llvm.org/D57275
git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@352397 91177308-0d34-0410-b5e6-96231b3b80d8
|
import six
if six.PY2:
import commands
get_command_output = commands.getoutput
get_command_status_output = commands.getstatusoutput
cmp_ = cmp
else:
def get_command_status_output(command):
try:
import subprocess
return (
0,
subprocess.check_output(
command,
shell=True,
universal_newlines=True).rstrip())
except subprocess.CalledProcessError as e:
return (e.returncode, e.output)
def get_command_output(command):
return get_command_status_output(command)[1]
cmp_ = lambda x, y: (x > y) - (x < y)
|
import six
if six.PY2:
import commands
get_command_output = commands.getoutput
get_command_status_output = commands.getstatusoutput
cmp_ = cmp
else:
def get_command_status_output(command):
try:
import subprocess
return (
0,
subprocess.check_output(
command,
shell=True,
universal_newlines=True))
except subprocess.CalledProcessError as e:
return (e.returncode, e.output)
def get_command_output(command):
return get_command_status_output(command)[1]
cmp_ = lambda x, y: (x > y) - (x < y)
|
Add behavior to navigate to the new URL!
|
import { setTheInput } from './URLUtils-impl.js';
import { setAll as setPrivateMethods } from './private-methods.js';
export default class CustomHTMLAnchorElementImpl {
createdCallback() {
doSetTheInput(this);
addDefaultEventListener(this, 'click', () => window.location.href = this.href);
}
attributeChangedCallback(name) {
if (name === 'href') {
doSetTheInput(this);
}
}
get text() {
return this.textContent;
}
set text(v) {
this.textContent = v;
}
}
setPrivateMethods('CustomHTMLAnchorElement', {
// Required by URLUtils
getTheBase() {
return this.baseURI;
},
updateSteps(value) {
this.setAttribute('href', value);
}
});
function doSetTheInput(el) {
var urlInput = el.hasAttribute('href') ? el.getAttribute('href') : '';
setTheInput(el, urlInput);
}
// This might be more generally useful; if so factor it out into its own file.
function addDefaultEventListener(eventTarget, eventName, listener) {
eventTarget.addEventListener(eventName, e => {
setTimeout(() => {
if (!e.defaultPrevented) {
listener(e);
}
}, 0);
});
}
|
import { setTheInput } from './URLUtils-impl.js';
import { setAll as setPrivateMethods } from './private-methods.js';
export default class CustomHTMLAnchorElementImpl {
createdCallback() {
doSetTheInput(this);
}
attributeChangedCallback(name) {
if (name === 'href') {
doSetTheInput(this);
}
}
get text() {
return this.textContent;
}
set text(v) {
this.textContent = v;
}
}
setPrivateMethods('CustomHTMLAnchorElement', {
// Required by URLUtils
getTheBase() {
return this.baseURI;
},
updateSteps(value) {
this.setAttribute('href', value);
}
});
function doSetTheInput(el) {
var urlInput = el.hasAttribute('href') ? el.getAttribute('href') : '';
setTheInput(el, urlInput);
}
|
Change bindShared to singleton due to deprecation since Laravel 5.1
|
<?php namespace Barryvdh\TranslationManager;
use Illuminate\Translation\TranslationServiceProvider as BaseTranslationServiceProvider;
class TranslationServiceProvider extends BaseTranslationServiceProvider {
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->registerLoader();
$this->app->singleton('translator', function($app)
{
$loader = $app['translation.loader'];
// When registering the translator component, we'll need to set the default
// locale as well as the fallback locale. So, we'll grab the application
// configuration so we can easily get both of these values from there.
$locale = $app['config']['app.locale'];
$trans = new Translator($loader, $locale);
$trans->setFallback($app['config']['app.fallback_locale']);
if($app->bound('translation-manager')){
$trans->setTranslationManager($app['translation-manager']);
}
return $trans;
});
}
}
|
<?php namespace Barryvdh\TranslationManager;
use Illuminate\Translation\TranslationServiceProvider as BaseTranslationServiceProvider;
class TranslationServiceProvider extends BaseTranslationServiceProvider {
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->registerLoader();
$this->app->bindShared('translator', function($app)
{
$loader = $app['translation.loader'];
// When registering the translator component, we'll need to set the default
// locale as well as the fallback locale. So, we'll grab the application
// configuration so we can easily get both of these values from there.
$locale = $app['config']['app.locale'];
$trans = new Translator($loader, $locale);
$trans->setFallback($app['config']['app.fallback_locale']);
if($app->bound('translation-manager')){
$trans->setTranslationManager($app['translation-manager']);
}
return $trans;
});
}
}
|
Update the s3 api example
|
package aws
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials/stscreds"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
)
func ListBuckets() {
fmt.Println("List buckets")
// Specify profile for config and region for requests
sess := session.Must(session.NewSessionWithOptions(session.Options{
Config: aws.Config{Region: aws.String("us-west-2")},
Profile: "okta2aws",
}))
creds := stscreds.NewCredentials(sess,
"arn:aws:iam::461168169469:role/SSOAdmin1Role")
s3svc := s3.New(sess, &aws.Config{Credentials: creds})
result, err := s3svc.ListBuckets(nil)
if err != nil {
fmt.Println("Failed to list s3 buckets.", err)
}
for _, b := range result.Buckets {
fmt.Printf("Bucket %s created on %s \n ",
aws.StringValue(b.Name),
aws.TimeValue(b.CreationDate))
bucketname := aws.String(*b.Name)
// Get Bucket location.
input := &s3.GetBucketLocationInput{
Bucket: bucketname,
}
result, err := s3svc.GetBucketLocation(input)
if err != nil {
fmt.Println(err.Error())
}
fmt.Printf("Result: %s", aws.StringValue(result.LocationConstraint))
}
}
|
package aws
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials/stscreds"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
)
func ListBuckets() {
fmt.Println("List buckets")
// Specify profile for config and region for requests
sess := session.Must(session.NewSessionWithOptions(session.Options{
Config: aws.Config{Region: aws.String("us-west-2")},
Profile: "okta2aws",
}))
creds := stscreds.NewCredentials(sess,
"arn:aws:iam::4xxxx9:role/SoeRolee")
s3svc := s3.New(sess, &aws.Config{Credentials: creds})
result, err := s3svc.ListBuckets(nil)
if err != nil {
fmt.Println("Failed to list s3 buckets.", err)
}
for _, b := range result.Buckets {
fmt.Printf("* %s created on %s \n ",
aws.StringValue(b.Name),
aws.TimeValue(b.CreationDate))
}
}
|
Update sys.path to import heatmap
|
#!/usr/bin/env python
"""Test coordinate classes."""
import sys
try:
import unittest2 as unittest # Python 2.6
except ImportError:
import unittest
ROOT_DIR = os.path.split(os.path.abspath(os.path.dirname(__file__)))[0]
sys.path.append(ROOT_DIR)
import heatmap as hm
class Tests(unittest.TestCase):
# To remove Python 3's
# "DeprecationWarning: Please use assertRaisesRegex instead"
if sys.version_info[0] == 2:
assertRaisesRegex = unittest.TestCase.assertRaisesRegexp
def test_basic(self):
'''Test Configuration class.'''
# Act
config = hm.Configuration(use_defaults=True)
# Assert
self.assertEqual(config.margin, 0)
self.assertEqual(config.frequency, 1)
def test_fill_missing_no_input(self):
'''Test Configuration class.'''
# Arrange
config = hm.Configuration(use_defaults=True)
# Act / Assert
with self.assertRaisesRegex(ValueError, "no input specified"):
config.fill_missing()
if __name__ == '__main__':
unittest.main()
|
#!/usr/bin/env python
"""Test coordinate classes."""
import sys
try:
import unittest2 as unittest # Python 2.6
except ImportError:
import unittest
import heatmap as hm
class Tests(unittest.TestCase):
# To remove Python 3's
# "DeprecationWarning: Please use assertRaisesRegex instead"
if sys.version_info[0] == 2:
assertRaisesRegex = unittest.TestCase.assertRaisesRegexp
def test_basic(self):
'''Test Configuration class.'''
# Act
config = hm.Configuration(use_defaults=True)
# Assert
self.assertEqual(config.margin, 0)
self.assertEqual(config.frequency, 1)
def test_fill_missing_no_input(self):
'''Test Configuration class.'''
# Arrange
config = hm.Configuration(use_defaults=True)
# Act / Assert
with self.assertRaisesRegex(ValueError, "no input specified"):
config.fill_missing()
if __name__ == '__main__':
unittest.main()
|
Allow all attributes to be gathered in a simple array
|
<?php
namespace duncan3dc\DomParser;
class Element extends Base {
public function __construct($dom,$mode) {
parent::__construct($dom,$mode);
}
public function __get($key) {
$value = $this->dom->$key;
switch($key) {
case "parentNode":
return new Element($value,$this->mode);
break;
case "nodeValue":
return trim($value);
break;
}
return $value;
}
public function getAttribute($name) {
return $this->dom->getAttribute($name);
}
public function getAttributes() {
$attributes = array();
foreach($this->dom->attributes as $key => $val) {
$attributes[$key] = $val;
}
return $attributes;
}
}
|
<?php
namespace duncan3dc\DomParser;
class Element extends Base {
public function __construct($dom,$mode) {
parent::__construct($dom,$mode);
}
public function __get($key) {
$value = $this->dom->$key;
switch($key) {
case "parentNode":
return new Element($value,$this->mode);
break;
case "nodeValue":
return trim($value);
break;
}
return $value;
}
public function getAttribute($name) {
return $this->dom->getAttribute($name);
}
}
|
Use the `seq` from the fixture
|
'use strict'
const assert = require('assert')
const assertCalled = require('assert-called')
const CouchDBChangesResponse = require('../')
const changes = [
{
id: 'foo',
changes: [{ rev: '2-578db51f2d332dd53a5ca02cf6ca5b54' }],
seq: 12
},
{
id: 'bar',
changes: [{ rev: '4-378db51f2d332dd53a5ca02cf6ca5b54' }],
seq: 14
}
]
const stream = new CouchDBChangesResponse({
type: 'normal'
})
const chunks = []
stream.once('readable', assertCalled(() => {
var chunk
while ((chunk = stream.read()) && chunks.push(chunk));
}))
stream.once('finish', assertCalled(() => {
assert.deepEqual(JSON.parse(chunks.join('')), {
results: changes,
last_seq: changes[1].seq
})
}))
stream.write(changes[0])
stream.write(changes[1])
stream.write({ last_seq: changes[1].seq })
stream.end()
|
'use strict'
const assert = require('assert')
const assertCalled = require('assert-called')
const CouchDBChangesResponse = require('../')
const changes = [
{
id: 'foo',
changes: [{ rev: '2-578db51f2d332dd53a5ca02cf6ca5b54' }],
seq: 12
},
{
id: 'bar',
changes: [{ rev: '4-378db51f2d332dd53a5ca02cf6ca5b54' }],
seq: 14
}
]
const stream = new CouchDBChangesResponse({
type: 'normal'
})
const chunks = []
stream.once('readable', assertCalled(() => {
var chunk
while ((chunk = stream.read()) && chunks.push(chunk));
}))
stream.once('finish', assertCalled(() => {
assert.deepEqual(JSON.parse(chunks.join('')), {
results: changes,
last_seq: 14
})
}))
stream.write(changes[0])
stream.write(changes[1])
stream.write({ last_seq: changes[1].seq })
stream.end()
|
Increment index version for 1.6.13
|
/*
* Copyright (c) Joachim Ansorg, mail@ansorg-it.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ansorgit.plugins.bash.lang.psi.stubs.index;
/**
* Configures the versions of the available Bash indexes.
*/
public final class BashIndexVersion {
private static final int BASE = 42;
public static final int CACHES_VERSION = BASE + 9;
public static final int STUB_INDEX_VERSION = BASE + 31;
public static final int ID_INDEX_VERSION = BASE + 19;
private BashIndexVersion() {
}
}
|
/*
* Copyright (c) Joachim Ansorg, mail@ansorg-it.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ansorgit.plugins.bash.lang.psi.stubs.index;
/**
* Configures the versions of the available Bash indexes.
*/
public final class BashIndexVersion {
private static final int BASE = 41;
public static final int CACHES_VERSION = BASE + 9;
public static final int STUB_INDEX_VERSION = BASE + 31;
public static final int ID_INDEX_VERSION = BASE + 19;
private BashIndexVersion() {
}
}
|
Add contact page to nav
|
<?php
error_reporting(E_ALL);
// WH Test database settings
define('DB_NAME', 'test');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_HOST', '127.0.0.1');
define('DIR_BASE', dirname(dirname(dirname(__FILE__))).'/');
define('DIR_APP', DIR_BASE.'app');
define('DIR_CLASS', DIR_APP.'/class/');
define('DIR_LIB', DIR_BASE.'lib/');
define('DIR_SQL', './sql/');
define('BASE_URL', 'http://localhost/JD.meDev/');
define('SUB_DIR', '/JD.meDev/');
define('LOADED', true);
// WH This is a general settings array. Some of our classes currently depend on this
// but I plan on re-writing them to correct this.
// $settings['sub_dir'] = '/JD.meDev/';
$settings['js'][] = 'main.js';
$settings['main_nav'] = array('home', 'about me', 'testimonials','blog','portfolio', 'contact');
|
<?php
error_reporting(E_ALL);
// WH Test database settings
define('DB_NAME', 'test');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_HOST', '127.0.0.1');
define('DIR_BASE', dirname(dirname(dirname(__FILE__))).'/');
define('DIR_APP', DIR_BASE.'app');
define('DIR_CLASS', DIR_APP.'/class/');
define('DIR_LIB', DIR_BASE.'lib/');
define('DIR_SQL', './sql/');
define('BASE_URL', 'http://localhost/JD.meDev/');
define('SUB_DIR', '/JD.meDev/');
define('LOADED', true);
// WH This is a general settings array. Some of our classes currently depend on this
// but I plan on re-writing them to correct this.
// $settings['sub_dir'] = '/JD.meDev/';
$settings['js'][] = 'main.js';
$settings['main_nav'] = array('home', 'about me', 'testimonials','blog','portfolio');
|
Allow runtime $ and : to accept variable amount of arguments.
|
import sys
import operator
import dg
import interactive
from . import compiler
class Interactive (interactive.Interactive):
PARSER = dg.Parser()
COMPILER = compiler.Compiler()
GLOBALS = {
# Runtime counterparts of some stuff in `Compiler.builtins`.
'$': lambda f, *xs: f(*xs)
, ':': lambda f, *xs: f(*xs)
# TODO various operators
, '+': operator.add
, '-': operator.sub
, '!!': operator.getitem
}
def compile(self, code):
q = self.PARSER.compile_command(code)
q = q if q is None else self.COMPILER.compile(q, name='<module>', single=True)
return q
def run(self, ns):
q = self.PARSER.parse(sys.stdin, '<stdin>')
q = self.COMPILER.compile(q, name='<module>')
return self.eval(q, ns)
Interactive().shell(__name__, Interactive.GLOBALS)
|
import sys
import operator
import dg
import interactive
from . import compiler
class Interactive (interactive.Interactive):
PARSER = dg.Parser()
COMPILER = compiler.Compiler()
GLOBALS = {
# Runtime counterparts of some stuff in `Compiler.builtins`.
'$': lambda f, x: f(x)
, ':': lambda f, x: f(x)
# TODO various operators
, '+': operator.add
, '-': operator.sub
, '!!': operator.getitem
}
def compile(self, code):
q = self.PARSER.compile_command(code)
q = q if q is None else self.COMPILER.compile(q, name='<module>', single=True)
return q
def run(self, ns):
q = self.PARSER.parse(sys.stdin, '<stdin>')
q = self.COMPILER.compile(q, name='<module>')
return self.eval(q, ns)
Interactive().shell(__name__, Interactive.GLOBALS)
|
Fix: Improve native WeakMap check for newer node versions
|
'use strict';
var assert = require('assert');
var WM = require('es6-weak-map');
var hasWeakMap = require('es6-weak-map/is-implemented');
var defaultResolution = require('default-resolution');
var runtimes = new WM();
function isFunction(fn){
return (typeof fn === 'function');
}
function isExtensible(fn){
if(hasWeakMap()){
// native weakmap doesn't care about extensible
return true;
}
return Object.isExtensible(fn);
}
function lastRun(fn, timeResolution){
assert(isFunction(fn), 'Only functions can check lastRun');
assert(isExtensible(fn), 'Only extensible functions can check lastRun');
var time = runtimes.get(fn);
if(time == null){
return;
}
if(timeResolution == null){
timeResolution = defaultResolution();
}
if(timeResolution){
return time - (time % timeResolution);
}
return time;
}
function capture(fn){
assert(isFunction(fn), 'Only functions can be captured');
assert(isExtensible(fn), 'Only extensible functions can be captured');
runtimes.set(fn, Date.now());
}
lastRun.capture = capture;
module.exports = lastRun;
|
'use strict';
var assert = require('assert');
var WM = require('es6-weak-map');
var hasNativeWeakmap = require('es6-weak-map/is-native-implemented');
var defaultResolution = require('default-resolution');
var runtimes = new WM();
function isFunction(fn){
return (typeof fn === 'function');
}
function isExtensible(fn){
if(hasNativeWeakmap){
// native weakmap doesn't care about extensible
return true;
}
return Object.isExtensible(fn);
}
function lastRun(fn, timeResolution){
assert(isFunction(fn), 'Only functions can check lastRun');
assert(isExtensible(fn), 'Only extensible functions can check lastRun');
var time = runtimes.get(fn);
if(time == null){
return;
}
if(timeResolution == null){
timeResolution = defaultResolution();
}
if(timeResolution){
return time - (time % timeResolution);
}
return time;
}
function capture(fn){
assert(isFunction(fn), 'Only functions can be captured');
assert(isExtensible(fn), 'Only extensible functions can be captured');
runtimes.set(fn, Date.now());
}
lastRun.capture = capture;
module.exports = lastRun;
|
Watch for changes on HYP_CONTENT_FOR_IDS
|
angular.module("hypContentFor", [])
.value("HYP_CONTENT_FOR_IDS", { })
.directive("content", function () {
return {
scope: { "for": "@" },
transclude: true,
controller: function ($scope, $transclude, HYP_CONTENT_FOR_IDS) {
HYP_CONTENT_FOR_IDS[$scope["for"]] = $transclude();
}
};
})
.directive("yield", function ($interval, HYP_CONTENT_FOR_IDS) {
return {
scope: { to: "@" },
link: function (scope, elem) {
interval = null;
watchFn = function () { return HYP_CONTENT_FOR_IDS[scope.to]; };
scope.$watch(watchFn, function (newValue) {
elem.empty();
elem.append(newValue);
});
}
};
});
|
angular.module("hypContentFor", [])
.constant("HYP_CONTENT_FOR_IDS", [ ])
.directive("content", function (HYP_CONTENT_FOR_IDS) {
return {
scope: { "for": "@" },
transclude: true,
controller: function ($scope, $transclude) {
HYP_CONTENT_FOR_IDS[$scope["for"]] = $transclude();
}
};
})
.directive("yield", function ($interval, HYP_CONTENT_FOR_IDS) {
return {
scope: { to: "@" },
link: function (scope, elem) {
interval = null;
repeatFn = function () {
content = HYP_CONTENT_FOR_IDS[scope.to];
if (content) {
$interval.cancel(interval);
} else {
return;
}
elem.replaceWith(content);
}
repeatFn();
interval = $interval(repeatFn, 100, 9);
}
};
});
|
Include site and current url in navigation shape data.
|
// DecentCMS (c) 2014 Bertrand Le Roy, under MIT. See LICENSE.txt for licensing details.
'use strict';
var async = require('async');
function NavigationHandler(scope) {
this.scope = scope;
}
NavigationHandler.feature = 'navigation';
NavigationHandler.service = 'shape-handler';
NavigationHandler.scope = 'request';
NavigationHandler.prototype.handle = function handleNavigation(context, done) {
var layout = context.shape;
if (!layout.meta || layout.meta.type !== 'layout') return done();
var scope = this.scope;
var navigationContext = {
menu: 'default',
items: []
};
this.scope.callService('navigation-provider', 'addRootItems', navigationContext, function() {
var site = scope.require('shell');
var current = scope.url;
var shapeHelper = scope.require('shape');
shapeHelper.place(layout, 'navigation', {
meta: {type: 'menu'},
site: site,
name: navigationContext.menu,
items: navigationContext.items,
current: current
}, 'after');
done();
});
};
module.exports = NavigationHandler;
|
// DecentCMS (c) 2014 Bertrand Le Roy, under MIT. See LICENSE.txt for licensing details.
'use strict';
var async = require('async');
function NavigationHandler(scope) {
this.scope = scope;
}
NavigationHandler.feature = 'navigation';
NavigationHandler.service = 'shape-handler';
NavigationHandler.scope = 'request';
NavigationHandler.prototype.handle = function handleNavigation(context, done) {
var layout = context.shape;
if (!layout.meta || layout.meta.type !== 'layout') return done();
var scope = this.scope;
var navigationContext = {
menu: 'default',
items: []
};
this.scope.callService('navigation-provider', 'addRootItems', navigationContext, function() {
var shapeHelper = scope.require('shape');
shapeHelper.place(layout, 'navigation', {
meta: {type: 'menu'},
name: navigationContext.menu,
items: navigationContext.items
}, 'after');
done();
});
};
module.exports = NavigationHandler;
|
Update the Portuguese example test
|
# Portuguese Language Test
from seleniumbase.translate.portuguese import CasoDeTeste
class MinhaClasseDeTeste(CasoDeTeste):
def test_exemplo_1(self):
self.abrir("https://pt.wikipedia.org/wiki/")
self.verificar_texto("Wikipédia")
self.verificar_elemento('[title="Língua portuguesa"]')
self.digitar("#searchform input", "João Pessoa")
self.clique("#searchform button")
self.verificar_texto("João Pessoa", "#firstHeading")
self.verificar_elemento('img[alt*="João Pessoa"]')
self.digitar("#searchform input", "Florianópolis")
self.clique("#searchform button")
self.verificar_texto("Florianópolis", "h1#firstHeading")
self.verificar_elemento('td:contains("Avenida Beira-Mar")')
self.voltar()
self.verificar_verdade("João" in self.obter_url_atual())
self.digitar("#searchform input", "Teatro Amazonas")
self.clique("#searchform button")
self.verificar_texto("Teatro Amazonas", "#firstHeading")
self.verificar_texto_do_link("Festival Amazonas de Ópera")
|
# Portuguese Language Test
from seleniumbase.translate.portuguese import CasoDeTeste
class MinhaClasseDeTeste(CasoDeTeste):
def test_exemplo_1(self):
self.abrir("https://pt.wikipedia.org/wiki/")
self.verificar_texto("Wikipédia")
self.verificar_elemento('[title="Língua portuguesa"]')
self.js_digitar("#searchform input", "João Pessoa")
self.clique("#searchform button")
self.verificar_texto("João Pessoa", "#firstHeading")
self.verificar_elemento('img[alt*="João Pessoa"]')
self.js_digitar("#searchform input", "Florianópolis")
self.clique("#searchform button")
self.verificar_texto("Florianópolis", "h1#firstHeading")
self.verificar_elemento('td:contains("Avenida Beira-Mar")')
self.voltar()
self.verificar_verdade("João" in self.obter_url_atual())
self.js_digitar("#searchform input", "Teatro Amazonas")
self.clique("#searchform button")
self.verificar_texto("Teatro Amazonas", "#firstHeading")
self.verificar_texto_do_link("Festival Amazonas de Ópera")
|
Add missing SHEARED spawn reason
|
package com.laytonsmith.abstraction.enums;
import com.laytonsmith.annotations.MEnum;
@MEnum("com.commandhelper.SpawnReason")
public enum MCSpawnReason {
BREEDING,
BUILD_IRONGOLEM,
BUILD_SNOWMAN,
BUILD_WITHER,
/**
* Deprecated as of 1.14, no longer used.
*/
CHUNK_GEN,
/**
* Spawned by plugins
*/
CUSTOM,
/**
* Missing spawn reason
*/
DEFAULT,
/**
* The kind of egg you throw
*/
EGG,
JOCKEY,
LIGHTNING,
NATURAL,
REINFORCEMENTS,
SHOULDER_ENTITY,
SLIME_SPLIT,
SPAWNER,
SPAWNER_EGG,
VILLAGE_DEFENSE,
VILLAGE_INVASION,
NETHER_PORTAL,
DISPENSE_EGG,
INFECTION,
CURED,
OCELOT_BABY,
SILVERFISH_BLOCK,
MOUNT,
TRAP,
ENDER_PEARL,
DROWNED,
SHEARED
}
|
package com.laytonsmith.abstraction.enums;
import com.laytonsmith.annotations.MEnum;
@MEnum("com.commandhelper.SpawnReason")
public enum MCSpawnReason {
BREEDING,
BUILD_IRONGOLEM,
BUILD_SNOWMAN,
BUILD_WITHER,
/**
* Deprecated as of 1.14, no longer used.
*/
CHUNK_GEN,
/**
* Spawned by plugins
*/
CUSTOM,
/**
* Missing spawn reason
*/
DEFAULT,
/**
* The kind of egg you throw
*/
EGG,
JOCKEY,
LIGHTNING,
NATURAL,
REINFORCEMENTS,
SHOULDER_ENTITY,
SLIME_SPLIT,
SPAWNER,
SPAWNER_EGG,
VILLAGE_DEFENSE,
VILLAGE_INVASION,
NETHER_PORTAL,
DISPENSE_EGG,
INFECTION,
CURED,
OCELOT_BABY,
SILVERFISH_BLOCK,
MOUNT,
TRAP,
ENDER_PEARL,
DROWNED,
}
|
Remove unnecessary import that was failing a test
|
from lxml import etree
from xmodule.x_module import XModule
from xmodule.raw_module import RawDescriptor
import json
class DiscussionModule(XModule):
def get_html(self):
context = {
'discussion_id': self.discussion_id,
}
return self.system.render_template('discussion/_discussion_module.html', context)
def __init__(self, system, location, definition, descriptor, instance_state=None, shared_state=None, **kwargs):
XModule.__init__(self, system, location, definition, descriptor, instance_state, shared_state, **kwargs)
if isinstance(instance_state, str):
instance_state = json.loads(instance_state)
xml_data = etree.fromstring(definition['data'])
self.discussion_id = xml_data.attrib['id']
self.title = xml_data.attrib['for']
self.discussion_category = xml_data.attrib['discussion_category']
class DiscussionDescriptor(RawDescriptor):
module_class = DiscussionModule
|
from lxml import etree
from xmodule.x_module import XModule
from xmodule.raw_module import RawDescriptor
import comment_client
import json
class DiscussionModule(XModule):
def get_html(self):
context = {
'discussion_id': self.discussion_id,
}
return self.system.render_template('discussion/_discussion_module.html', context)
def __init__(self, system, location, definition, descriptor, instance_state=None, shared_state=None, **kwargs):
XModule.__init__(self, system, location, definition, descriptor, instance_state, shared_state, **kwargs)
if isinstance(instance_state, str):
instance_state = json.loads(instance_state)
xml_data = etree.fromstring(definition['data'])
self.discussion_id = xml_data.attrib['id']
self.title = xml_data.attrib['for']
self.discussion_category = xml_data.attrib['discussion_category']
class DiscussionDescriptor(RawDescriptor):
module_class = DiscussionModule
|
Hide empty TOC items in metadata editor.
|
import { ModelComponent } from '../../kit'
export default class MetaSectionTOCEntry extends ModelComponent {
render ($$) {
const id = this.props.id
const name = this.props.name
const model = this.props.model
let el = $$('a').addClass('sc-meta-section-toc-entry')
.attr({ href: '#' + id })
.on('click', this.handleClick)
let label = this.getLabel(name)
if (model.isCollection) {
const items = model.getItems()
if (items.length > 0) {
label = label + ' (' + items.length + ')'
el.setStyle('display', 'block').append(label)
} else {
el.setStyle('display', 'none')
}
} else {
el.append(label)
}
return el
}
handleClick (e) {
// NOTE: currently we are using link anchors for metadata panel navigation
// this way we are preventing Electron from opening links in a new window
// later we want to introduce different routing mechanism
e.stopPropagation()
}
}
|
import { ModelComponent } from '../../kit'
export default class MetaSectionTOCEntry extends ModelComponent {
render ($$) {
const id = this.props.id
const name = this.props.name
const model = this.props.model
let el = $$('a').addClass('sc-meta-section-toc-entry')
.attr({ href: '#' + id })
.on('click', this.handleClick)
let label = this.getLabel(name)
if (model.isCollection) {
const items = model.getItems()
if (items.length > 0) {
label = label + ' (' + items.length + ')'
el.append(label)
}
} else {
el.append(label)
}
return el
}
handleClick (e) {
// NOTE: currently we are using link anchors for metadata panel navigation
// this way we are preventing Electron from opening links in a new window
// later we want to introduce different routing mechanism
e.stopPropagation()
}
}
|
Put the code into a comment as an example usage.
|
"""
Example usage:
import matplotlib.pyplot as plt
from files import load_wav
from analysis import split_to_blocks
def analyze_mean_energy(file, block_size=1024):
x, fs = load_wav(file)
blocks, t = split_to_blocks(x, block_size)
y = mean_energy(blocks)
plt.semilogy(t, y)
plt.ylim(0, 1)
"""
import numpy as np
def mean_power(x_blocks):
return np.sqrt(np.mean(x_blocks**2, axis=-1))
def power(x_blocks):
return np.sqrt(np.sum(x_blocks**2, axis=-1))
def mean_energy(x_blocks):
return np.mean(x_blocks**2, axis=-1)
def energy(x_blocks):
return np.sum(x_blocks**2, axis=-1)
|
import numpy as np
def mean_power(x_blocks):
return np.sqrt(np.mean(x_blocks**2, axis=-1))
def power(x_blocks):
return np.sqrt(np.sum(x_blocks**2, axis=-1))
def mean_energy(x_blocks):
return np.mean(x_blocks**2, axis=-1)
def energy(x_blocks):
return np.sum(x_blocks**2, axis=-1)
if __name__ == '__main__':
import matplotlib.pyplot as plt
from files import load_wav
from analysis import split_to_blocks
def analyze_mean_energy(file, block_size=1024):
x, fs = load_wav(file)
blocks, t = split_to_blocks(x, block_size)
y = mean_energy(blocks)
plt.semilogy(t, y)
plt.ylim(0, 1)
|
Declare 'displace' arrays at the top of the function
|
function sortCss(settings, cssObject) {
var displaceDeep = [
'sass function',
'sass import',
'sass include',
'sass include arguments',
'sass mixin',
'sass include block',
'sass extend',
'property group',
];
var displaceZeroDepth = [
'sass import',
'sass include',
'sass variable assignment',
'font face',
'sass function',
'sass mixin',
'sass include block',
'sass placeholder',
];
function sortDeep(array) {
sortCss.scope(settings, array, {
displace : displaceDeep
});
for (var i = 0, n = array.length; i < n; i++) {
if (Array.isArray(array[i].content) && array[i].content.length) {
sortDeep(array[i].content);
}
}
}
sortCss.scope(settings, cssObject, {
displace : displaceZeroDepth
});
if (settings.sortBlockScope) {
for (var i = 0, n = cssObject.length; i < n; i++) {
if (Array.isArray(cssObject[i].content) && cssObject[i].content.length) {
sortDeep(cssObject[i].content);
}
}
}
}
sortCss.list = {};
sortCss.each = {};
|
function sortCss(settings, cssObject) {
function sortDeep(array) {
sortCss.scope(settings, array, {
displace : [
'sass function',
'sass import',
'sass include',
'sass include arguments',
'sass mixin',
'sass include block',
'sass extend',
'property group',
]
});
for (var i = 0, n = array.length; i < n; i++) {
if (Array.isArray(array[i].content) && array[i].content.length) {
sortDeep(array[i].content);
}
}
}
sortCss.scope(settings, cssObject, {
displace : [
'sass import',
'sass include',
'sass variable assignment',
'font face',
'sass function',
'sass mixin',
'sass include block',
'sass placeholder',
]
});
if (settings.sortBlockScope) {
for (var i = 0, n = cssObject.length; i < n; i++) {
if (Array.isArray(cssObject[i].content) && cssObject[i].content.length) {
sortDeep(cssObject[i].content);
}
}
}
}
sortCss.list = {};
sortCss.each = {};
|
Call module constructor before calling inherited.
|
var Helpers = require('../helpers');
var Builtin = require('../builtin');
// Remove module methods
Class.$.appendFeatures = null;
Class.$.initialize = function(name, superclass, fn) {
var cls = Builtin(this);
if (!fn && (superclass instanceof Function)) {
fn = superclass;
superclass = undefined;
}
if (superclass === undefined) {
superclass = SuperObject;
}
if (superclass && !superclass.kindOf(Class)) {
throw new TypeError("superclass must be a Class");
}
if (superclass) {
cls.setSuperclass(Builtin(superclass));
}
$super(name, fn);
if (superclass) {
superclass.inherited(this);
}
};
Class.$.inherited = function(base) {
};
Helpers.defineGetter(Class.$, 'superclass', function() {
var klass = this.directSuperclass;
while (klass && klass.kindOf(IncludedModule)) {
klass = klass.directSuperclass;
}
return klass;
});
Class.$.toString = function() {
var name = '';
var sc = Builtin(this).singletonClassObject;
if (sc) {
sc = sc.object;
if (sc.kindOf(Class) || sc.kindOf(Module)) {
name = "#<Class:" + sc.toString() + ">";
}
} else {
name = this.moduleName;
}
return name;
};
|
var Helpers = require('../helpers');
var Builtin = require('../builtin');
// Remove module methods
Class.$.appendFeatures = null;
Class.$.initialize = function(name, superclass, fn) {
var cls = Builtin(this);
if (!fn && (superclass instanceof Function)) {
fn = superclass;
superclass = undefined;
}
if (superclass === undefined) {
superclass = SuperObject;
}
if (superclass && !superclass.kindOf(Class)) {
throw new TypeError("superclass must be a Class");
}
if (superclass) {
cls.setSuperclass(Builtin(superclass));
superclass.inherited(this);
}
$super(name, fn);
};
Class.$.inherited = function(base) {
};
Helpers.defineGetter(Class.$, 'superclass', function() {
var klass = this.directSuperclass;
while (klass && klass.kindOf(IncludedModule)) {
klass = klass.directSuperclass;
}
return klass;
});
Class.$.toString = function() {
var name = '';
var sc = Builtin(this).singletonClassObject;
if (sc) {
sc = sc.object;
if (sc.kindOf(Class) || sc.kindOf(Module)) {
name = "#<Class:" + sc.toString() + ">";
}
} else {
name = this.moduleName;
}
return name;
};
|
Set the home page as default
|
function rebuildTOC() {
var ToC =
"<div class='table-of-contents'>" +
"<h2>On this page:</h2>" +
"<ul>";
var newLine, el, title, link;
$("#content h1").each(function() {
el = $(this);
title = el.text();
link = "#" + el.attr("id");
newLine =
"<li>" +
"<a href='" + link + "'>" +
title +
"</a>" +
"</li>";
ToC += newLine;
});
ToC +=
"</ul>" +
"</div>";
return ToC;
}
$(function() {
$('#home').click(function() {
$('#content').load('content/introduction.html');
});
$('#install').click(function() {
$('#content').load('content/installmono.html', function() {
ToC = rebuildTOC();
$('#content').prepend(ToC);
});
});
$('#contact').click(function() {
window.alert("Contact details not yet available");
});
$('#license').click(function() {
window.alert("License details not yet available");
});
});
/* run after the page has loaded */
$(document).ready(function(){
$('#home').trigger('click');
});
|
function rebuildTOC() {
var ToC =
"<div class='table-of-contents'>" +
"<h2>On this page:</h2>" +
"<ul>";
var newLine, el, title, link;
$("#content h1").each(function() {
el = $(this);
title = el.text();
link = "#" + el.attr("id");
newLine =
"<li>" +
"<a href='" + link + "'>" +
title +
"</a>" +
"</li>";
ToC += newLine;
});
ToC +=
"</ul>" +
"</div>";
return ToC;
}
$(function() {
$('#home').click(function() {
$('#content').load('content/introduction.html');
});
$('#install').click(function() {
$('#content').load('content/installmono.html', function() {
ToC = rebuildTOC();
$('#content').prepend(ToC);
});
});
$('#contact').click(function() {
window.alert("Contact details not yet available");
});
$('#license').click(function() {
window.alert("License details not yet available");
});
});
|
Set the Development Status to Beta
|
#!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
from gntp.version import __version__
setup(
name='gntp',
description='Growl Notification Transport Protocol for Python',
long_description=open('README.rst').read(),
author='Paul Traylor',
url='http://github.com/kfdm/gntp/',
version=__version__,
packages=['gntp'],
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.5',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: Implementation :: PyPy',
],
entry_points={
'console_scripts': [
'gntp = gntp.cli:main'
]
}
)
|
#!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
from gntp.version import __version__
setup(
name='gntp',
description='Growl Notification Transport Protocol for Python',
long_description=open('README.rst').read(),
author='Paul Traylor',
url='http://github.com/kfdm/gntp/',
version=__version__,
packages=['gntp'],
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.5',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: Implementation :: PyPy',
],
entry_points={
'console_scripts': [
'gntp = gntp.cli:main'
]
}
)
|
Change author in about file
|
"""Central place for package metadata."""
# NOTE: We use __title__ instead of simply __name__ since the latter would
# interfere with a global variable __name__ denoting object's name.
__title__ = 'resolwe'
__summary__ = 'Open source enterprise dataflow engine in Django'
__url__ = 'https://github.com/genialis/resolwe'
# Semantic versioning is used. For more information see:
# https://packaging.python.org/en/latest/distributing/#semantic-versioning-preferred
__version__ = '10.2.0a2'
__author__ = 'Genialis, Inc.'
__email__ = 'dev-team@genialis.com'
__license__ = 'Apache License (2.0)'
__copyright__ = '2015-2018, ' + __author__
__all__ = (
'__title__', '__summary__', '__url__', '__version__', '__author__',
'__email__', '__license__', '__copyright__',
)
|
"""Central place for package metadata."""
# NOTE: We use __title__ instead of simply __name__ since the latter would
# interfere with a global variable __name__ denoting object's name.
__title__ = 'resolwe'
__summary__ = 'Open source enterprise dataflow engine in Django'
__url__ = 'https://github.com/genialis/resolwe'
# Semantic versioning is used. For more information see:
# https://packaging.python.org/en/latest/distributing/#semantic-versioning-preferred
__version__ = '10.2.0a2'
__author__ = 'Genialis d.o.o.'
__email__ = 'dev-team@genialis.com'
__license__ = 'Apache License (2.0)'
__copyright__ = '2015-2018, ' + __author__
__all__ = (
'__title__', '__summary__', '__url__', '__version__', '__author__',
'__email__', '__license__', '__copyright__',
)
|
Add default values for config
|
package co.phoenixlab.discord;
import java.util.HashSet;
import java.util.Set;
public class Configuration {
private String email;
private String password;
private String commandPrefix;
private Set<String> blacklist;
public Configuration() {
email = "";
password = "";
commandPrefix = "!";
blacklist = new HashSet<>();
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getCommandPrefix() {
return commandPrefix;
}
public void setCommandPrefix(String commandPrefix) {
this.commandPrefix = commandPrefix;
}
public Set<String> getBlacklist() {
return blacklist;
}
}
|
package co.phoenixlab.discord;
import java.util.HashSet;
import java.util.Set;
public class Configuration {
private String email;
private String password;
private String commandPrefix;
private Set<String> blacklist;
public Configuration() {
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getCommandPrefix() {
return commandPrefix;
}
public void setCommandPrefix(String commandPrefix) {
this.commandPrefix = commandPrefix;
}
public Set<String> getBlacklist() {
return blacklist;
}
}
|
Fix typo in test name
|
package org.junit.internal.matchers;
import static org.hamcrest.CoreMatchers.any;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.internal.matchers.StacktracePrintingMatcher.isException;
import static org.junit.internal.matchers.StacktracePrintingMatcher.isThrowable;
import org.junit.Test;
public class StacktracePrintingMatcherTest {
@Test
public void succeedsWhenInnerMatcherSucceeds() throws Exception {
assertTrue(isThrowable(any(Throwable.class)).matches(new Exception()));
}
@Test
public void failsWhenInnerMatcherFails() throws Exception {
assertFalse(isException(notNullValue(Exception.class)).matches(null));
}
@Test
public void assertThatIncludesStacktrace() {
Exception actual= new IllegalArgumentException("my message");
Exception expected= new NullPointerException();
try {
assertThat(actual, isThrowable(equalTo(expected)));
} catch (AssertionError e) {
assertThat(e.getMessage(), containsString("Stacktrace was: java.lang.IllegalArgumentException: my message"));
}
}
}
|
package org.junit.internal.matchers;
import static org.hamcrest.CoreMatchers.any;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.internal.matchers.StacktracePrintingMatcher.isException;
import static org.junit.internal.matchers.StacktracePrintingMatcher.isThrowable;
import org.junit.Test;
public class StacktracePrintingMatcherTest {
@Test
public void succeedsWhenInnerMatcherSuceeds() throws Exception {
assertTrue(isThrowable(any(Throwable.class)).matches(new Exception()));
}
@Test
public void failsWhenInnerMatcherFails() throws Exception {
assertFalse(isException(notNullValue(Exception.class)).matches(null));
}
@Test
public void assertThatIncludesStacktrace() {
Exception actual= new IllegalArgumentException("my message");
Exception expected= new NullPointerException();
try {
assertThat(actual, isThrowable(equalTo(expected)));
} catch (AssertionError e) {
assertThat(e.getMessage(), containsString("Stacktrace was: java.lang.IllegalArgumentException: my message"));
}
}
}
|
Fix bug with loading Module config file
|
<?php
namespace Config;
class Modules {
private $environment;
public function __construct($modules = [], $configFile = "config.json") {
$this->modules = $modules;
$this->configFile = $configFile;
}
public function getModuleSettings() {
$moduleSettings = [];
foreach ($this->modules as $moduleName) {
$moduleFile = 'Modules/' . $moduleName . '/' . $this->configFile;
if ($settings = $this->getFile($moduleFile)) $moduleSettings[] = $settings;
}
return $moduleSettings;
}
private function getFile($file) {
$fileName = __DIR__ . '/../' . $file;
if (!file_exists($fileName)) return false;
$settings = json_decode(str_replace('{dir}', dirname($file), file_get_contents($fileName)), true);
if (isset($settings['extend'])) {
$settings = array_merge($this->getFile($settings['extend']), $settings);
}
return $settings;
}
}
|
<?php
namespace Config;
class Modules {
private $environment;
public function __construct($modules = [], $configFile = "config.json") {
$this->modules = $modules;
$this->configFile = $configFile;
}
public function getModuleSettings() {
$moduleSettings = [];
foreach ($this->modules as $moduleName) {
$moduleFile = 'Modules/' . $moduleName . '/' . $this->configFile;
if ($settings = $this->getFile($moduleFile)) $moduleSettings[] = $settings;
}
return $moduleSettings;
}
private function getFile($file) {
if (!file_exists($file)) return false;
$settings = json_decode(str_replace('{dir}', dirname($file), file_get_contents($file)), true);
if (isset($settings['extend'])) {
$settings = array_merge($this->getFile($settings['extend']), $settings);
}
return $settings;
}
}
|
Add form to create a bucketlist item
|
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, TextAreaField
from wtforms.validators import DataRequired, Length, Email
class SignupForm(FlaskForm):
"""Render and validate the signup form"""
email = StringField("Email", validators=[DataRequired(), Email(message="Invalid email format"), Length(max=32)])
username = StringField("Username", validators=[DataRequired(), Length(2, 32)])
password = PasswordField("Password", validators=[DataRequired(), Length(min=4, max=32)])
class LoginForm(FlaskForm):
"""Form to let users login"""
email = StringField("Email", validators=[DataRequired(), Email(message="Invalid email format"), Length(max=32)])
password = PasswordField("Password", validators=[DataRequired(), Length(4, 32)])
remember = BooleanField("Remember Me")
class BucketlistForm(FlaskForm):
"""Form to CRUd a bucketlist"""
name = StringField("Name", validators=[DataRequired()])
description = TextAreaField("Description", validators=[DataRequired()])
class BucketlistItemForm(FlaskForm):
"""Form to CRUd a bucketlist item"""
title = StringField("Title", validators=[DataRequired()])
description = TextAreaField("Description", validators=[DataRequired()])
status = BooleanField("Status", validators=[DataRequired])
|
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, TextAreaField
from wtforms.validators import DataRequired, Length, Email
class SignupForm(FlaskForm):
"""Render and validate the signup form"""
email = StringField("Email", validators=[DataRequired(), Email(message="Invalid email format"), Length(max=32)])
username = StringField("Username", validators=[DataRequired(), Length(2, 32)])
password = PasswordField("Password", validators=[DataRequired(), Length(min=4, max=32)])
class LoginForm(FlaskForm):
"""Form to let users login"""
email = StringField("Email", validators=[DataRequired(), Email(message="Invalid email format"), Length(max=32)])
password = PasswordField("Password", validators=[DataRequired(), Length(4, 32)])
remember = BooleanField("Remember Me")
class BucketlistForm(FlaskForm):
"""Form to CRUd a bucketlist"""
name = StringField("Name", validators=[DataRequired()])
description = TextAreaField("Description", validators=[DataRequired()])
|
Remove -n in favor of --as
|
#!/usr/bin/env node
import yargs from 'yargs';
import path from 'path';
import fs from 'fs';
import * as pose from '.';
import actions from './actions';
const opts = yargs
.usage('$ pose <action> [options]')
.help('help')
.epilog(actions.trim())
.options({
name: {
alias: ['as'],
default: path.basename(process.cwd()),
desc: 'Name of template',
},
entry: {
alias: ['e'],
default: process.cwd(),
defaultDescription: 'cwd',
desc: 'Entry of template',
},
help: {
alias: ['h'],
},
}).argv;
const action = opts._[0];
if (!action) {
console.log('Type "pose help" to get started.');
process.exit();
}
[
opts._pose = path.join(process.env.HOME, '.pose'),
opts._templates = path.join(opts._pose, 'templates'),
].forEach(dir => {
fs.mkdir(dir, () => null);
});
if (typeof pose[action] === 'function') {
pose[action](opts);
} else {
console.error(`Unknown action "${action}"`);
}
export { action, opts };
|
#!/usr/bin/env node
import yargs from 'yargs';
import path from 'path';
import fs from 'fs';
import * as pose from '.';
import actions from './actions';
const opts = yargs
.usage('$ pose <action> [options]')
.help('help')
.epilog(actions.trim())
.options({
name: {
alias: ['n', 'as'],
default: path.basename(process.cwd()),
desc: 'Name of template',
},
entry: {
alias: ['e'],
default: process.cwd(),
defaultDescription: 'cwd',
desc: 'Entry of template',
},
help: {
alias: ['h'],
},
}).argv;
const action = opts._[0];
if (!action) {
console.log('Type "pose help" to get started.');
process.exit();
}
[
opts._pose = path.join(process.env.HOME, '.pose'),
opts._templates = path.join(opts._pose, 'templates'),
].forEach(dir => {
fs.mkdir(dir, () => null);
});
if (typeof pose[action] === 'function') {
pose[action](opts);
} else {
console.error(`Unknown action "${action}"`);
}
export { action, opts };
|
Fix binding of stomp endpoints
|
package no.dusken.momus.config;
import java.util.List;
import no.dusken.momus.mapper.HibernateAwareObjectMapper;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.converter.MappingJackson2MessageConverter;
import org.springframework.messaging.converter.MessageConverter;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
@Configuration
@EnableWebSocketMessageBroker
@EnableAsync
class WebsocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/ws");
config.setApplicationDestinationPrefixes("/ws");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/api/ws").setAllowedOrigins("https://momus.smint.no").withSockJS();
}
@Override
public boolean configureMessageConverters(List<MessageConverter> converters) {
MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
converter.setObjectMapper(new HibernateAwareObjectMapper());
converters.add(converter);
return false;
}
}
|
package no.dusken.momus.config;
import java.util.List;
import no.dusken.momus.mapper.HibernateAwareObjectMapper;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.converter.MappingJackson2MessageConverter;
import org.springframework.messaging.converter.MessageConverter;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
@Configuration
@EnableWebSocketMessageBroker
@EnableAsync
class WebsocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/api/ws");
config.setApplicationDestinationPrefixes("/api/ws");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/api/ws").setAllowedOrigins("https://momus.smint.no").withSockJS();
}
@Override
public boolean configureMessageConverters(List<MessageConverter> converters) {
MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
converter.setObjectMapper(new HibernateAwareObjectMapper());
converters.add(converter);
return false;
}
}
|
FIX a bug, you fuck'in forgot to rename the new function
|
'''Copyright(C): Leaf Johnson 2011
This file is part of makeclub.
makeclub 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.
makeclub 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 Affero General Public License
along with makeclub. If not, see <http://www.gnu.org/licenses/>.
'''
from google.appengine.api import users
operations = [
"listclubs",
"createClub"
]
clubOperations = [
"view",
"create",
"edit",
"delete",
"arrange",
"finish",
"newact"
]
actOperatoins = [
"view",
"edit",
"join"
]
def isAccessible (user, operation):
return True
def hasClubPrivilige (user, club, operation):
return True
def hasActPrivilige (user, act, operation):
return True
|
'''Copyright(C): Leaf Johnson 2011
This file is part of makeclub.
makeclub 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.
makeclub 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 Affero General Public License
along with makeclub. If not, see <http://www.gnu.org/licenses/>.
'''
from google.appengine.api import users
operations = [
"listclubs",
"createClub"
]
clubOperations = [
"view",
"create",
"edit",
"delete",
"arrange",
"finish"
]
actOperatoins = [
"create",
"view",
"edit",
"join"
]
def isAccessible (user, operation):
return True
def hasClubPrivilige (user, club, operation):
return True
def hasClubPrivilige (user, act, operation):
return True
|
Make sure the sort of menu items is "order"
|
var Q = require('q');
var keystone = require('keystone');
const MENUS = ['main', 'footer'];
var app;
function reload() {
var MenuItem = keystone.list('Menu item');
var menuItems = {};
Q.all(MENUS.map((menu) => {
return MenuItem.model.find({
placement: menu
})
.populate('page')
.sort('order')
.exec(function(err, items) {
menuItems[menu] = items.map((item) => {
item.url = item.getUrl();
return item;
});
});
})).then(() => {
app.set('menus', menuItems);
});
}
module.exports = function(expressApp) {
app = expressApp;
reload();
};
module.exports.reload = reload;
module.exports.MENUS = MENUS;
|
var Q = require('q');
var keystone = require('keystone');
const MENUS = ['main', 'footer'];
var app;
function reload() {
var MenuItem = keystone.list('Menu item');
var menuItems = {};
Q.all(MENUS.map((menu) => {
return MenuItem.model.find({
placement: menu
}).populate('page').exec(function(err, items) {
menuItems[menu] = items.map((item) => {
item.url = item.getUrl();
return item;
});
});
})).then(() => {
app.set('menus', menuItems);
});
}
module.exports = function(expressApp) {
app = expressApp;
reload();
};
module.exports.reload = reload;
module.exports.MENUS = MENUS;
|
Add arguments --domain and --region to mass init.
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# vim: set hls is ai et sw=4 sts=4 ts=8 nu ft=python:
# built-in modules
# 3rd-party modules
import click
# local modules
from mass.monitor.app import app
from mass.scheduler.swf import utils
from mass.scheduler.swf import SWFWorker
@click.group()
def cli():
pass
@cli.command()
@click.option('-d', '--domain', help='Amazon SWF Domain.')
@click.option('-r', '--region', help='Amazon Region.')
def init(domain, region):
utils.register_domain(domain, region)
utils.register_workflow_type(domain, region)
utils.register_activity_type(domain, region)
@cli.group()
def worker():
pass
@cli.group()
def job():
pass
@cli.group()
def monitor():
pass
@worker.command('start')
def worker_start():
worker = SWFWorker()
worker.start()
@job.command('submit')
@click.option('-j', '--json', help='Job Description in JSON.')
@click.option('-a', '--alfscript', help='Job Description in alfscript.')
def job_submit(json_script, alf_script):
pass
@monitor.command('start')
def monitor_start():
monitor = app.run(debug=True)
cli.add_command(init)
cli.add_command(worker)
cli.add_command(job)
cli.add_command(monitor)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# vim: set hls is ai et sw=4 sts=4 ts=8 nu ft=python:
# built-in modules
# 3rd-party modules
import click
# local modules
from mass.monitor.app import app
from mass.scheduler.swf import utils
from mass.scheduler.swf import SWFWorker
@click.group()
def cli():
pass
@cli.command()
def init():
utils.register_domain()
utils.register_workflow_type()
utils.register_activity_type()
@cli.group()
def worker():
pass
@cli.group()
def job():
pass
@cli.group()
def monitor():
pass
@worker.command('start')
def worker_start():
worker = SWFWorker()
worker.start()
@job.command('submit')
@click.option('-j', '--json', help='Job Description in JSON.')
@click.option('-a', '--alfscript', help='Job Description in alfscript.')
def job_submit(json_script, alf_script):
pass
@monitor.command('start')
def monitor_start():
monitor = app.run(debug=True)
cli.add_command(init)
cli.add_command(worker)
cli.add_command(job)
cli.add_command(monitor)
|
Include package data specified in MANIFEST
Not really needed, but adding it incase we do bundle other things in future
|
#!/usr/bin/env python
import os
from setuptools import find_packages, setup
def read(filename):
with open(os.path.join(os.path.dirname(__file__), filename)) as f:
return f.read()
setup(
name="devsoc-contentfiles",
version="0.3a1",
description="DEV Content Files",
long_description=read("README.rst"),
long_description_content_type="text/x-rst",
url="https://github.com/developersociety/devsoc-contentfiles",
maintainer="The Developer Society",
maintainer_email="studio@dev.ngo",
platforms=["any"],
packages=find_packages(exclude=["tests"]),
include_package_data=True,
python_requires=">=3.5",
classifiers=[
"Environment :: Web Environment",
"Framework :: Django",
"Framework :: Django :: 1.11",
"Framework :: Django :: 2.2",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
],
license="BSD",
)
|
#!/usr/bin/env python
import os
from setuptools import find_packages, setup
def read(filename):
with open(os.path.join(os.path.dirname(__file__), filename)) as f:
return f.read()
setup(
name="devsoc-contentfiles",
version="0.3a1",
description="DEV Content Files",
long_description=read("README.rst"),
long_description_content_type="text/x-rst",
url="https://github.com/developersociety/devsoc-contentfiles",
maintainer="The Developer Society",
maintainer_email="studio@dev.ngo",
platforms=["any"],
packages=find_packages(exclude=["tests"]),
python_requires=">=3.5",
classifiers=[
"Environment :: Web Environment",
"Framework :: Django",
"Framework :: Django :: 1.11",
"Framework :: Django :: 2.2",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
],
license="BSD",
)
|
Add default grid system prompt
|
'use strict';
function notEmpty(src) {
return !!src;
}
module.exports = [{
type: 'input',
name: 'name',
message: 'Project Name',
validate: notEmpty
}, {
type: 'input',
name: 'description',
message: 'Description',
validate: notEmpty
}, {
type: 'list',
name: 'engine',
message: 'Which templating engine?',
choices: [{
name: 'Handlebars',
value: 'handlebars'
}, {
name: 'DustJS',
value: 'dust'
}],
default: 'handlebars'
}, {
type: 'list',
name: 'grid',
message: 'Which grid system?',
choices: [{
name: 'Bootstrap',
value: 'bootstrap'
}, {
name: 'Susy',
value: 'susy'
}],
default: 'bootstrap'
}];
|
'use strict';
function notEmpty(src) {
return !!src;
}
module.exports = [{
type: 'input',
name: 'name',
message: 'Project Name',
validate: notEmpty
}, {
type: 'input',
name: 'description',
message: 'Description',
validate: notEmpty
}, {
type: 'list',
name: 'engine',
message: 'Which templating engine?',
choices: [{
name: 'Handlebars',
value: 'handlebars'
}, {
name: 'DustJS',
value: 'dust'
}],
default: 'handlebars'
}, {
type: 'list',
name: 'grid',
message: 'Which grid system?',
choices: [{
name: 'Bootstrap',
value: 'bootstrap'
}, {
name: 'Susy',
value: 'susy'
}]
}];
|
Use fresh event loop for asyncio test
|
# -*- coding: utf-8 -*-
import nose.tools as nt
from asyncio import Future, gather, new_event_loop, sleep
from pyee import EventEmitter
def test_async_emit():
"""Test that event_emitters can handle wrapping coroutines
"""
loop = new_event_loop()
ee = EventEmitter(loop=loop)
should_call = Future(loop=loop)
@ee.on('event')
async def event_handler():
should_call.set_result(True)
async def create_timeout(loop=loop):
await sleep(1, loop=loop)
if not should_call.done():
raise Exception('should_call timed out!')
return should_call.cancel()
timeout = create_timeout(loop=loop)
@should_call.add_done_callback
def _done(result):
nt.assert_true(result)
ee.emit('event')
loop.run_until_complete(gather(should_call, timeout, loop=loop))
|
# -*- coding: utf-8 -*-
import nose.tools as nt
from asyncio import Future, gather, get_event_loop, sleep
from pyee import EventEmitter
def test_async_emit():
"""Test that event_emitters can handle wrapping coroutines
"""
loop = get_event_loop()
ee = EventEmitter(loop=loop)
should_call = Future(loop=loop)
@ee.on('event')
async def event_handler():
should_call.set_result(True)
async def create_timeout(loop=loop):
await sleep(1, loop=loop)
if not should_call.done():
raise Exception('should_call timed out!')
return should_call.cancel()
timeout = create_timeout(loop=loop)
@should_call.add_done_callback
def _done(result):
nt.assert_true(result)
ee.emit('event')
loop.run_until_complete(gather(should_call, timeout))
|
Refactor coursera tool. Add getAdjacencylist function.
lzhoucs|G580|Win8|WebStorm9
|
var http = require('http');
var courseraHttpHandler = function(url, processor, callback) {
http.get(url, function(response) {
var str = '';
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
var processedStr = str.trim().split('\r\n').map( processor );
callback( processedStr );
});
});
}
var strToInt = function (str) {
return parseInt(str);
}
/*
* Convert from coursera sample format to javascript array.
* e.g :
*
* a.txt :
*
* 111
* 222
* 333
* 444
*
* converts to
*
* [111,222,333,444]
* */
exports.getNumberArray = function (url, callback) {
courseraHttpHandler(url, strToInt, callback);
};
exports.getAdjacencylist = function (url, callback) {
courseraHttpHandler(url, function (str) {
return str.trim().split('\t').map( strToInt );
}, callback);
}
|
var http = require('http');
/*
* Convert from coursera sample format to javascript array.
* e.g :
*
* a.txt :
*
* 111
* 222
* 333
* 444
*
* converts to
*
* [111,222,333,444]
* */
var strToArray = function(str) {
return str.trim().split('\r\n').map(function (elStr) {
return parseInt(elStr);
})
}
function simpleHttpHandler(url, callback) {
http.get(url, function(response) {
var str = '';
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
callback( str )
});
});
}
exports.getNumberArray = function (url, callback) {
simpleHttpHandler(url, function (str) {
var numberArry = str.trim().split('\r\n').map(function (elStr) {
return parseInt(elStr);
})
callback(numberArry);
});
};
|
Fix ordering of category view
Signed-off-by: Michal Čihař <a2df1e659c9fd2578de0a26565357cb273292eeb@cihar.com>
|
from django.shortcuts import get_object_or_404
from django.views.generic.dates import ArchiveIndexView
from django.views.generic.edit import FormView
from .models import Entry, Category
from .forms import ContactForm
class CategoryView(ArchiveIndexView):
model = Entry
date_field = 'date'
paginate_by = 20
template_name = 'posts/entry_category.html'
def get(self, request, slug, **kwargs):
self.kwargs['category'] = get_object_or_404(Category, slug=slug)
return super().get(request, kwargs)
def get_queryset(self):
return super().get_queryset().filter(category=self.kwargs['category'])
def get_context_data(self, **kwargs):
result = super().get_context_data(**kwargs)
result['category'] = self.kwargs['category']
return result
class ContactView(FormView):
template_name = 'contact.html'
form_class = ContactForm
success_url = '/kontakt/'
def form_valid(self, form):
# This method is called when valid form data has been POSTed.
# It should return an HttpResponse.
form.send_email()
return super().form_valid(form)
|
from django.shortcuts import get_object_or_404
from django.views.generic.dates import ArchiveIndexView
from django.views.generic.edit import FormView
from .models import Entry, Category
from .forms import ContactForm
class CategoryView(ArchiveIndexView):
model = Entry
date_field = 'date'
paginate_by = 20
template_name = 'posts/entry_category.html'
def get(self, request, slug, **kwargs):
self.kwargs['category'] = get_object_or_404(Category, slug=slug)
return super().get(request, kwargs)
def get_queryset(self):
return Entry.objects.filter(category=self.kwargs['category'])
def get_context_data(self, **kwargs):
result = super().get_context_data(**kwargs)
result['category'] = self.kwargs['category']
return result
class ContactView(FormView):
template_name = 'contact.html'
form_class = ContactForm
success_url = '/kontakt/'
def form_valid(self, form):
# This method is called when valid form data has been POSTed.
# It should return an HttpResponse.
form.send_email()
return super().form_valid(form)
|
Add a version number for scattering.
|
from numpy.distutils.core import setup
from numpy.distutils.misc_util import Configuration
from numpy.distutils.system_info import get_info
from os.path import join
flags = ['-W', '-Wall', '-march=opteron', '-O3']
def configuration(parent_package='', top_path=None):
config = Configuration('scattering', parent_package, top_path,
version='0.8',
author = 'Ryan May',
author_email = 'rmay31@gmail.com',
platforms = ['Linux'],
description = 'Software for simulating weather radar data.',
url = 'http://weather.ou.edu/~rmay/research.html')
lapack = get_info('lapack_opt')
sources = ['ampld.lp.pyf', 'ampld.lp.f', 'modified_double_precision_drop.f']
config.add_extension('_tmatrix', [join('src', f) for f in sources],
extra_compile_args=flags, **lapack)
return config
setup(**configuration(top_path='').todict())
|
from numpy.distutils.core import setup
from numpy.distutils.misc_util import Configuration
from numpy.distutils.system_info import get_info
from os.path import join
flags = ['-W', '-Wall', '-march=opteron', '-O3']
def configuration(parent_package='', top_path=None):
config = Configuration('scattering', parent_package, top_path,
author = 'Ryan May',
author_email = 'rmay31@gmail.com',
platforms = ['Linux'],
description = 'Software for simulating weather radar data.',
url = 'http://weather.ou.edu/~rmay/research.html')
lapack = get_info('lapack_opt')
sources = ['ampld.lp.pyf', 'ampld.lp.f', 'modified_double_precision_drop.f']
config.add_extension('_tmatrix', [join('src', f) for f in sources],
extra_compile_args=flags, **lapack)
return config
setup(**configuration(top_path='').todict())
|
Add missing Ouzo copyright notice
|
<?php
/*
* Copyright (c) Ouzo contributors, http://ouzoframework.org
* This file is made available under the MIT License (view the LICENSE file for more information).
*/
use Doctrine\Common\Annotations\AnnotationReader;
use Ouzo\Routing\Generator\RouteFileGenerator;
use Ouzo\Routing\Loader\AnnotationClassLoader;
use Ouzo\Routing\Loader\AnnotationDirectoryLoader;
use Ouzo\Utilities\Path;
use PHPUnit\Framework\TestCase;
class RouteFileGeneratorTest extends TestCase
{
/**
* @test
*/
public function shouldGenerateRouteFileTemplate()
{
//given
$reader = new AnnotationReader();
$classLoader = new AnnotationClassLoader($reader);
$directoryLoader = new AnnotationDirectoryLoader($classLoader);
$routeFileGenerator = new RouteFileGenerator($directoryLoader);
$path = Path::joinWithTemp('GeneratedRoutes.php');
//when
$result = $routeFileGenerator->generate($path, [__DIR__ . '/../Fixtures/Annotation']);
//then
$this->assertIsInt($result);
$this->assertEquals($result, strlen(file_get_contents($path)));
}
}
|
<?php
use Doctrine\Common\Annotations\AnnotationReader;
use Ouzo\Routing\Generator\RouteFileGenerator;
use Ouzo\Routing\Loader\AnnotationClassLoader;
use Ouzo\Routing\Loader\AnnotationDirectoryLoader;
use Ouzo\Utilities\Path;
use PHPUnit\Framework\TestCase;
class RouteFileGeneratorTest extends TestCase
{
/**
* @test
*/
public function shouldGenerateRouteFileTemplate()
{
//given
$reader = new AnnotationReader();
$classLoader = new AnnotationClassLoader($reader);
$directoryLoader = new AnnotationDirectoryLoader($classLoader);
$routeFileGenerator = new RouteFileGenerator($directoryLoader);
$path = Path::joinWithTemp('GeneratedRoutes.php');
//when
$result = $routeFileGenerator->generate($path, [__DIR__ . '/../Fixtures/Annotation']);
//then
$this->assertIsInt($result);
$this->assertEquals($result, strlen(file_get_contents($path)));
}
}
|
[JSON] Use type-switch for error field
|
package logrus
import (
"encoding/json"
"fmt"
"time"
)
type JSONFormatter struct{}
func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {
data := make(Fields, len(entry.Data)+3)
for k, v := range entry.Data {
switch v := v.(type) {
case error:
// Otherwise errors are ignored by `encoding/json`
// https://github.com/Sirupsen/logrus/issues/137
data[k] = v.Error()
default:
data[k] = v
}
}
prefixFieldClashes(data)
data["time"] = entry.Time.Format(time.RFC3339)
data["msg"] = entry.Message
data["level"] = entry.Level.String()
serialized, err := json.Marshal(data)
if err != nil {
return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
}
return append(serialized, '\n'), nil
}
|
package logrus
import (
"encoding/json"
"fmt"
"time"
)
type JSONFormatter struct{}
func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {
data := make(Fields, len(entry.Data)+3)
for k, v := range entry.Data {
// Otherwise errors are ignored by `encoding/json`
// https://github.com/Sirupsen/logrus/issues/137
if err, ok := v.(error); ok {
data[k] = err.Error()
} else {
data[k] = v
}
}
prefixFieldClashes(data)
data["time"] = entry.Time.Format(time.RFC3339)
data["msg"] = entry.Message
data["level"] = entry.Level.String()
serialized, err := json.Marshal(data)
if err != nil {
return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
}
return append(serialized, '\n'), nil
}
|
Use plugin language and prepare for save/update action
|
<?php
namespace ContentTranslator;
class Meta Extends Entity\Translate
{
public function __construct()
{
// Get actions
add_filter('get_post_metadata',array($this,'get'),4,1);
// Add and update actions
foreach (array('add','update') as $action) {
add_filter($action . '_post_metadata', array($this, 'save'));
}
}
public function save(null, $object_id, $meta_key, $single ) {
return null;
}
public function get(null, $object_id, $meta_key, $single )
{
if(!$this->isLangualMeta($meta_key)) {
return get_metadata('post', $object_id, $this->createLangualMetaKey($meta_key), $single);
}
return null;
}
private function isLangualMeta($meta_key) {
return substr($meta_key, -strlen("_".\ContentTranslator\Switcher::$currentLanguage->code) == "_".\ContentTranslator\Switcher::$currentLanguage->code ? true : false;
}
private function createLangualMetaKey ($meta_key) {
return $meta_key."_".\ContentTranslator\Switcher::$currentLanguage->code;
}
}
|
<?php
namespace ContentTranslator;
class Meta Extends Entity\Translate
{
protected $lang;
public function __construct()
{
$this->lang = "en";
add_filter('get_post_metadata',array($this,'get'),4,1);
}
public function save() {
}
public function get(null, $object_id, $meta_key, $single ) {
if(!$this->isLangualMeta($meta_key)) {
return get_metadata('post', $object_id, $this->createLangualMetaKey($meta_key), $single);
}
return null;
}
private function isLangualMeta($meta_key) {
return substr($meta_key, -strlen("_".$this->lang)) == "_".$this->lang ? true : false;
}
private function createLangualMetaKey ($meta_key) {
return $meta_key."_".$this->lang;
}
}
|
Remove source maps and comments from production
|
'use strict';
import gulp from 'gulp';
import sass from 'gulp-sass';
import gulpif from 'gulp-if';
import browserSync from 'browser-sync';
import autoprefixer from 'gulp-autoprefixer';
import handleErrors from '../util/handle-errors';
import config from '../config';
gulp.task('sass', function() {
return gulp.src(config.styles.src)
.pipe(sass({
sourceComments: global.isProd ? false : 'map',
sourceMap: global.isProd ? false : 'sass',
outputStyle: global.isProd ? 'compressed' : 'nested'
}))
.on('error', handleErrors)
.pipe(autoprefixer('last 2 versions', '> 1%', 'ie 8'))
.pipe(gulp.dest(config.styles.dest))
.pipe(gulpif(browserSync.active, browserSync.reload({ stream: true })));
});
|
'use strict';
import gulp from 'gulp';
import sass from 'gulp-sass';
import gulpif from 'gulp-if';
import browserSync from 'browser-sync';
import autoprefixer from 'gulp-autoprefixer';
import handleErrors from '../util/handle-errors';
import config from '../config';
gulp.task('sass', function() {
return gulp.src(config.styles.src)
.pipe(sass({
sourceComments: global.isProd ? 'none' : 'map',
sourceMap: 'sass',
outputStyle: global.isProd ? 'compressed' : 'nested'
}))
.on('error', handleErrors)
.pipe(autoprefixer('last 2 versions', '> 1%', 'ie 8'))
.pipe(gulp.dest(config.styles.dest))
.pipe(gulpif(browserSync.active, browserSync.reload({ stream: true })));
});
|
Fix null pointer exception because of the missing value assignment.
|
package com.obidea.semantika.mapping.parser.r2rml;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.obidea.semantika.util.StringUtils;
public class R2RmlTemplate
{
private static final Pattern columnInCurlyBraces = Pattern.compile("\\{([^\\}]+)\\}");
private int mIndex = 1;
private String mTemplateString;
private List<String> mColumnNames = new ArrayList<String>();
public R2RmlTemplate(String templateString)
{
mTemplateString = templateString;
process(templateString);
}
public String getTemplateString()
{
return mTemplateString;
}
public List<String> getColumnNames()
{
return mColumnNames;
}
private void process(String templateString)
{
Matcher m = columnInCurlyBraces.matcher(templateString);
while (m.find()) {
String arg = m.group(2);
if (!StringUtils.isEmpty(arg)) {
mTemplateString.replace(arg, mIndex+"");
mColumnNames.add(arg);
mIndex++;
}
}
}
}
|
package com.obidea.semantika.mapping.parser.r2rml;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.obidea.semantika.util.StringUtils;
public class R2RmlTemplate
{
private static final Pattern columnInCurlyBraces = Pattern.compile("\\{([^\\}]+)\\}");
private int mIndex = 1;
private String mTemplateString;
private List<String> mColumnNames = new ArrayList<String>();
public R2RmlTemplate(String templateString)
{
process(templateString);
}
public String getTemplateString()
{
return mTemplateString;
}
public List<String> getColumnNames()
{
return mColumnNames;
}
private void process(String templateString)
{
Matcher m = columnInCurlyBraces.matcher(templateString);
while (m.find()) {
String arg = m.group(2);
if (!StringUtils.isEmpty(arg)) {
mTemplateString.replace(arg, mIndex+"");
mColumnNames.add(arg);
mIndex++;
}
}
}
}
|
Allow passing extra args to function matchers
|
'use strict';
var minimatch = require('minimatch');
var anymatch = function(criteria, value, returnIndex, startIndex, endIndex) {
if (!Array.isArray(criteria)) { criteria = [criteria]; }
var string = Array.isArray(value) ? value[0] : value;
if (arguments.length === 1) { return anymatch.bind(null, criteria); }
if (startIndex == null) { startIndex = 0; }
var matchIndex = -1;
function testCriteria (criterion, index) {
var result;
switch (toString.call(criterion)) {
case '[object String]':
result = string === criterion || minimatch(string, criterion);
break;
case '[object RegExp]':
result = criterion.test(string);
break;
case '[object Function]':
result = criterion.apply(null, Array.isArray(value) ? value : [value]);
break;
default:
result = false;
}
if (result) { matchIndex = index + startIndex; }
return result;
}
var matched = criteria.slice(startIndex, endIndex).some(testCriteria);
return returnIndex === true ? matchIndex : matched;
};
module.exports = anymatch;
|
'use strict';
var minimatch = require('minimatch');
var anymatch = function(criteria, string, returnIndex, startIndex, endIndex) {
if (!Array.isArray(criteria)) { criteria = [criteria]; }
if (arguments.length === 1) { return anymatch.bind(null, criteria); }
if (startIndex == null) { startIndex = 0; }
var matchIndex = -1;
function testCriteria (criterion, index) {
var result;
switch (toString.call(criterion)) {
case '[object String]':
result = string === criterion || minimatch(string, criterion);
break;
case '[object RegExp]':
result = criterion.test(string);
break;
case '[object Function]':
result = criterion(string);
break;
default:
result = false;
}
if (result) { matchIndex = index + startIndex; }
return result;
}
var matched = criteria.slice(startIndex, endIndex).some(testCriteria);
return returnIndex === true ? matchIndex : matched;
};
module.exports = anymatch;
|
Transform timestamps on messages to Date objects.
|
'use strict';
const ActionTypes = require('../constants').ActionTypes;
const Dispatcher = require('../dispatcher');
const { List, Map } = require('immutable');
const Store = require('./store');
let unconfirmedMessages = List();
let messages = Map();
//transform a message before saving it.
let transformMessage = function(msg){
msg.created_at = new Date(msg.created_at);
msg.last_online_at = new Date(msg.last_online_at);
return msg
}
class ChatMessagesStore extends Store {
constructor() {
this.dispatchToken = Dispatcher.register((action) => {
switch (action.actionType) {
case ActionTypes.CHAT_MESSAGES_RECEIVED:
messages = messages.set(action.channel, List(action.messages).map(transformMessage);
break;
case ActionTypes.CHAT_SERVER_MESSAGE_RECEIVED:
messages = messages.set(action.channel, messages.get(action.channel, List()).push(transformMessage(action.message)));
break;
case ActionTypes.CHAT_MESSAGE_SUBMITTED:
unconfirmedMessages = unconfirmedMessages.push(action.message);
break;
default:
return;
}
this.emitChange();
});
}
getMessages(channel) {
return messages.get(channel) || List();
}
};
module.exports = new ChatMessagesStore();
|
'use strict';
const ActionTypes = require('../constants').ActionTypes;
const Dispatcher = require('../dispatcher');
const { List, Map } = require('immutable');
const Store = require('./store');
let unconfirmedMessages = List();
let messages = Map();
class ChatMessagesStore extends Store {
constructor() {
this.dispatchToken = Dispatcher.register((action) => {
switch (action.actionType) {
case ActionTypes.CHAT_MESSAGES_RECEIVED:
messages = messages.set(action.channel, List(action.messages) );
break;
case ActionTypes.CHAT_SERVER_MESSAGE_RECEIVED:
messages = messages.set(action.channel, messages.get(action.channel, List()).push(action.message));
break;
case ActionTypes.CHAT_MESSAGE_SUBMITTED:
unconfirmedMessages = unconfirmedMessages.push(action.message);
break;
default:
return;
}
this.emitChange();
});
}
getMessages(channel) {
return messages.get(channel) || List();
}
};
module.exports = new ChatMessagesStore();
|
Fix for broken container security test
|
from tests.base import BaseTest
from tenable_io.api.models import ScTestJob
class TestScTestJobsApi(BaseTest):
def test_status(self, client, image):
jobs = client.sc_test_jobs_api.list()
assert len(jobs) > 0, u'At least one job exists.'
test_job = client.sc_test_jobs_api.status(jobs[0].job_id)
assert isinstance(test_job, ScTestJob), u'The method returns type.'
def test_by_image(self, client, image):
job = client.sc_test_jobs_api.by_image(image['id'])
assert isinstance(job, ScTestJob), u'The method returns type.'
def test_by_image_digest(self, client, image):
job = client.sc_test_jobs_api.by_image_digest(image['digest'])
assert isinstance(job, ScTestJob), u'The method returns type.'
def test_list(self, client, image):
jobs = client.sc_test_jobs_api.list()
assert len(jobs) > 0, u'At least one job exists.'
assert isinstance(jobs[0], ScTestJob), u'The method returns job list.'
|
from tests.base import BaseTest
from tenable_io.api.models import ScTestJob
class TestScTestJobsApi(BaseTest):
def test_status(self, client, image):
jobs = client.sc_test_jobs_api.list()
assert len(jobs) > 0, u'At least one job exists.'
test_job = client.sc_test_jobs_api.status(jobs[0].job_id)
assert isinstance(test_job, ScTestJob), u'The method returns type.'
def test_by_image(self, client, image):
job = client.sc_test_jobs_api.by_image(image['id'])
assert isinstance(job, ScTestJob), u'The method returns type.'
def test_by_image_digest(self, client, image):
job = client.sc_test_jobs_api.by_image(image['digest'])
assert isinstance(job, ScTestJob), u'The method returns type.'
def test_list(self, client, image):
jobs = client.sc_test_jobs_api.list()
assert len(jobs) > 0, u'At least one job exists.'
assert isinstance(jobs[0], ScTestJob), u'The method returns job list.'
|
Comment out dotenv for heroku deployment
|
'use strict';
var express = require('express');
var routes = require('./app/routes/index.js');
var mongoose = require('mongoose');
var passport = require('passport');
var session = require('express-session');
var bodyParser = require('body-parser')
var app = express();
// require('dotenv').load();
require('./app/config/passport')(passport);
mongoose.connect(process.env.MONGO_URI);
mongoose.Promise = global.Promise;
// Configure server to parse JSON for us
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use('/controllers', express.static(process.cwd() + '/app/controllers'));
app.use('/public', express.static(process.cwd() + '/public'));
app.use(session({
secret: 'secretClementine',
resave: false,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
routes(app, passport);
var port = process.env.PORT || 8080;
app.listen(port, function () {
console.log('Node.js listening on port ' + port + '...');
});
|
'use strict';
var express = require('express');
var routes = require('./app/routes/index.js');
var mongoose = require('mongoose');
var passport = require('passport');
var session = require('express-session');
var bodyParser = require('body-parser')
var app = express();
require('dotenv').load();
require('./app/config/passport')(passport);
mongoose.connect(process.env.MONGO_URI);
mongoose.Promise = global.Promise;
// Configure server to parse JSON for us
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use('/controllers', express.static(process.cwd() + '/app/controllers'));
app.use('/public', express.static(process.cwd() + '/public'));
app.use(session({
secret: 'secretClementine',
resave: false,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
routes(app, passport);
var port = process.env.PORT || 8080;
app.listen(port, function () {
console.log('Node.js listening on port ' + port + '...');
});
|
Comment out some hub tests, as they do not currently work
|
"""Test Moksha's Hub """
#from nose.tools import eq_, assert_true
#from moksha.hub import MokshaHub
#
#class TestHub:
#
# def setUp(self):
# self.hub = MokshaHub()
#
# def tearDown(self):
# self.hub.close()
#
# def test_creating_queue(self):
# self.hub.create_queue('test')
# eq_(len(self.hub.queues), 1)
#
# def test_delete_queue(self):
# """ Test deleting a queue """
# def test_subscription(self):
# """ Test subscribing to a queue """
# def test_unsubscribing(self):
# """ Test unsubscribing to a queue """
# def test_sending_message(self):
# """ Test sending a simple message """
# def test_receiving_message(self):
# """ Test receiving a message """
# def test_query(self):
# """ Test querying queues """
|
"""Test Moksha's Hub """
from nose.tools import eq_, assert_true
from moksha.hub import MokshaHub
class TestHub:
def setUp(self):
self.hub = MokshaHub()
def tearDown(self):
self.hub.close()
def test_creating_queue(self):
self.hub.create_queue('test')
eq_(len(self.hub.queues), 1)
def test_delete_queue(self):
""" Test deleting a queue """
def test_subscription(self):
""" Test subscribing to a queue """
def test_unsubscribing(self):
""" Test unsubscribing to a queue """
def test_sending_message(self):
""" Test sending a simple message """
def test_receiving_message(self):
""" Test receiving a message """
def test_query(self):
""" Test querying queues """
|
Enable selecting text in Differential shield and gap
Test Plan:
Selected text in shield.
Selected text in right side.
Reviewers: epriestley, btrahan
Reviewed By: btrahan
CC: aran, Korvin
Differential Revision: https://secure.phabricator.com/D3522
|
/**
* @provides javelin-behavior-differential-user-select
* @requires javelin-behavior
* javelin-dom
* javelin-stratcom
*/
JX.behavior('differential-user-select', function() {
var unselectable;
function isOnRight(node) {
return node.previousSibling &&
node.parentNode.firstChild != node.previousSibling;
}
JX.Stratcom.listen(
'mousedown',
null,
function(e) {
var key = 'differential-unselectable';
if (unselectable) {
JX.DOM.alterClass(unselectable, key, false);
}
var diff = e.getNode('differential-diff');
var td = e.getNode('tag:td');
if (diff && td && isOnRight(td)) {
unselectable = diff;
JX.DOM.alterClass(diff, key, true);
}
});
});
|
/**
* @provides javelin-behavior-differential-user-select
* @requires javelin-behavior
* javelin-dom
* javelin-stratcom
*/
JX.behavior('differential-user-select', function() {
var unselectable;
function isOnRight(node) {
return node.parentNode.firstChild != node.previousSibling;
}
JX.Stratcom.listen(
'mousedown',
null,
function(e) {
var key = 'differential-unselectable';
if (unselectable) {
JX.DOM.alterClass(unselectable, key, false);
}
var diff = e.getNode('differential-diff');
var td = e.getNode('tag:td');
if (diff && td && isOnRight(td)) {
unselectable = diff;
JX.DOM.alterClass(diff, key, true);
}
});
});
|
Remove unneeded import of HelpFormatter.
|
# main: loader of all the command entry points.
import sys
import traceback
from pkg_resources import iter_entry_points
from rasterio.rio.cli import BrokenCommand, cli
# Find and load all entry points in the rasterio.rio_commands group.
# This includes the standard commands included with Rasterio as well
# as commands provided by other packages.
#
# At a mimimum, commands must use the rasterio.rio.cli.cli command
# group decorator like so:
#
# from rasterio.rio.cli import cli
#
# @cli.command()
# def foo(...):
# ...
for entry_point in iter_entry_points('rasterio.rio_commands'):
try:
entry_point.load()
except Exception:
# Catch this so a busted plugin doesn't take down the CLI.
# Handled by registering a dummy command that does nothing
# other than explain the error.
cli.add_command(
BrokenCommand(entry_point.name))
|
# main: loader of all the command entry points.
import sys
import traceback
from click.formatting import HelpFormatter
from pkg_resources import iter_entry_points
from rasterio.rio.cli import BrokenCommand, cli
# Find and load all entry points in the rasterio.rio_commands group.
# This includes the standard commands included with Rasterio as well
# as commands provided by other packages.
#
# At a mimimum, commands must use the rasterio.rio.cli.cli command
# group decorator like so:
#
# from rasterio.rio.cli import cli
#
# @cli.command()
# def foo(...):
# ...
for entry_point in iter_entry_points('rasterio.rio_commands'):
try:
entry_point.load()
except Exception:
# Catch this so a busted plugin doesn't take down the CLI.
# Handled by registering a dummy command that does nothing
# other than explain the error.
cli.add_command(
BrokenCommand(entry_point.name))
|
Add check for nil response
The app was erroring on missing statusCode when no response
was received. This allows the app not to crash if the url
doesn't respond.
|
var url = require('url')
var dashButton = require('node-dash-button');
var request = require('request')
function DasherButton(button) {
var options = {headers: button.headers, body: button.body, json: button.json}
this.dashButton = dashButton(button.address, button.interface)
this.dashButton.on("detected", function() {
console.log(button.name + " pressed.")
doRequest(button.url, button.method, options)
})
console.log(button.name + " added.")
}
function doRequest(requestUrl, method, options, callback) {
options = options || {}
options.query = options.query || {}
options.json = options.json || false
options.headers = options.headers || {}
var reqOpts = {
url: url.parse(requestUrl),
method: method || 'GET',
qs: options.query,
body: options.body,
json: options.json,
headers: options.headers
}
request(reqOpts, function onResponse(error, response, body) {
if (error) {
console.log("there was an error");
console.log(error);
}
if (response && response.statusCode === 401) {
console.log("Not authenticated");
console.log(error);
}
if (response && response.statusCode !== 200) {
console.log("Not a 200");
console.log(error);
}
if (callback) {
callback(error, response, body)
}
})
}
module.exports = DasherButton
|
var url = require('url')
var dashButton = require('node-dash-button');
var request = require('request')
function DasherButton(button) {
var options = {headers: button.headers, body: button.body, json: button.json}
this.dashButton = dashButton(button.address, button.interface)
this.dashButton.on("detected", function() {
console.log(button.name + " pressed.")
doRequest(button.url, button.method, options)
})
console.log(button.name + " added.")
}
function doRequest(requestUrl, method, options, callback) {
options = options || {}
options.query = options.query || {}
options.json = options.json || false
options.headers = options.headers || {}
var reqOpts = {
url: url.parse(requestUrl),
method: method || 'GET',
qs: options.query,
body: options.body,
json: options.json,
headers: options.headers
}
request(reqOpts, function onResponse(error, response, body) {
if (error) {
console.log("there was an error");
console.log(error);
}
if (response.statusCode === 401) {
console.log("Not authenticated");
console.log(error);
}
if (response.statusCode !== 200) {
console.log("Not a 200");
console.log(error);
}
if (callback) {
callback(error, response, body)
}
})
}
module.exports = DasherButton
|
[API] Sort CVE by published_at attribute.
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Freshermeat - An open source software directory and release tracker.
# Copyright (C) 2017-2019 Cédric Bonhomme - https://www.cedricbonhomme.org
#
# For more information : https://gitlab.com/cedric/Freshermeat
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from bootstrap import manager
from web import models
from web.views.api.v1 import processors
from web.views.api.v1.common import url_prefix
def pre_get_many(search_params=None, **kw):
order_by = [{"field":"published_at", "direction":"desc"}]
if 'order_by' not in search_params:
search_params['order_by'] = []
search_params['order_by'].extend(order_by)
blueprint_cve = manager.create_api_blueprint(
models.CVE,
url_prefix=url_prefix,
methods=['GET'],
preprocessors=dict(
GET_MANY=[pre_get_many]))
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Freshermeat - An open source software directory and release tracker.
# Copyright (C) 2017-2019 Cédric Bonhomme - https://www.cedricbonhomme.org
#
# For more information : https://gitlab.com/cedric/Freshermeat
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from bootstrap import manager
from web import models
from web.views.api.v1 import processors
from web.views.api.v1.common import url_prefix
blueprint_cve = manager.create_api_blueprint(
models.CVE,
url_prefix=url_prefix,
methods=['GET'])
|
Update test case for 2014
|
import unittest2
import datetime
from google.appengine.ext import testbed
from datafeeds.datafeed_fms import DatafeedFms
class TestDatafeedFmsTeams(unittest2.TestCase):
def setUp(self):
self.testbed = testbed.Testbed()
self.testbed.activate()
self.testbed.init_urlfetch_stub()
self.testbed.init_memcache_stub()
self.datafeed = DatafeedFms()
def tearDown(self):
self.testbed.deactivate()
def test_getFmsTeamList(self):
teams = self.datafeed.getFmsTeamList()
self.find177(teams)
def find177(self, teams):
found_177 = False
for team in teams:
if team.team_number == 177:
found_177 = True
self.assertEqual(team.name, "ClearEdge Power / United Technologies / Gain Talent / EBA&D & South Windsor High School")
#self.assertEqual(team.address, u"South Windsor, CT, USA")
self.assertEqual(team.nickname, "Bobcat Robotics")
self.assertTrue(found_177)
self.assertTrue(len(teams) > 0)
|
import unittest2
import datetime
from google.appengine.ext import testbed
from datafeeds.datafeed_fms import DatafeedFms
class TestDatafeedFmsTeams(unittest2.TestCase):
def setUp(self):
self.testbed = testbed.Testbed()
self.testbed.activate()
self.testbed.init_urlfetch_stub()
self.testbed.init_memcache_stub()
self.datafeed = DatafeedFms()
def tearDown(self):
self.testbed.deactivate()
def test_getFmsTeamList(self):
teams = self.datafeed.getFmsTeamList()
self.find177(teams)
def find177(self, teams):
found_177 = False
for team in teams:
if team.team_number == 177:
found_177 = True
self.assertEqual(team.name, "UTC / Ensign Bickford Aerospace & Defense & South Windsor High School")
#self.assertEqual(team.address, u"South Windsor, CT, USA")
self.assertEqual(team.nickname, "Bobcat Robotics")
self.assertTrue(found_177)
self.assertTrue(len(teams) > 0)
|
Rework the pip runner to use `PathFinder`
This makes it possible to only "replace" `pip` and have the submodules
get correctly located by the regular importlib machinery. This also
asserts that it was able to locate the module, ensuring that failure to
locate the module results in an exception.
|
"""Execute exactly this copy of pip, within a different environment.
This file is named as it is, to ensure that this module can't be imported via
an import statement.
"""
import runpy
import sys
import types
from importlib.machinery import ModuleSpec, PathFinder
from os.path import dirname
from typing import Optional, Sequence, Union
PIP_SOURCES_ROOT = dirname(dirname(__file__))
class PipImportRedirectingFinder:
@classmethod
def find_spec(
self,
fullname: str,
path: Optional[Sequence[Union[bytes, str]]] = None,
target: Optional[types.ModuleType] = None,
) -> Optional[ModuleSpec]:
if fullname != "pip":
return None
spec = PathFinder.find_spec(fullname, [PIP_SOURCES_ROOT], target)
assert spec, (PIP_SOURCES_ROOT, fullname)
return spec
sys.meta_path.insert(0, PipImportRedirectingFinder())
assert __name__ == "__main__", "Cannot run __pip-runner__.py as a non-main module"
runpy.run_module("pip", run_name="__main__", alter_sys=True)
|
"""Execute exactly this copy of pip, within a different environment.
This file is named as it is, to ensure that this module can't be imported via
an import statement.
"""
import importlib.util
import runpy
import sys
import types
from importlib.machinery import ModuleSpec
from os.path import dirname, join
from typing import Optional, Sequence, Union
PIP_SOURCES_ROOT = dirname(dirname(dirname(__file__)))
class PipImportRedirectingFinder:
@classmethod
def find_spec(
self,
fullname: str,
path: Optional[Sequence[Union[bytes, str]]] = None,
target: Optional[types.ModuleType] = None,
) -> Optional[ModuleSpec]:
if not fullname.startswith("pip."):
return None
# Import pip from the source directory of this file
location = join(PIP_SOURCES_ROOT, *fullname.split("."))
return importlib.util.spec_from_file_location(fullname, location)
sys.meta_path.insert(0, PipImportRedirectingFinder())
assert __name__ == "__main__", "Cannot run __pip-runner__.py as a non-main module"
runpy.run_module("pip", run_name="__main__")
|
Use `datetime` Instead of `date`
|
<?php if(!defined('KIRBY')) exit ?>
title: Comment
pages: false
files: false
icon: comment
fields:
name:
label: Name
type: text
required: true
width: 1/2
icon: user
validate:
max: 64
date:
label: Date
type: datetime
width: 1/2
validate:
date
email:
label: Email Address
type: email
width: 1/2
validate:
max: 64
email
url:
label: Website Address
type: url
width: 1/2
validate:
max: 64
text:
label: Text
required: true
type: textarea
validate:
max: 1000
|
<?php if(!defined('KIRBY')) exit ?>
title: Comment
pages: false
files: false
icon: comment
fields:
name:
label: Name
type: text
required: true
width: 1/2
icon: user
validate:
max: 64
date:
label: Date
type: date
width: 1/2
validate:
date
email:
label: Email Address
type: email
width: 1/2
validate:
max: 64
email
url:
label: Website Address
type: url
width: 1/2
validate:
max: 64
text:
label: Text
required: true
type: textarea
validate:
max: 1000
|
Refactor error as a property.
|
"""Test module for pbs client."""
from mock import MagicMock
import pbclient
class TestDefault(object):
"""Test class for pbs.helpers."""
config = MagicMock()
config.server = 'http://server'
config.api_key = 'apikey'
config.pbclient = pbclient
config.project = {'name': 'name',
'description': 'description',
'short_name': 'short_name'}
def tearDown(self):
"""Tear down method."""
self.error['status'] = 'failed'
@property
def error(self, action='GET',
exception_cls='NotFound',
exception_msg='(NotFound)',
status='failed',
status_code=404,
target='/api/app'):
"""Error property."""
return {'action': action,
'exception_cls': exception_cls,
'exception_msg': exception_msg,
'status': status,
'status_code': status_code,
'target': target}
|
from mock import MagicMock
import pbclient
class TestDefault(object):
"""Test class for pbs.helpers."""
error = {"action": "GET",
"exception_cls": "NotFound",
"exception_msg": "(NotFound)",
"status": "failed",
"status_code": 404,
"target": "/api/app"}
config = MagicMock()
config.server = 'http://server'
config.api_key = 'apikey'
config.pbclient = pbclient
config.project = {'name': 'name',
'description': 'description',
'short_name': 'short_name'}
def tearDown(self):
self.error['status'] = 'failed'
|
Implement open file and get file contents functionality
|
import os
def createDirectory(directoryPath):
if os.path.isdir(directoryPath) is False and os.path.exists(directoryPath) is False:
try:
os.makedirs(directoryPath)
except OSError:
print 'Error: Could not create directory at location: ' + directoryPath
def createFile(filePath):
try:
createdFile = open(filePath, 'w+')
createdFile.close()
except IOError:
print "Error: could not create file at location: " + filePath
def openFile(filePath):
try:
fileEntity = open(filePath, 'r')
return fileEntity
except IOError:
print "Error: could not open file at location: " + filePath
return False
def removeFile(filePath):
try:
os.remove(filePath)
except OSError:
print "Error: could not remove file at location: " + filePath
def removeDirectory(directoryPath):
try:
os.removedirs(directoryPath)
except OSError:
print "Error: could not remove directory at location: " + directoryPath
def getFileContents(filePath):
try:
fileData = openFile(filePath).read()
return fileData
except IOError:
print "Error: could find file data located in file at location: " + filePath
return False
|
import os
def createDirectory(directoryPath):
if os.path.isdir(directoryPath) is False and os.path.exists(directoryPath) is False:
try:
os.makedirs(directoryPath)
except OSError:
print 'Error: Could not create directory at location: ' + directoryPath
def createFile(filePath):
try:
createdFile = open(filePath, 'w+')
createdFile.close()
except IOError:
print "Error: could not create file at location: " + filePath
def removeFile(filePath):
try:
os.remove(filePath)
except OSError:
print "Error: could not remove file at location: " + filePath
def removeDirectory(directoryPath):
try:
os.removedirs(directoryPath)
except OSError:
print "Error: could not remove directory at location: " + directoryPath
def getFileContents(filePath):
return None
|
Clarify how to force Basic Auth
|
<?php
use GuzzleHttp\Client;
use VDB\Spider\RequestHandler\GuzzleRequestHandler;
use VDB\Spider\Spider;
require_once __DIR__ . '/../vendor/autoload.php';
// Create Spider
$spider = new Spider('http://httpbin.org/basic-auth/foo/bar');
$requestHandler = new GuzzleRequestHandler();
// Set a custom Guzzle client that does basic auth. See Guzzle docs on how to use other types of authentication.
$requestHandler->setClient(new Client(['auth' => ['foo', 'bar', 'basic'], 'http_errors' => false]));
$spider->getDownloader()->setRequestHandler($requestHandler);
// Execute crawl
$spider->crawl();
// Finally we could do some processing on the downloaded resources
// In this example, we will echo the title of all resources
echo "\n\nRESPONSE: ";
foreach ($spider->getDownloader()->getPersistenceHandler() as $resource) {
echo "\n" . $resource->getResponse()->getStatusCode() . ": " . $resource->getResponse()->getReasonPhrase();
echo "\n" . $resource->getResponse()->getBody();
}
|
<?php
use GuzzleHttp\Client;
use VDB\Spider\RequestHandler\GuzzleRequestHandler;
use VDB\Spider\Spider;
require_once __DIR__ . '/../vendor/autoload.php';
// Create Spider
$spider = new Spider('http://httpbin.org/basic-auth/foo/bar');
// Set a custom request handler that does basic auth
$requestHandler = new GuzzleRequestHandler();
$requestHandler->setClient(new Client(['auth' => ['foo', 'bar'], 'http_errors' => false]));
$spider->getDownloader()->setRequestHandler($requestHandler);
// Execute crawl
$spider->crawl();
// Finally we could do some processing on the downloaded resources
// In this example, we will echo the title of all resources
echo "\n\nRESPONSE: ";
foreach ($spider->getDownloader()->getPersistenceHandler() as $resource) {
echo "\n" . $resource->getResponse()->getStatusCode() . ": " . $resource->getResponse()->getReasonPhrase();
echo "\n" . $resource->getResponse()->getBody();
}
|
Switch static_reply tests to new helpers.
|
from twisted.internet.defer import inlineCallbacks
from vumi.application.tests.helpers import ApplicationHelper
from vumi.demos.static_reply import StaticReplyApplication
from vumi.tests.helpers import VumiTestCase
class TestStaticReplyApplication(VumiTestCase):
def setUp(self):
self.app_helper = ApplicationHelper(StaticReplyApplication)
self.add_cleanup(self.app_helper.cleanup)
@inlineCallbacks
def test_receive_message(self):
yield self.app_helper.get_application({
'reply_text': 'Your message is important to us.',
})
yield self.app_helper.make_dispatch_inbound("Hello")
[reply] = self.app_helper.get_dispatched_outbound()
self.assertEqual('Your message is important to us.', reply['content'])
self.assertEqual(u'close', reply['session_event'])
@inlineCallbacks
def test_receive_message_no_reply(self):
yield self.app_helper.get_application({})
yield self.app_helper.make_dispatch_inbound("Hello")
self.assertEqual([], self.app_helper.get_dispatched_outbound())
|
from twisted.internet.defer import inlineCallbacks
from vumi.application.tests.utils import ApplicationTestCase
from vumi.demos.static_reply import StaticReplyApplication
class TestStaticReplyApplication(ApplicationTestCase):
application_class = StaticReplyApplication
@inlineCallbacks
def test_receive_message(self):
yield self.get_application(config={
'reply_text': 'Your message is important to us.',
})
yield self.dispatch(self.mkmsg_in())
[reply] = yield self.get_dispatched_messages()
self.assertEqual('Your message is important to us.', reply['content'])
self.assertEqual(u'close', reply['session_event'])
@inlineCallbacks
def test_receive_message_no_reply(self):
yield self.get_application(config={})
yield self.dispatch(self.mkmsg_in())
self.assertEqual([], (yield self.get_dispatched_messages()))
|
Add address and port parameters to run()
|
const FileSystemBackend = require('./src/backend/FileSystemBackend')
const FileSystemBuffer = require('./src/backend/FileSystemBuffer')
const host = require('./src/host/singletonHost')
const util = require('./src/util')
// Various shortuct functions and variables providing a similar interface
// to the package as in other Stencila language packages
// e.g. https://github.com/stencila/r/blob/master/R/main.R
const version = require('./package').version
const install = function () {
return host.install()
}
const environ = function () {
return console.log(JSON.stringify(host.environ(), null, ' ')) // eslint-disable-line no-console
}
const start = function (address='127.0.0.1', port=2000) {
return host.start(address, port)
}
const stop = function () {
return host.stop()
}
const run = function (address='127.0.0.1', port=2000) {
return host.run(address, port)
}
module.exports = {
FileSystemBackend,
FileSystemBuffer,
host: host,
util: util,
version: version,
install: install,
environ: environ,
start: start,
stop: stop,
run: run
}
|
const FileSystemBackend = require('./src/backend/FileSystemBackend')
const FileSystemBuffer = require('./src/backend/FileSystemBuffer')
const host = require('./src/host/singletonHost')
const util = require('./src/util')
// Various shortuct functions and variables providing a similar interface
// to the package as in other Stencila language packages
// e.g. https://github.com/stencila/r/blob/master/R/main.R
const version = require('./package').version
const install = function () {
return host.install()
}
const environ = function () {
return console.log(JSON.stringify(host.environ(), null, ' ')) // eslint-disable-line no-console
}
const start = function (address='127.0.0.1', port=2000) {
return host.start(address, port)
}
const stop = function () {
return host.stop()
}
const run = function () {
return host.run()
}
module.exports = {
FileSystemBackend,
FileSystemBuffer,
host: host,
util: util,
version: version,
install: install,
environ: environ,
start: start,
stop: stop,
run: run
}
|
Use statics for parseQuery modes (easier to read)
|
const HASH = '#'.charCodeAt(0);
const DOT = '.'.charCodeAt(0);
const TAGNAME = 0;
const ID = 1;
const CLASSNAME = 2;
export const parseQuery = (query) => {
let tag = null;
let id = null;
let className = null;
let mode = TAGNAME;
let buffer = '';
for (let i = 0; i <= query.length; i++) {
const char = query.charCodeAt(i);
const isHash = char === HASH;
const isDot = char === DOT;
const isEnd = !char;
if (isHash || isDot || isEnd) {
if (mode === TAGNAME) {
if (i === 0) {
tag = 'div';
} else {
tag = buffer;
}
} else if (mode === ID) {
id = buffer;
} else {
if (className) {
className += ' ' + buffer;
} else {
className = buffer;
}
}
if (isHash) {
mode = ID;
} else if (isDot) {
mode = CLASSNAME;
}
buffer = '';
} else {
buffer += query[i];
}
}
return { tag, id, className };
};
|
const HASH = '#'.charCodeAt(0);
const DOT = '.'.charCodeAt(0);
export const parseQuery = (query) => {
let tag = null;
let id = null;
let className = null;
let mode = 0;
let buffer = '';
for (let i = 0; i <= query.length; i++) {
const char = query.charCodeAt(i);
const isHash = char === HASH;
const isDot = char === DOT;
const isEnd = !char;
if (isHash || isDot || isEnd) {
if (mode === 0) {
if (i === 0) {
tag = 'div';
} else {
tag = buffer;
}
} else if (mode === 1) {
id = buffer;
} else {
if (className) {
className += ' ' + buffer;
} else {
className = buffer;
}
}
if (isHash) {
mode = 1;
} else if (isDot) {
mode = 2;
}
buffer = '';
} else {
buffer += query[i];
}
}
return { tag, id, className };
};
|
Call getUserFeed() when current user url is changed
|
var githubFeed = ({
feedUrl: "",
loadFeedUrl: function() {
var self = this;
chrome.storage.local.get("current_user_url", function(data) {
self.feedUrl = data.current_user_url;
});
},
urlChanged: function() {
var self = this;
chrome.storage.onChanged.addListener(function(changes, namespace) {
for (var key in changes) {
if (key === "current_user_url") {
alert("!!!");
console.log(changes[key].newValue);
self.feedUrl = changes[key].newValue;
self.getUserFeed();
}
}
});
},
getUserFeed: function() {
$.ajax({
type: "GET",
url: this.feedUrl,
success: function (data) {
debugger;
},
error: function (xhr, status, data) {
debugger;
},
});
},
init: function() {
this.urlChanged();
return this;
},
}).init();
githubFeed.loadFeedUrl();
|
var githubFeed = ({
feedUrl: "",
loadFeedUrl: function() {
var self = this;
chrome.storage.local.get("current_user_url", function(data) {
self.feedUrl = data.current_user_url;
});
},
urlChanged: function() {
chrome.storage.onChanged.addListener(function(changes, namespace) {
for (var key in changes) {
if (key === "current_user_url") {
alert("!!!");
console.log(changes[key].newValue);
this.feedUrl = changes[key].newValue;
}
}
});
},
getUserFeed: function() {
$.ajax({
type: "GET",
url: this.feedUrl,
success: function (data) {
debugger;
},
error: function (xhr, status, data) {
debugger;
},
});
},
init: function() {
this.urlChanged();
return this;
},
}).init();
githubFeed.loadFeedUrl();
|
Fix sort content types in role view
Signed-off-by: soupette <367d233c448abb973a0136207eb0cf446765a6f5@strapi.io>
|
import React, { memo } from 'react';
import PropTypes from 'prop-types';
import { Box } from '@strapi/parts/Box';
import styled from 'styled-components';
import sortBy from 'lodash/sortBy';
import ContentTypeCollapses from '../ContentTypeCollapses';
import GlobalActions from '../GlobalActions';
const StyledBox = styled(Box)`
overflow-x: auto;
`;
const ContentTypes = ({ isFormDisabled, kind, layout: { actions, subjects } }) => {
const sortedSubjects = sortBy([...subjects], 'label');
return (
<StyledBox background="neutral0">
<GlobalActions actions={actions} kind={kind} isFormDisabled={isFormDisabled} />
<ContentTypeCollapses
actions={actions}
isFormDisabled={isFormDisabled}
pathToData={kind}
subjects={sortedSubjects}
/>
</StyledBox>
);
};
ContentTypes.propTypes = {
isFormDisabled: PropTypes.bool.isRequired,
kind: PropTypes.string.isRequired,
layout: PropTypes.shape({
actions: PropTypes.array,
subjects: PropTypes.arrayOf(
PropTypes.shape({
uid: PropTypes.string.isRequired,
label: PropTypes.string.isRequired,
properties: PropTypes.array.isRequired,
})
),
}).isRequired,
};
export default memo(ContentTypes);
|
import React, { memo } from 'react';
import PropTypes from 'prop-types';
import { Box } from '@strapi/parts/Box';
import styled from 'styled-components';
import ContentTypeCollapses from '../ContentTypeCollapses';
import GlobalActions from '../GlobalActions';
const StyledBox = styled(Box)`
overflow-x: auto;
`;
const ContentTypes = ({ isFormDisabled, kind, layout: { actions, subjects } }) => {
const sortedSubjects = [...subjects].sort((a, b) => a.label > b.label);
return (
<StyledBox background="neutral0">
<GlobalActions actions={actions} kind={kind} isFormDisabled={isFormDisabled} />
<ContentTypeCollapses
actions={actions}
isFormDisabled={isFormDisabled}
pathToData={kind}
subjects={sortedSubjects}
/>
</StyledBox>
);
};
ContentTypes.propTypes = {
isFormDisabled: PropTypes.bool.isRequired,
kind: PropTypes.string.isRequired,
layout: PropTypes.shape({
actions: PropTypes.array,
subjects: PropTypes.arrayOf(
PropTypes.shape({
uid: PropTypes.string.isRequired,
label: PropTypes.string.isRequired,
properties: PropTypes.array.isRequired,
})
),
}).isRequired,
};
export default memo(ContentTypes);
|
Allow description to be null
|
<?php
namespace Vision\Hydrator\Strategy;
use Vision\Annotation\Property;
use Vision\Annotation\WebEntity;
use Zend\Hydrator\Strategy\StrategyInterface;
class WebEntitiesStrategy implements StrategyInterface
{
/**
* @param WebEntity[] $value
* @return array
*/
public function extract($value)
{
return array_map(function(WebEntity $webEntity) {
return array_filter([
'entityId' => $webEntity->getEntityId(),
'score' => $webEntity->getScore(),
'description' => $webEntity->getDescription(),
]);
}, $value);
}
/**
* @param array $value
* @return WebEntity[]
*/
public function hydrate($value)
{
$webEntities = [];
foreach ($value as $webEntityInfo) {
$webEntities[] = new WebEntity(
$webEntityInfo['entityId'],
isset($webEntityInfo['description']) ? $webEntityInfo['description'] : null,
isset($webEntityInfo['score']) ? $webEntityInfo['score'] : null
);
}
return $webEntities;
}
}
|
<?php
namespace Vision\Hydrator\Strategy;
use Vision\Annotation\Property;
use Vision\Annotation\WebEntity;
use Zend\Hydrator\Strategy\StrategyInterface;
class WebEntitiesStrategy implements StrategyInterface
{
/**
* @param WebEntity[] $value
* @return array
*/
public function extract($value)
{
return array_map(function(WebEntity $webEntity) {
return array_filter([
'entityId' => $webEntity->getEntityId(),
'score' => $webEntity->getScore(),
'description' => $webEntity->getDescription(),
]);
}, $value);
}
/**
* @param array $value
* @return WebEntity[]
*/
public function hydrate($value)
{
$webEntities = [];
foreach ($value as $webEntityInfo) {
$webEntities[] = new WebEntity($webEntityInfo['entityId'], $webEntityInfo['description'], isset($webEntityInfo['score']) ? $webEntityInfo['score'] : null);
}
return $webEntities;
}
}
|
Update Checking Threshold with pep8 syntax
|
def checking_threshold(a, b, avg_heart_rate):
"""
checking for Tachycardia or Bradycardia
:param a: int variable, lower bound bpm
:param b: int variable, upper bound bpm
:param avg_heart_rate: array, bpm
:return: The condition string
"""
# Checks if the the heart rate is lesser or greater than the threshold
if avg_heart_rate <= a:
output = "Bradycardia"
return output
elif avg_heart_rate >= b:
output = "Tachycardia"
return output
else:
output = "Normal Heart Rate"
return output
# a=int(input("Enter the Bradycardia Threshold"))
# b=int(input("Enter the Tachycardia Threshold"))
# avg_heart_rate=72
# Checking_Threshold(a,b,avg_heart_rate)
|
def checking_threshold(a, b, avg_heart_rate):
"""checking for Tachycardia or Bradycardia
:param a: int variable, lower bound bpm
:param b: int variable, upper bound bpm
:param avg_heart_rate: array, bpm
:return: The condition string
"""
# Checks if the the heart rate is lesser or greater than the threshold
if avg_heart_rate <= a:
output = "Bradycardia"
return output
elif avg_heart_rate >= b:
output = "Tachycardia"
return output
else:
output = "Normal Heart Rate"
return output
# a=int(input("Enter the Bradycardia Threshold"))
# b=int(input("Enter the Tachycardia Threshold"))
# avg_heart_rate=72
# Checking_Threshold(a,b,avg_heart_rate)
|
Add changes to the js file
|
// window.checkAdLoad = function(){
// var checkAdLoadfunction = function(){
// var msg = "Ad unit is not present";
// if($("._teraAdContainer")){
// console.log("Ad unit is present")
// msg = "Ad unit is present";
// }
// return msg;
// }
// checkAdLoadfunction()
// console.log(checkAdLoadfunction);
// var validateAd = new CustomEvent("trackAdLoad", { "detail": checkAdLoadfunction});
// window.dispatchEvent(validateAd);
// }
window.sayHello = function(name){
console.log("Hey "+name);
}
function checkAdLoad(){
if(t$("._abmMainAdContainer")){
return "Ad is Present";
} else {
return "Ad is Absent"
}
}
var validateAd = new CustomEvent("adLoaded", { "info": checkAdLoad()});
window.dispatchEvent(validateAd);
t$(document).ready(function(){
console.log("Checking the AdInstances.");
window.checkAdLoadfunction = function(){
if(t$("._abmMainAdContainer")){
console.log("Ad unit is present");
t$('div').mouseover(function(){
t$(this).find('._abmAdContainer')
console.log('Hoverred mouse over tera ad unit')
});
}
}
});
|
// window.checkAdLoad = function(){
// var checkAdLoadfunction = function(){
// var msg = "Ad unit is not present";
// if($("._teraAdContainer")){
// console.log("Ad unit is present")
// msg = "Ad unit is present";
// }
// return msg;
// }
// checkAdLoadfunction()
// console.log(checkAdLoadfunction);
// var validateAd = new CustomEvent("trackAdLoad", { "detail": checkAdLoadfunction});
// window.dispatchEvent(validateAd);
// }
window.sayHello = function(name){
console.log("Hey "+name);
}
t$(document).ready(function(){
console.log("Checking the AdInstances.");
window.checkAdLoadfunction = function(){
if(t$("._abmMainAdContainer")){
console.log("Ad unit is present");
t$('div').mouseover(function(){
t$(this).find('._abmAdContainer')
console.log('Hoverred mouse over tera ad unit')
});
}
}
});
|
Add fix for non pages like search.
|
from django import template
from django.db.models import ObjectDoesNotExist
from jobs.models import JobPostingListPage
register = template.Library()
@register.simple_tag(takes_context=True)
def get_active_posting_page(context):
if 'page' not in context:
return None
try:
root = context['page'].get_root()
listing_pages = JobPostingListPage.objects.descendant_of(root)
if listing_pages.count() > 0:
listing_page = listing_pages[0]
if listing_page.subpages.count() > 0:
if listing_page.subpages.count() == 1:
return listing_page.subpages[0]
return listing_page
return None
except ObjectDoesNotExist:
return None
|
from django import template
from django.db.models import ObjectDoesNotExist
from jobs.models import JobPostingListPage
register = template.Library()
@register.simple_tag(takes_context=True)
def get_active_posting_page(context):
try:
root = context['page'].get_root()
listing_pages = JobPostingListPage.objects.descendant_of(root)
if listing_pages.count() > 0:
listing_page = listing_pages[0]
if listing_page.subpages.count() > 0:
if listing_page.subpages.count() == 1:
return listing_page.subpages[0]
return listing_page
return None
except ObjectDoesNotExist:
return None
|
[Admin] Add custom events for order and customer show menu builders
|
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Bundle\UiBundle\Menu\Event;
use Knp\Menu\FactoryInterface;
use Knp\Menu\ItemInterface;
use Symfony\Component\EventDispatcher\Event;
/**
* @author Patrik Karisch <patrik.karisch@abimus.com>
*/
class MenuBuilderEvent extends Event
{
/**
* @var FactoryInterface
*/
private $factory;
/**
* @var ItemInterface
*/
private $menu;
/**
* @param FactoryInterface $factory
* @param ItemInterface $menu
*/
public function __construct(FactoryInterface $factory, ItemInterface $menu)
{
$this->factory = $factory;
$this->menu = $menu;
}
/**
* @return FactoryInterface
*/
public function getFactory()
{
return $this->factory;
}
/**
* @return ItemInterface
*/
public function getMenu()
{
return $this->menu;
}
}
|
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Bundle\UiBundle\Menu\Event;
use Knp\Menu\FactoryInterface;
use Knp\Menu\ItemInterface;
use Symfony\Component\EventDispatcher\Event;
/**
* @author Patrik Karisch <patrik.karisch@abimus.com>
*/
final class MenuBuilderEvent extends Event
{
/**
* @var FactoryInterface
*/
private $factory;
/**
* @var ItemInterface
*/
private $menu;
/**
* @param FactoryInterface $factory
* @param ItemInterface $menu
*/
public function __construct(FactoryInterface $factory, ItemInterface $menu)
{
$this->factory = $factory;
$this->menu = $menu;
}
/**
* @return FactoryInterface
*/
public function getFactory()
{
return $this->factory;
}
/**
* @return ItemInterface
*/
public function getMenu()
{
return $this->menu;
}
}
|
Fix typo in ngram sorting code.
|
package langdet
// Token represents a text token and its occurence in an analyzed text
type Token struct {
Occurrence int
Key string
}
// ByOccurrence represents an array of tokens which can be sorted by occurrences of the tokens.
type ByOccurrence []Token
func (a ByOccurrence) Len() int { return len(a) }
func (a ByOccurrence) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByOccurrence) Less(i, j int) bool {
if a[i].Occurrence == a[j].Occurrence {
return a[i].Key < a[j].Key
}
return a[i].Occurrence < a[j].Occurrence
}
// Language represents a language by its name and the profile ( map[token]OccurrenceRank )
type Language struct {
Profile map[string]int
Name string
}
// DetectionResult represents the result from comparing 2 Profiles. It includes the confidence which is basically the
// the relative distance between the two profiles.
type DetectionResult struct {
Name string
Confidence int
}
//ResByConf represents an array of DetectionResult and can be sorted by Confidence.
type ResByConf []DetectionResult
func (a ResByConf) Len() int { return len(a) }
func (a ResByConf) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ResByConf) Less(i, j int) bool { return a[i].Confidence > a[j].Confidence }
|
package langdet
// Token represents a text token and its occurence in an analyzed text
type Token struct {
Occurrence int
Key string
}
// ByOccurrence represents an array of tokens which can be sorted by occurrences of the tokens.
type ByOccurrence []Token
func (a ByOccurrence) Len() int { return len(a) }
func (a ByOccurrence) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByOccurrence) Less(i, j int) bool {
if a[i].Occurrence == a[j].Occurrence {
return a[i].Key < a[i].Key
}
return a[i].Occurrence < a[j].Occurrence
}
// Language represents a language by its name and the profile ( map[token]OccurrenceRank )
type Language struct {
Profile map[string]int
Name string
}
// DetectionResult represents the result from comparing 2 Profiles. It includes the confidence which is basically the
// the relative distance between the two profiles.
type DetectionResult struct {
Name string
Confidence int
}
//ResByConf represents an array of DetectionResult and can be sorted by Confidence.
type ResByConf []DetectionResult
func (a ResByConf) Len() int { return len(a) }
func (a ResByConf) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ResByConf) Less(i, j int) bool { return a[i].Confidence > a[j].Confidence }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.