text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Correct path names for fixed files.
--HG--
branch : distribute
extra : rebase_source : d5bd9c6fdb8cf2208eca9e0e5f37cb7fea1d14a5 | import os
from distutils import log
from sdist import sdist
from lib2to3.refactor import RefactoringTool, get_fixers_from_package
class _RefactoringTool(RefactoringTool):
def log_error(self, msg, *args, **kw):
log.error(msg, *args)
def log_message(self, msg, *args):
log.info(msg, *args)
def log_debug(self, msg, *args):
log.debug(msg, *args)
class sdist3(sdist):
description = "sdist version that runs 2to3 on all sources before packaging"
fixer_names = None
def copy_file(self, file, dest, link=None):
# We ignore the link parameter, always demanding a copy, so that
# 2to3 won't overwrite the original file.
sdist.copy_file(self, file, dest)
def make_release_tree(self, base_dir, files):
sdist.make_release_tree(self, base_dir, files)
# run 2to3 on all files
fixer_names = self.fixer_names
if fixer_names is None:
fixer_names = get_fixers_from_package('lib2to3.fixes')
r = _RefactoringTool(fixer_names)
r.refactor([os.path.join(base_dir, f) for f in files if f.endswith(".py")], write=True)
| from distutils import log
from sdist import sdist
from lib2to3.refactor import RefactoringTool, get_fixers_from_package
class _RefactoringTool(RefactoringTool):
def log_error(self, msg, *args, **kw):
log.error(msg, *args)
def log_message(self, msg, *args):
log.info(msg, *args)
def log_debug(self, msg, *args):
log.debug(msg, *args)
class sdist3(sdist):
description = "sdist version that runs 2to3 on all sources before packaging"
fixer_names = None
def copy_file(self, file, dest, link=None):
# We ignore the link parameter, always demanding a copy, so that
# 2to3 won't overwrite the original file.
sdist.copy_file(self, file, dest)
def make_release_tree(self, base_dir, files):
sdist.make_release_tree(self, base_dir, files)
# run 2to3 on all files
fixer_names = self.fixer_names
if fixer_names is None:
fixer_names = get_fixers_from_package('lib2to3.fixes')
r = _RefactoringTool(fixer_names)
r.refactor([f for f in files if f.endswith(".py")], write=True)
|
Use __DIR__ rather than dirname(__FILE__) for simplicity. | <?php
// Configuration information loaded from a file.
class Config {
const CONFIG_FILE = 'config';
const DIVIDER = ' = ';
protected static $config;
protected static function init() {
$path = __DIR__ . '/' . static::CONFIG_FILE;
if (!file_exists($path)) {
throw new Exception('Configuration file not found at ' . $path);
}
static::$config = [];
$rawConfig = file_get_contents($path);
foreach (explode("\n", $rawConfig) as $line) {
if (strpos($line, static::DIVIDER) === false) {
continue;
}
list($key, $value) = explode(static::DIVIDER, $line);
static::$config[$key] = $value;
}
}
public static function __callStatic($name, array $args) {
if (!isset(static::$config)) {
static::init();
}
if (isset(static::$config[$name])) {
return static::$config[$name];
} else {
return null;
}
}
}
| <?php
// Configuration information loaded from a file.
class Config {
const CONFIG_FILE = 'config';
const DIVIDER = ' = ';
protected static $config;
protected static function init() {
$path = dirname(__FILE__) . '/' . static::CONFIG_FILE;
if (!file_exists($path)) {
throw new Exception('Configuration file not found at ' . $path);
}
static::$config = [];
$rawConfig = file_get_contents($path);
foreach (explode("\n", $rawConfig) as $line) {
if (strpos($line, static::DIVIDER) === false) {
continue;
}
list($key, $value) = explode(static::DIVIDER, $line);
static::$config[$key] = $value;
}
}
public static function __callStatic($name, array $args) {
if (!isset(static::$config)) {
static::init();
}
if (isset(static::$config[$name])) {
return static::$config[$name];
} else {
return null;
}
}
}
|
Change name of state to SearchField. Apparently the name has to match the state. | /*
* Copyright (c) 2009 Kathryn Huxtable and Kenneth Orr.
*
* This file is part of the SeaGlass Pluggable Look and Feel.
*
* 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.
*
* $Id$
*/
package com.seaglasslookandfeel.state;
import javax.swing.JComponent;
import javax.swing.text.JTextComponent;
/**
* Is the text field a search field variant?
*/
public class TextFieldIsSearchState extends State {
public TextFieldIsSearchState() {
super("SearchField");
}
public boolean isInState(JComponent c) {
return (c instanceof JTextComponent) && "search".equals(c.getClientProperty("JTextField.variant"));
}
}
| /*
* Copyright (c) 2009 Kathryn Huxtable and Kenneth Orr.
*
* This file is part of the SeaGlass Pluggable Look and Feel.
*
* 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.
*
* $Id$
*/
package com.seaglasslookandfeel.state;
import javax.swing.JComponent;
import javax.swing.text.JTextComponent;
/**
* Is the text field a search field variant?
*/
public class TextFieldIsSearchState extends State {
public TextFieldIsSearchState() {
super("IsSearchField");
}
public boolean isInState(JComponent c) {
return (c instanceof JTextComponent) && "search".equals(c.getClientProperty("JTextField.variant"));
}
}
|
Check for missing path_info, also use OC_Response for 404 error | <?php
$RUNTIME_NOSETUPFS = true;
$RUNTIME_NOAPPS = TRUE;
require_once('lib/base.php');
if (array_key_exists('PATH_INFO', $_SERVER)){
$path_info = $_SERVER['PATH_INFO'];
}else{
$path_info = substr($_SERVER['PHP_SELF'], strpos($_SERVER['PHP_SELF'], basename(__FILE__)) + strlen(basename(__FILE__)));
}
if ($path_info === false) {
OC_Response::setStatus(OC_Response::STATUS_NOT_FOUND);
exit;
}
if (!$pos = strpos($path_info, '/', 1)) {
$pos = strlen($path_info);
}
$service=substr($path_info, 1, $pos-1);
$file = OC_AppConfig::getValue('core', 'remote_' . $service);
if(is_null($file)){
OC_Response::setStatus(OC_Response::STATUS_NOT_FOUND);
exit;
}
$parts=explode('/',$file);
$app=$parts[2];
OC_App::loadApp($app);
$baseuri = OC::$WEBROOT . '/remote.php/'.$service.'/';
require_once(OC::$APPSROOT . $file);
| <?php
$RUNTIME_NOSETUPFS = true;
$RUNTIME_NOAPPS = TRUE;
require_once('lib/base.php');
if (array_key_exists('PATH_INFO', $_SERVER)){
$path_info = $_SERVER['PATH_INFO'];
}else{
$path_info = substr($_SERVER['PHP_SELF'], strpos($_SERVER['PHP_SELF'], basename(__FILE__)) + strlen(basename(__FILE__)));
}
if (!$pos = strpos($path_info, '/', 1)) {
$pos = strlen($path_info);
}
$service=substr($path_info, 1, $pos-1);
$file = OC_AppConfig::getValue('core', 'remote_' . $service);
if(is_null($file)){
header('HTTP/1.0 404 Not Found');
exit;
}
$parts=explode('/',$file);
$app=$parts[2];
OC_App::loadApp($app);
$baseuri = OC::$WEBROOT . '/remote.php/'.$service.'/';
require_once(OC::$APPSROOT . $file); |
Remove path to logviewer, not used | <?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', 'RandomFormController@view');
Route::post('/', 'RandomFormController@handle'); //->middleware('decrypt.input');
Route::pattern('santa', '[0-9a-zA-Z]{'.config('hashids.connections')[config('hashids.default')]['length'].'}');
Route::get('/dearsanta/{santa}', 'DearSantaController@view')->name('dearsanta');
Route::post('/dearsanta/{santa}', 'DearSantaController@handle')->middleware('decrypt.key');;
Route::get('/org/{draw}', 'OrganizerController@view')->name('organizerPanel');
Route::post('/org/{draw}/{participant}/changeEmail', 'OrganizerController@changeEmail')->name('organizerPanel.changeEmail')->middleware('decrypt.key');;
Route::post('/event', 'EmailEventController@handle')->middleware('decrypt.key');
| <?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', 'RandomFormController@view');
Route::post('/', 'RandomFormController@handle'); //->middleware('decrypt.input');
Route::pattern('santa', '[0-9a-zA-Z]{'.config('hashids.connections')[config('hashids.default')]['length'].'}');
Route::get('/dearsanta/{santa}', 'DearSantaController@view')->name('dearsanta');
Route::post('/dearsanta/{santa}', 'DearSantaController@handle')->middleware('decrypt.key');;
Route::get('/org/{draw}', 'OrganizerController@view')->name('organizerPanel');
Route::post('/org/{draw}/{participant}/changeEmail', 'OrganizerController@changeEmail')->name('organizerPanel.changeEmail')->middleware('decrypt.key');;
Route::post('/event', 'EmailEventController@handle')->middleware('decrypt.key');
if (App::environment('local', 'dev', 'testing')) {
Route::get('/logs', '\Rap2hpoutre\LaravelLogViewer\LogViewerController@index');
}
|
Use a function to get the token
More reliable: the header is not a string but a function, so right before sending the request, Angular will call `getToken` and get the token | angular.module('ng-rails-csrf', [] ).config(['$httpProvider', function($httpProvider) {
var getToken = function() {
// Rails 3+
var el = document.querySelector('meta[name="csrf-token"]');
if (el) {
el = el.getAttribute('content');
} else {
// Rails 2
el = document.querySelector('input[name="authenticity_token"]');
if (el) {
el = el.value;
}
}
return el;
};
var updateToken = function() {
var headers = $httpProvider.defaults.headers.common, token = getToken();
if (token) {
headers['X-CSRF-TOKEN'] = getToken;
headers['X-Requested-With'] = 'XMLHttpRequest';
}
};
updateToken();
if (window['Turbolinks']) {
$(document).bind('page:change', updateToken);
}
}]);
| angular.module('ng-rails-csrf', [] ).config(['$httpProvider', function($httpProvider) {
var getToken = function() {
// Rails 3+
var el = document.querySelector('meta[name="csrf-token"]');
if (el) {
el = el.getAttribute('content');
} else {
// Rails 2
el = document.querySelector('input[name="authenticity_token"]');
if (el) {
el = el.value;
}
}
return el;
};
var updateToken = function() {
var headers = $httpProvider.defaults.headers.common, token = getToken();
if (token) {
headers['X-CSRF-TOKEN'] = token;
headers['X-Requested-With'] = 'XMLHttpRequest';
}
};
updateToken();
if (window['Turbolinks']) {
$(document).bind('page:change', updateToken);
}
}]);
|
Add raven to the dependancy list. | #!/usr/bin/env python
#coding: utf-8
from cms import VERSION
from setuptools import setup, find_packages
EXCLUDE_FROM_PACKAGES = ['cms.bin']
setup(
name="onespacemedia-cms",
version=".".join(str(n) for n in VERSION),
url="https://github.com/onespacemedia/cms",
author="Daniel Samuels",
author_email="daniel@onespacemedia.com",
license="BSD",
packages=find_packages(exclude=EXCLUDE_FROM_PACKAGES),
include_package_data=True,
scripts=['cms/bin/start_cms_project.py'],
zip_safe=False,
entry_points={
"console_scripts": [
"start_cms_project.py = cms.bin.start_cms_project:main",
],
},
description='CMS used by Onespacemedia',
install_requires=[
'django',
'psycopg2',
'django-suit',
'django-optimizations',
'Pillow',
'django-reversion',
'django-usertools',
'django-historylinks',
'django-watson',
'django-extensions',
'Werkzeug',
'raven'
],
)
| #!/usr/bin/env python
#coding: utf-8
from cms import VERSION
from setuptools import setup, find_packages
EXCLUDE_FROM_PACKAGES = ['cms.bin']
setup(
name="onespacemedia-cms",
version=".".join(str(n) for n in VERSION),
url="https://github.com/onespacemedia/cms",
author="Daniel Samuels",
author_email="daniel@onespacemedia.com",
license="BSD",
packages=find_packages(exclude=EXCLUDE_FROM_PACKAGES),
include_package_data=True,
scripts=['cms/bin/start_cms_project.py'],
zip_safe=False,
entry_points={
"console_scripts": [
"start_cms_project.py = cms.bin.start_cms_project:main",
],
},
description='CMS used by Onespacemedia',
install_requires=[
'django',
'psycopg2',
'django-suit',
'django-optimizations',
'Pillow',
'django-reversion',
'django-usertools',
'django-historylinks',
'django-watson',
'django-extensions',
'Werkzeug'
],
)
|
Fix another problem where package data was not included | import sys
from chandra_aca import __version__
from setuptools import setup
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
user_options = [('args=', 'a', "Arguments to pass to py.test")]
def initialize_options(self):
TestCommand.initialize_options(self)
self.args = []
def run_tests(self):
# Import here because outside the eggs aren't loaded
import pytest
errno = pytest.main(self.args)
sys.exit(errno)
setup(name='chandra_aca',
author='Jean Connelly, Tom Aldcroft',
description='Chandra Aspect Camera Tools',
author_email='jconnelly@cfa.harvard.edu',
version=__version__,
zip_safe=False,
packages=['chandra_aca', 'chandra_aca.tests'],
package_data={'chandra_aca.tests': ['data/*.txt']},
tests_require=['pytest'],
cmdclass={'test': PyTest},
)
| import sys
from chandra_aca import __version__
from setuptools import setup
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
user_options = [('args=', 'a', "Arguments to pass to py.test")]
def initialize_options(self):
TestCommand.initialize_options(self)
self.args = []
def run_tests(self):
# Import here because outside the eggs aren't loaded
import pytest
errno = pytest.main(self.args)
sys.exit(errno)
setup(name='chandra_aca',
author='Jean Connelly, Tom Aldcroft',
description='Chandra Aspect Camera Tools',
author_email='jconnelly@cfa.harvard.edu',
version=__version__,
zip_safe=False,
packages=['chandra_aca', 'chandra_aca.tests'],
tests_require=['pytest'],
cmdclass={'test': PyTest},
)
|
Add prettier as eslint plugin | module.exports = {
root: true,
parserOptions: {
ecmaVersion: 2017,
sourceType: "module"
},
plugins: ["ember", "prettier"],
extends: [
"eslint:recommended",
"plugin:ember/recommended",
"plugin:prettier/recommended"
],
env: {
browser: true
},
rules: {
"prettier/prettier": 2,
"ember/new-module-imports": 2
},
overrides: [
// node files
{
files: [
"index.js",
"testem.js",
"ember-cli-build.js",
"config/**/*.js",
"tests/dummy/config/**/*.js",
"blueprints/**/*.js"
],
excludedFiles: ["app/**", "addon/**", "tests/dummy/app/**"],
parserOptions: {
sourceType: "script",
ecmaVersion: 2015
},
env: {
browser: false,
node: true
},
plugins: ["node"],
rules: Object.assign(
{},
require("eslint-plugin-node").configs.recommended.rules,
{
// add your custom rules and overrides for node files here
}
)
}
]
};
| module.exports = {
root: true,
parserOptions: {
ecmaVersion: 2017,
sourceType: "module"
},
plugins: ["ember"],
extends: [
"eslint:recommended",
"plugin:ember/recommended",
"plugin:prettier/recommended"
],
env: {
browser: true
},
rules: {
"prettier/prettier": 2,
"ember/new-module-imports": 2
},
overrides: [
// node files
{
files: [
"index.js",
"testem.js",
"ember-cli-build.js",
"config/**/*.js",
"tests/dummy/config/**/*.js",
"blueprints/**/*.js"
],
excludedFiles: ["app/**", "addon/**", "tests/dummy/app/**"],
parserOptions: {
sourceType: "script",
ecmaVersion: 2015
},
env: {
browser: false,
node: true
},
plugins: ["node"],
rules: Object.assign(
{},
require("eslint-plugin-node").configs.recommended.rules,
{
// add your custom rules and overrides for node files here
}
)
}
]
};
|
Add additional swagger UI redirects
- cbioportal.org/api/
- cbioportal.org/api/swagger-ui.html | package org.cbioportal.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;
import javax.servlet.http.HttpServletRequest;
/**
* Springfox 3.0 doesn't completely respect the path we specify for the swagger UI
* This redirect puts the api-doc json in the specified path so that the swagger UI works
* and the frontend can pull the json.
*/
@Controller
public class DocRedirectController {
@GetMapping("/api-docs")
public RedirectView docRedirect(
@RequestParam(value = "group", defaultValue = "default")
String group,
final RedirectAttributes redirectAttributes,
HttpServletRequest request
) {
redirectAttributes.addAttribute("group", group);
return new RedirectView("/api/v2/api-docs");
}
@GetMapping({"/", "/swagger-ui.html"})
public RedirectView swaggerUIRedirect(
@RequestParam(value = "group", defaultValue = "default")
String group,
final RedirectAttributes redirectAttributes,
HttpServletRequest request
) {
redirectAttributes.addAttribute("group", group);
return new RedirectView("/api/swagger-ui/index.html");
}
}
| package org.cbioportal.web;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;
import javax.servlet.http.HttpServletRequest;
/**
* Springfox 3.0 doesn't completely respect the path we specify for the swagger UI
* This redirect puts the api-doc json in the specified path so that the swagger UI works
* and the frontend can pull the json.
*/
@Controller
public class DocRedirectController {
@GetMapping("/api-docs")
public RedirectView redirectWithUsingRedirectView(
@RequestParam(value = "group", defaultValue = "default")
String group,
final RedirectAttributes redirectAttributes,
HttpServletRequest request
) {
redirectAttributes.addAttribute("group", group);
return new RedirectView("/api/v2/api-docs");
}
}
|
fix: Enable filtering of empty entries | const parsers = require('../parsers')
const transform = require('../transform')
const request = require('../request')
const { EmptyParseOutputError } = require('../errors')
async function parse(parser, text) {
const parsed = await parsers[parser](text)
if (!parsed) throw new EmptyParseOutputError()
return transform(parsed)
}
async function parseFromString({ content, parser }) {
if (parser) {
return parse(parser, content)
} else {
for (let i = 0; i < parsers.keys.length; i++) {
try {
return await parse(parsers.keys[i], content)
} catch (error) {
if (i < parsers.keys.length - 1) {
continue
}
throw error
}
}
}
}
async function parseFromQuery({ url, parser }) {
const content = (await request(url)).text
const parsed = await parseFromString({ content, parser })
parsed.entries = parsed.entries.filter((item) => item != null)
parsed.feedLink = parsed.feedLink || url
return parsed
}
module.exports = { parseFromQuery, parseFromString }
| const parsers = require('../parsers')
const transform = require('../transform')
const request = require('../request')
const { ConnectionFailedError, EmptyParseOutputError } = require('../errors')
async function parse(parser, text) {
const parsed = await parsers[parser](text)
if (!parsed) throw new EmptyParseOutputError()
return transform(parsed)
}
async function parseFromString({ content, parser }) {
if (parser) {
return parse(parser, content)
} else {
for (let i = 0; i < parsers.keys.length; i++) {
try {
return await parse(parsers.keys[i], content)
} catch (error) {
if (i < parsers.keys.length - 1) {
continue
}
throw error
}
}
}
}
async function parseFromQuery({ url, parser }) {
try {
const content = (await request(url)).text
const parsed = await parseFromString({ content, parser })
parsed.entries = parsed.entries.filter((item) => item == null)
return await parseFromString({ content, parser })
} catch (error) {
if (error.code === 'ENOTFOUND') {
throw new ConnectionFailedError(url)
}
throw error
}
}
module.exports = { parseFromQuery, parseFromString }
|
Update byte objects tests to reflect new behaviour. | from protobuf3.fields.bytes import BytesField
from protobuf3.message import Message
from unittest import TestCase
class TestBytesField(TestCase):
def setUp(self):
class BytesTestMessage(Message):
b = BytesField(field_number=2)
self.msg_cls = BytesTestMessage
def test_get(self):
msg = self.msg_cls()
msg.parse_from_bytes(bytes([0x12, 0x07, 0x74, 0x65, 0x73, 0x74, 0x69, 0x6E, 0x67]))
self.assertEqual(msg.b, b'testing')
def test_default_get(self):
msg = self.msg_cls()
self.assertEqual(msg.b, b'')
def test_set(self):
msg = self.msg_cls()
msg.b = b'test'
self.assertEqual(msg.b, b'test')
def test_set_string(self):
msg = self.msg_cls()
msg.b = 'test'
self.assertEqual(msg.b, b'test')
def test_invalid_set(self):
msg = self.msg_cls()
def failure():
msg.b = 123
self.assertRaises(ValueError, failure)
| from protobuf3.fields.bytes import BytesField
from protobuf3.message import Message
from unittest import TestCase
class TestBytesField(TestCase):
def setUp(self):
class BytesTestMessage(Message):
b = BytesField(field_number=2)
self.msg_cls = BytesTestMessage
def test_get(self):
msg = self.msg_cls()
msg.parse_from_bytes([0x12, 0x07, 0x74, 0x65, 0x73, 0x74, 0x69, 0x6E, 0x67])
self.assertEqual(msg.b, b'testing')
def test_default_get(self):
msg = self.msg_cls()
self.assertEqual(msg.b, b'')
def test_set(self):
msg = self.msg_cls()
msg.b = b'test'
self.assertEqual(msg.b, b'test')
def test_set_string(self):
msg = self.msg_cls()
msg.b = 'test'
self.assertEqual(msg.b, b'test')
def test_invalid_set(self):
msg = self.msg_cls()
def failure():
msg.b = 123
self.assertRaises(ValueError, failure)
|
Fix regex for package naming diagnostic | package com.azure.tools.apiview.processor.diagnostics.rules;
import com.azure.tools.apiview.processor.diagnostics.DiagnosticRule;
import com.azure.tools.apiview.processor.model.APIListing;
import com.azure.tools.apiview.processor.model.Diagnostic;
import com.github.javaparser.ast.CompilationUnit;
import java.util.regex.Pattern;
import static com.azure.tools.apiview.processor.analysers.util.ASTUtils.*;
public class PackageNameDiagnosticRule implements DiagnosticRule {
final static Pattern regex = Pattern.compile("^com.azure(\\.[a-z0-9]+)+$");
@Override
public void scan(final CompilationUnit cu, final APIListing listing) {
getPackageName(cu).ifPresent(packageName -> {
// we need to map the issue to the class id, because package text isn't printed in the APIView output
getClassName(cu).map(listing.getKnownTypes()::get).ifPresent(typeId -> {
if (!regex.matcher(packageName).matches()) {
listing.addDiagnostic(new Diagnostic(typeId,
"Package name must start with 'com.azure', and it must be lower-case, with no underscores or hyphens."));
}
});
});
}
}
| package com.azure.tools.apiview.processor.diagnostics.rules;
import com.azure.tools.apiview.processor.diagnostics.DiagnosticRule;
import com.azure.tools.apiview.processor.model.APIListing;
import com.azure.tools.apiview.processor.model.Diagnostic;
import com.github.javaparser.ast.CompilationUnit;
import java.util.regex.Pattern;
import static com.azure.tools.apiview.processor.analysers.util.ASTUtils.*;
public class PackageNameDiagnosticRule implements DiagnosticRule {
final static Pattern regex = Pattern.compile("^com.azure.[a-z0-9]*(\\.[a-z0-9]+)+[0-9a-z]$");
@Override
public void scan(final CompilationUnit cu, final APIListing listing) {
getPackageName(cu).ifPresent(packageName -> {
// we need to map the issue to the class id, because package text isn't printed in the APIView output
getClassName(cu).map(listing.getKnownTypes()::get).ifPresent(typeId -> {
if (!regex.matcher(packageName).matches()) {
listing.addDiagnostic(new Diagnostic(typeId,
"Package name must start with 'com.azure', and it must be lower-case, with no underscores or hyphens."));
}
});
});
}
}
|
Remove assosiate user social auth step | SHELL_PLUS = "ipython"
SOCIAL_AUTH_STEAM_EXTRA_DATA = ['player']
SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/'
SOCIAL_AUTH_LOGIN_ERROR_URL = '/login/error/'
SOCIAL_AUTH_INACTIVE_USER_URL = '/login/inactive/'
SOCIAL_AUTH_NEW_USER_REDIRECT_URL = '/'
SOCIAL_AUTH_PASSWORDLESS = True
SOCIAL_AUTH_PIPELINE = (
'social_core.pipeline.social_auth.social_details',
'social_core.pipeline.social_auth.social_uid',
'social_core.pipeline.social_auth.auth_allowed',
'social_core.pipeline.social_auth.social_user',
'wph.social.pipeline.require_email',
'social_core.pipeline.user.get_username',
# 'social_core.pipeline.mail.mail_validation',
'social_core.pipeline.user.create_user',
# 'social_core.pipeline.social_auth.associate_user',
'social_core.pipeline.social_auth.load_extra_data',
'social_core.pipeline.user.user_details',
)
| SHELL_PLUS = "ipython"
SOCIAL_AUTH_STEAM_EXTRA_DATA = ['player']
SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/'
SOCIAL_AUTH_LOGIN_ERROR_URL = '/login/error/'
SOCIAL_AUTH_INACTIVE_USER_URL = '/login/inactive/'
SOCIAL_AUTH_NEW_USER_REDIRECT_URL = '/'
SOCIAL_AUTH_PASSWORDLESS = True
SOCIAL_AUTH_PIPELINE = (
'social_core.pipeline.social_auth.social_details',
'social_core.pipeline.social_auth.social_uid',
'social_core.pipeline.social_auth.auth_allowed',
'social_core.pipeline.social_auth.social_user',
'wph.social.pipeline.require_email',
'social_core.pipeline.user.get_username',
# 'social_core.pipeline.mail.mail_validation',
'social_core.pipeline.user.create_user',
'social_core.pipeline.social_auth.associate_user',
'social_core.pipeline.social_auth.load_extra_data',
'social_core.pipeline.user.user_details',
)
|
Replace double quotes with single quotes | /*
* biojs-io-biom
* https://github.com/iimog/biojs-io-biom
*
* Copyright (c) 2016 Markus J. Ankenbrand
* Licensed under the MIT license.
*/
export const VERSION = '0.1.0';
/**
@class Biom
*/
export class Biom {
constructor({
id: _id = null,
format: _format = 'Biological Observation Matrix 1.0.0',
format_url: _format_url = 'http://biom-format.org',
type: _type = 'OTU table',
generated_by: _generated_by = `biojs-io-biom v${VERSION}`
} = {}){
this._id = _id;
this._format = _format;
this._format_url = _format_url;
this._type = _type;
this._generated_by = _generated_by;
}
get id(){
return this._id;
}
get generated_by(){
return this._generated_by;
}
}
| /*
* biojs-io-biom
* https://github.com/iimog/biojs-io-biom
*
* Copyright (c) 2016 Markus J. Ankenbrand
* Licensed under the MIT license.
*/
export const VERSION = "0.1.0";
/**
@class Biom
*/
export class Biom {
constructor({
id: _id = null,
format: _format = "Biological Observation Matrix 1.0.0",
format_url: _format_url = "http://biom-format.org",
type: _type = "OTU table",
generated_by: _generated_by = `biojs-io-biom v${VERSION}`
} = {}){
this._id = _id;
this._generated_by = _generated_by;
}
get id(){
return this._id;
}
get generated_by(){
return this._generated_by;
}
}
|
Verify services status if FI is rebooted
Change-Id: Ia02ef16d53fbb7b55a8de884ff16a4bef345a1f2 | def start(lab, log, args):
from fabric.context_managers import shell_env
grep_host = args.get('grep_host', 'overcloud-')
statuses = {'up': 1, 'down': 0}
server = lab.director()
with shell_env(OS_AUTH_URL=lab.cloud.end_point, OS_USERNAME=lab.cloud.user, OS_PASSWORD=lab.cloud.password, OS_TENANT_NAME=lab.cloud.tenant):
res = server.run("nova service-list | grep {0} | awk '{{print $4 \" \" $6 \" \" $12}}'".format(grep_host), warn_only=True)
results = [line.split() for line in res.split('\n')]
msg = ' '.join(['{1}:{0}={2}'.format(r[0], r[1], statuses[r[2]]) for r in results])
log.info('{1}'.format(grep_host, msg))
| def start(lab, log, args):
import time
from fabric.context_managers import shell_env
grep_host = args.get('grep_host', 'overcloud-')
duration = args['duration']
period = args['period']
statuses = {'up': 1, 'down': 0}
server = lab.director()
start_time = time.time()
while start_time + duration > time.time():
with shell_env(OS_AUTH_URL=lab.cloud.end_point, OS_USERNAME=lab.cloud.user, OS_PASSWORD=lab.cloud.password, OS_TENANT_NAME=lab.cloud.tenant):
res = server.run("nova service-list | grep {0} | awk '{{print $4 \" \" $6 \" \" $12}}'".format(grep_host), warn_only=True)
results = [line.split() for line in res.split('\n')]
msg = ' '.join(['{1}:{0}={2}'.format(r[0], r[1], statuses[r[2]]) for r in results])
log.info('{1}'.format(grep_host, msg))
time.sleep(period)
|
Fix the geos library location | import os
from .base import *
GEOS_LIBRARY_PATH = '/var/task/libgeos_c.so'
ALLOWED_HOSTS = ['*']
# Override the database name and user if needed
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'HOST': os.environ.get('DATABASE_HOST'),
'USER': os.environ.get('DATABASE_USER'),
'PORT': '5432',
'NAME': os.environ.get('DATABASE_NAME'),
'PASSWORD': os.environ.get('DATABASE_PASS')
}
}
DEFAULT_FILE_STORAGE = 's3_lambda_storage.S3LambdaStorage'
STATICFILES_STORAGE = 's3_lambda_storage.S3StaticLambdaStorage'
AWS_STORAGE_BUCKET_NAME = "data.electionleaflets.org"
AWS_S3_SECURE_URLS = True
AWS_S3_HOST = 's3-eu-west-1.amazonaws.com'
AWS_S3_CUSTOM_DOMAIN = "data.electionleaflets.org"
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
'LOCATION': 'el_cache',
}
}
THUMBNAIL_KVSTORE ='sorl.thumbnail.kvstores.cached_db_kvstore.KVStore'
CSRF_TRUSTED_ORIGINS = ['.electionleaflets.org']
| import os
from .base import *
# GEOS_LIBRARY_PATH = '/var/task/libgeos_c.so'
ALLOWED_HOSTS = ['*']
# Override the database name and user if needed
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'HOST': os.environ.get('DATABASE_HOST'),
'USER': os.environ.get('DATABASE_USER'),
'PORT': '5432',
'NAME': os.environ.get('DATABASE_NAME'),
'PASSWORD': os.environ.get('DATABASE_PASS')
}
}
DEFAULT_FILE_STORAGE = 's3_lambda_storage.S3LambdaStorage'
STATICFILES_STORAGE = 's3_lambda_storage.S3StaticLambdaStorage'
AWS_STORAGE_BUCKET_NAME = "data.electionleaflets.org"
AWS_S3_SECURE_URLS = True
AWS_S3_HOST = 's3-eu-west-1.amazonaws.com'
AWS_S3_CUSTOM_DOMAIN = "data.electionleaflets.org"
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
'LOCATION': 'el_cache',
}
}
THUMBNAIL_KVSTORE ='sorl.thumbnail.kvstores.cached_db_kvstore.KVStore'
CSRF_TRUSTED_ORIGINS = ['.electionleaflets.org']
|
Fix IDE nag (unused variable)
git-svn-id: 79cef5a5a257cc9dbe40a45ac190115b4780e2d0@1842706 13f79535-47bb-0310-9956-ffa450edef68 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.tomcat.util.compat;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.SSLContext;
import org.apache.tomcat.util.net.Constants;
/**
* This class checks for the availability of TLS features.
*/
public class TLS {
private static final boolean tlsv13Available;
static {
boolean ok = false;
try {
SSLContext.getInstance(Constants.SSL_PROTO_TLSv1_3);
ok = true;
} catch (NoSuchAlgorithmException ex) {
}
tlsv13Available = ok;
}
public static boolean isTlsv13Available() {
return tlsv13Available;
}
}
| /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.tomcat.util.compat;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.SSLContext;
import org.apache.tomcat.util.net.Constants;
/**
* This class checks for the availability of TLS features.
*/
public class TLS {
private static final boolean tlsv13Available;
static {
boolean ok = false;
try {
SSLContext sc = SSLContext.getInstance(Constants.SSL_PROTO_TLSv1_3);
ok = true;
} catch (NoSuchAlgorithmException ex) {
}
tlsv13Available = ok;
}
public static boolean isTlsv13Available() {
return tlsv13Available;
}
}
|
Update email in pip package | from setuptools import setup
setup(
name = 'taskcat',
packages = ['taskcat'],
description = 'An OpenSource Cloudformation Deployment Framework',
author = 'Tony Vattathil',
author_email = 'tonynv@amazon.com',
url = 'https://aws-quickstart.github.io/taskcat/',
version = '0.1.7',
download_url = 'https://github.com/aws-quickstart/taskcat/tarball/master',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
keywords = ['aws', 'cloudformation', 'cloud', 'cloudformation testing', 'cloudformation deploy', 'taskcat'],
#packages=find_packages(exclude=['contrib', 'docs', 'tests']),
install_requires=['uuid', 'pyfiglet', 'argparse', 'boto3', 'pyyaml'],
#data_files=[('config', ['ci/config.yml`'])],
# To provide executable scripts, use entry points in preference to the
# "scripts" keyword. Entry points provide cross-platform support and allow
# pip to create the appropriate form of executable for the target platform.
#entry_points={
# 'console_scripts': [
# 'sample=sample:main',
# ],
#},
)
| from setuptools import setup
setup(
name = 'taskcat',
packages = ['taskcat'],
description = 'An OpenSource Cloudformation Deployment Framework',
author = 'Tony Vattathil',
author_email = 'avattathil@gmail.com',
url = 'https://github.com/avattathil/taskcat.io',
version = '0.1.3',
download_url = 'https://github.com/avattathil/taskcat.io/archive/master.zip',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
keywords = ['aws', 'cloudformation', 'cloud', 'cloudformation testing', 'cloudformation deploy', 'taskcat'],
#packages=find_packages(exclude=['contrib', 'docs', 'tests']),
install_requires=['uuid', 'pyfiglet', 'argparse', 'boto3', 'pyyaml'],
#data_files=[('config', ['ci/config.yml`'])],
# To provide executable scripts, use entry points in preference to the
# "scripts" keyword. Entry points provide cross-platform support and allow
# pip to create the appropriate form of executable for the target platform.
#entry_points={
# 'console_scripts': [
# 'sample=sample:main',
# ],
#},
)
|
Set appropriate login page redirection | <?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Guard;
class Authenticate
{
/**
* The Guard implementation.
*
* @var Guard
*/
protected $auth;
/**
* Create a new filter instance.
*
* @param Guard $auth
* @return void
*/
public function __construct(Guard $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($this->auth->guest()) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('login');
}
}
return $next($request);
}
}
| <?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Guard;
class Authenticate
{
/**
* The Guard implementation.
*
* @var Guard
*/
protected $auth;
/**
* Create a new filter instance.
*
* @param Guard $auth
* @return void
*/
public function __construct(Guard $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($this->auth->guest()) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('auth/login');
}
}
return $next($request);
}
}
|
Add isAnonymous property to anonymous user | var express = require('express');
var User = require('../schemas/userSchema.js');
var app = express();
app.get('/users', function (req, res, next) {
if (req.isAuthenticated()) {
res.json({
"users": [req.user]
});
} else {
res.json({
"users": [{
_id: "anonymous user",
isAnonymous: true
}]
})
}
});
app.put('/users/:id', function (req, res, next) {
if (!req.isAuthenticated()) {
res.send(401, 'You must be logged in to join a project');
}
User.findById(req.params.id).exec().then(function (user) {
user.projects = req.body.user.projects;
user.save();
res.json({
"user": user
});
}, next);
});
module.exports = app; | var express = require('express');
var User = require('../schemas/userSchema.js');
var app = express();
app.get('/users', function (req, res, next) {
if (req.isAuthenticated()) {
res.json({
"users": [req.user]
});
} else {
res.json({
"users": [{
_id: "anonymous user"
}]
})
}
});
app.put('/users/:id', function (req, res, next) {
if (!req.isAuthenticated()) {
res.send(401, 'You must be logged in to join a project');
}
User.findById(req.params.id).exec().then(function (user) {
user.projects = req.body.user.projects;
user.save();
res.json({
"user": user
});
}, next);
});
module.exports = app; |
Fix Django system check error for a editable field that is not displayed
This error,
"CommandError: System check identified some issues:
ERRORS:
<class 'fullcalendar.admin.EventAdmin'>: (admin.E122) The value of 'list_editable[0]' refers to 'status', which is not an attribute of 'events.Event'."
was given for Django >1.7.1 | from django.utils.translation import ugettext_lazy as _
from django.contrib import admin
from mezzanine.core.admin import StackedDynamicInlineAdmin, DisplayableAdmin
from fullcalendar.models import *
class EventCategoryAdmin(admin.ModelAdmin):
list_display = ('name',)
class OccurrenceInline(StackedDynamicInlineAdmin):
model = Occurrence
fields = ('start_time', 'end_time', 'description', 'location')
class EventAdmin(DisplayableAdmin):
list_display = ('title', 'event_category', 'status')
list_filter = ('event_category',)
search_fields = ('title', 'description', 'content', 'keywords')
fieldsets = (
(None, {
"fields": [
"title", "status", ("publish_date", "expiry_date"),
"event_category", "content"
]
}),
(_("Meta data"), {
"fields": [
"_meta_title", "slug",
("description", "gen_description"),
"keywords", "in_sitemap"
],
"classes": ("collapse-closed",)
}),
)
inlines = [OccurrenceInline]
admin.site.register(Event, EventAdmin)
admin.site.register(EventCategory, EventCategoryAdmin)
| from django.utils.translation import ugettext_lazy as _
from django.contrib import admin
from mezzanine.core.admin import StackedDynamicInlineAdmin, DisplayableAdmin
from fullcalendar.models import *
class EventCategoryAdmin(admin.ModelAdmin):
list_display = ('name',)
class OccurrenceInline(StackedDynamicInlineAdmin):
model = Occurrence
fields = ('start_time', 'end_time', 'description', 'location')
class EventAdmin(DisplayableAdmin):
list_display = ('title', 'event_category')
list_filter = ('event_category',)
search_fields = ('title', 'description', 'content', 'keywords')
fieldsets = (
(None, {
"fields": [
"title", "status", ("publish_date", "expiry_date"),
"event_category", "content"
]
}),
(_("Meta data"), {
"fields": [
"_meta_title", "slug",
("description", "gen_description"),
"keywords", "in_sitemap"
],
"classes": ("collapse-closed",)
}),
)
inlines = [OccurrenceInline]
admin.site.register(Event, EventAdmin)
admin.site.register(EventCategory, EventCategoryAdmin)
|
Refactor audiofactory to match standards | 'use strict';
/*
* Module for playing audio, now the Angular way!
*/
angular.module('audiohandler', [])
.factory('audioFactory', function ($document) {
return {
playSound: function (selector) {
var audio = $document[0].querySelector(selector);
audio.play();
},
stopSound: function (selector) {
var audio = $document[0].querySelector(selector);
audio.pause();
audio.currentTime = 0;
},
stopAllSounds: function () {
var elements = $document[0].querySelectorAll('audio');
var len = elements.length;
var i = 0;
for (i = 0; i < len; i++) {
elements[i].pause();
elements[i].currentTime = 0;
}
}
};
});
| 'use strict';
/*
* Module for playing audio, now the Angular way!
*/
var audiohandler = angular.module('audiohandler', []);
audiohandler.factory('audioFactory', function() {
return {
playSound: function(selector) {
var audio = document.querySelector(selector);
audio.play();
},
stopSound: function(selector) {
var audio = document.querySelector(selector);
audio.pause();
audio.currentTime = 0;
},
stopAllSounds: function() {
var elements = document.querySelectorAll('audio');
var len = elements.length;
for (var i = 0; i < len; i++) {
elements[i].pause();
elements[i].currentTime = 0;
}
}
}
});
|
Change command option format.
- proxy_mode into proxy-mode
- viewer_type into viewer-mode | import argparse
from microproxy import proxy
from microproxy.viewer import log as log_viewer
def proxy_handler(args):
proxy.start_proxy_server(args.host, args.port, args.proxy_mode)
def viewer_handler(args):
if args.viewer_mode == "log":
log_viewer.start()
def main():
parser = argparse.ArgumentParser(description="")
subparser = parser.add_subparsers()
proxy_parser = subparser.add_parser('proxy', help="Enable Proxy Server")
proxy_parser.add_argument("--host", default="127.0.0.1")
proxy_parser.add_argument("--port", type=int, default=5580)
proxy_parser.add_argument("--proxy-mode",
choices=["socks", "transparent"],
default="socks")
proxy_parser.set_defaults(func=proxy_handler)
viewer_parser = subparser.add_parser("viewer", help="Open Viewer")
viewer_parser.add_argument("--viewer-mode",
choices=["log"],
default="log")
viewer_parser.set_defaults(func=viewer_handler)
args = parser.parse_args()
args.func(args)
if __name__ == "__main__":
main()
| import argparse
from microproxy import proxy
from microproxy.viewer import log as log_viewer
def proxy_handler(args):
proxy.start_proxy_server(args.host, args.port, args.proxy_mode)
def viewer_handler(args):
if args.viewer_type == "log":
log_viewer.start()
def main():
parser = argparse.ArgumentParser(description="")
subparser = parser.add_subparsers()
proxy_parser = subparser.add_parser('proxy', help="Enable Proxy Server")
proxy_parser.add_argument("--host", default="127.0.0.1")
proxy_parser.add_argument("--port", type=int, default=5580)
proxy_parser.add_argument("--proxy_mode",
choices=["socks", "transparent"],
default="socks")
proxy_parser.set_defaults(func=proxy_handler)
viewer_parser = subparser.add_parser("viewer", help="Open Viewer")
viewer_parser.add_argument("--viewer_type",
choices=["log"],
default="log")
viewer_parser.set_defaults(func=viewer_handler)
args = parser.parse_args()
args.func(args)
if __name__ == "__main__":
main()
|
Fix Copy&Paste Error und documentation | package com.ulisesbocchio.jasyptmavenplugin.mojo;
import com.ulisesbocchio.jasyptmavenplugin.encrypt.EncryptionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
/**
* Goal which decrypts values.
*
* @author ubocchio
*/
@Mojo(name = "decrypt-value", defaultPhase = LifecyclePhase.PROCESS_RESOURCES)
@Slf4j
public class DecryptValueMojo extends AbstractValueJasyptMojo {
@Override
protected void run(final EncryptionService service, final String value, String encryptPrefix, String encryptSuffix, String decryptPrefix, String decryptSuffix) throws
MojoExecutionException {
try {
String actualValue = value.startsWith(encryptPrefix) ? value.substring(encryptPrefix.length(), value.length() - encryptSuffix.length()) : value;
log.info("Decrypting value " + actualValue);
String decryptedValue = service.decryptValue(actualValue);
log.info("\n" + decryptedValue);
} catch (Exception e) {
throw new MojoExecutionException("Error Decrypting: " + e.getMessage(), e);
}
}
}
| package com.ulisesbocchio.jasyptmavenplugin.mojo;
import com.ulisesbocchio.jasyptmavenplugin.encrypt.EncryptionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
/**
* Goal which decrypts demarcated values in properties files.
*
* @author ubocchio
*/
@Mojo(name = "decrypt-value", defaultPhase = LifecyclePhase.PROCESS_RESOURCES)
@Slf4j
public class DecryptValueMojo extends AbstractValueJasyptMojo {
@Override
protected void run(final EncryptionService service, final String value, String encryptPrefix, String encryptSuffix, String decryptPrefix, String decryptSuffix) throws
MojoExecutionException {
try {
String actualValue = value.startsWith(encryptPrefix) ? value.substring(encryptPrefix.length(), value.length() - encryptSuffix.length()) : value;
log.info("Decrypting value " + actualValue);
String decryptedValue = service.decryptValue(actualValue);
log.info("\n" + decryptedValue);
} catch (Exception e) {
throw new MojoExecutionException("Error Decrypting: " + e.getMessage(), e);
}
}
}
|
Add Rest API restrictions to Project Iterations.
(rhbz750673) | package org.zanata.rest.client;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.HEAD;
import javax.ws.rs.PUT;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.jboss.resteasy.client.ClientResponse;
import org.zanata.rest.MediaTypes;
import org.zanata.rest.dto.Project;
import org.zanata.rest.service.ProjectResource;
//@Path("/projects/p/{projectSlug}")
public interface IProjectResource extends ProjectResource
{
@HEAD
@Produces({ MediaTypes.APPLICATION_ZANATA_PROJECT_XML, MediaTypes.APPLICATION_ZANATA_PROJECT_JSON, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public ClientResponse head();
@GET
@Produces( { MediaTypes.APPLICATION_ZANATA_PROJECT_XML, MediaTypes.APPLICATION_ZANATA_PROJECT_ITERATION_JSON })
public ClientResponse<Project> get();
@PUT
@Consumes( { MediaTypes.APPLICATION_ZANATA_PROJECT_XML, MediaTypes.APPLICATION_ZANATA_PROJECT_ITERATION_JSON })
public ClientResponse put(Project project);
}
| package org.zanata.rest.client;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Produces;
import org.jboss.resteasy.client.ClientResponse;
import org.zanata.rest.MediaTypes;
import org.zanata.rest.dto.Project;
import org.zanata.rest.service.ProjectResource;
//@Path("/projects/p/{projectSlug}")
public interface IProjectResource extends ProjectResource
{
@GET
@Produces( { MediaTypes.APPLICATION_ZANATA_PROJECT_XML, MediaTypes.APPLICATION_ZANATA_PROJECT_ITERATION_JSON })
public ClientResponse<Project> get();
@PUT
@Consumes( { MediaTypes.APPLICATION_ZANATA_PROJECT_XML, MediaTypes.APPLICATION_ZANATA_PROJECT_ITERATION_JSON })
public ClientResponse put(Project project);
}
|
Stop an api error from crashing the program | package main
import (
"github.com/grsakea/kappastat/common"
"github.com/mrshankly/go-twitch/twitch"
"log"
"time"
)
func loopViewers(client *twitch.Client, c chan Message, infos chan kappastat.ViewerCount) {
followed := []string{}
ticker := time.NewTicker(time.Minute).C
for {
select {
case msg := <-c:
followed = followedHandler(followed, msg)
case <-ticker:
for _, v := range followed {
infos <- fetchViewers(client, v)
}
}
}
}
func fetchViewers(client *twitch.Client, chan_string string) kappastat.ViewerCount {
channel, err := client.Streams.Channel(chan_string)
if err != nil {
channel, err = client.Streams.Channel(chan_string)
if err != nil {
log.Print(err)
}
}
return kappastat.ViewerCount{chan_string, time.Now(), channel.Stream.Viewers}
}
| package main
import (
"github.com/grsakea/kappastat/common"
"github.com/mrshankly/go-twitch/twitch"
"log"
"time"
)
func loopViewers(client *twitch.Client, c chan Message, infos chan kappastat.ViewerCount) {
followed := []string{}
ticker := time.NewTicker(time.Minute).C
for {
select {
case msg := <-c:
followed = followedHandler(followed, msg)
case <-ticker:
for _, v := range followed {
infos <- fetchViewers(client, v)
}
}
}
}
func fetchViewers(client *twitch.Client, chan_string string) kappastat.ViewerCount {
channel, err := client.Streams.Channel(chan_string)
if err != nil {
channel, err = client.Streams.Channel(chan_string)
if err != nil {
log.Fatal(err)
}
}
return kappastat.ViewerCount{chan_string, time.Now(), channel.Stream.Viewers}
}
|
Set correct dependent property for formattedTopic | import Ember from 'ember';
export default Ember.Object.extend({
name: '',
userList: null,
messages: null,
connected: false,
sockethubChannelId: null,
topic: null,
slug: function() {
// This could be based on server type in the future. E.g. IRC would be
// server URL, while Campfire would be another id.
return this.get('name').replace(/#/g,'');
}.property('name'),
formattedTopic: function() {
if (this.get('topic') !== null) {
let topic = linkifyStr(this.get('topic'), {
defaultProtocol: 'https',
linkAttributes: { rel: 'nofollow' }
});
return new Ember.String.htmlSafe(topic);
} else {
return '';
}
}.property('topic')
});
| import Ember from 'ember';
export default Ember.Object.extend({
name: '',
userList: null,
messages: null,
connected: false,
sockethubChannelId: null,
topic: null,
slug: function() {
// This could be based on server type in the future. E.g. IRC would be
// server URL, while Campfire would be another id.
return this.get('name').replace(/#/g,'');
}.property('name'),
formattedTopic: function() {
if (this.get('topic') !== null) {
let topic = linkifyStr(this.get('topic'), {
defaultProtocol: 'https',
linkAttributes: { rel: 'nofollow' }
});
return new Ember.String.htmlSafe(topic);
} else {
return "";
}
}.property('message'),
});
|
Change prop variable names and add more default props | import React from 'react';
import PropTypes from 'prop-types';
import styles from './teamCard.css';
const TeamCard = ({ name, role, slackUsername, email, isBoard, description, imageSrc }) => (
<div className={styles.teamCard}>
{imageSrc && (<img src={imageSrc} alt={`Headshot of ${name}`} />)}
<h6 className={styles.name}>{name}</h6>
<i className={styles.role}>{role}</i>
<hr className={styles.hr} />
{!isBoard && (
<span className={styles.detail}>
<span className={styles.slackUsername}>
<text>{slack}</text>
</span>
<span className={styles.email}>
<text>{email}</text>
</span>
</span>
)}
{isBoard && description && (
<span className={styles.descriptionText}>
<text>{description}</text>
</span>
)}
</div>
);
TeamCard.propTypes = {
name: PropTypes.string.isRequired,
role: PropTypes.string.isRequired,
slackUsername: PropTypes.string,
email: PropTypes.string,
isBoard: PropTypes.bool,
imageSrc: PropTypes.string,
description: PropTypes.string,
};
TeamCard.defaultProps = {
description: null,
email: '',
isBoard: true,
imageSrc: '',
slackUsername: '',
};
export default TeamCard;
| import React from 'react';
import PropTypes from 'prop-types';
import styles from './teamCard.css';
const TeamCard = ({ name, role, slack, email, isBoard, description, imageSrc }) => (
<div className={styles.teamCard}>
{imageSrc && (<img src={imageSrc} alt={`Headshot of ${name}`} />)}
<h6 className={styles.name}>{name}</h6>
<i className={styles.role}>{role}</i>
<hr className={styles.hr} />
{!isBoard && (
<span className={styles.detail}>
<span className={styles.slack}>
<text>{slack}</text>
</span>
<span className={styles.email}>
<text>{email}</text>
</span>
</span>
)}
{isBoard && description && (
<span className={styles.descriptionText}>
<text>{description}</text>
</span>
)}
</div>
);
TeamCard.propTypes = {
name: PropTypes.string.isRequired,
role: PropTypes.string.isRequired,
slack: PropTypes.string.isRequired,
email: PropTypes.string.isRequired,
isBoard: PropTypes.bool,
imageSrc: PropTypes.string,
description: PropTypes.string,
};
TeamCard.defaultProps = {
description: null,
isBoard: true,
imageSrc: ''
};
export default TeamCard;
|
Add button, card, dataTable, grid, layout, menu, spinner, tabs and textfield "sub modules" to bundle | const webpack = require('webpack');
const path = require('path');
const libraryName = 'react-to-mdl';
// export config
module.exports = {
devtool: 'cheap-module-eval-source-map',
entry: {
button: './src/button',
card: './src/card',
dataTable: './src/dataTable',
grid: './src/grid',
layout: './src/layout',
menu: './src/menu',
spinner: './src/spinner',
tabs: './src/tabs',
textfield: './src/textfield',
index: './src/index'
},
externals: [
'classnames',
'material-design-lite',
'react',
'react-dom',
'react-router'
],
output: {
path: path.join(__dirname, 'lib'),
filename: '[name].js',
library: libraryName,
libraryTarget: 'umd',
umdNamedDefine: true
},
module: {
loaders: [{
test: /\.jsx?$/,
loader: 'babel',
include: path.join(__dirname, 'src')
}]
}
};
| const webpack = require('webpack');
const path = require('path');
const libraryName = 'react-to-mdl';
// export config
module.exports = {
devtool: 'cheap-module-eval-source-map',
entry: {
layout: './src/layout',
index: './src/index'
},
externals: [
'classnames',
'material-design-lite',
'react',
'react-dom',
'react-router'
],
output: {
path: path.join(__dirname, 'lib'),
filename: '[name].js',
library: libraryName,
libraryTarget: 'umd',
umdNamedDefine: true
},
module: {
loaders: [{
test: /\.jsx?$/,
loader: 'babel',
include: path.join(__dirname, 'src')
}]
}
};
|
fix(writer): Fix path generation for windows
Closes #28 | import fs from 'fs';
import path from 'path';
import dot from 'dot';
import { encoding } from '../constants';
dot.templateSettings.strip = false;
function getRelativePaths(fromDir, files) {
files.sort();
return files.map((file) => {
let relativePath = path.relative(fromDir, file);
if (relativePath.substr(0, 2) !== '..' || relativePath.substr(0, 2) !== './') {
relativePath = `./${relativePath}`;
}
relativePath = require('os').platform() === 'win32' ? relativePath.replace(/\\/g, '/') : relativePath
return {
relative: relativePath,
full: file,
};
});
}
function ensureFileDirectoryExists(filePath) {
const directory = path.dirname(filePath);
if (!fs.existsSync(directory)) {
fs.mkdirSync(directory);
}
}
export const templateContents = `
// template for doT (https://github.com/olado/doT)
function loadStories() {
{{~it.files :value:index}}require('{{=value.relative}}');
{{~}}
}
module.exports = {
loadStories,
};
`;
export function writeFile(files, outputPath) {
const template = dot.template(templateContents);
const relativePaths = getRelativePaths(path.dirname(outputPath), files);
const output = template({ files: relativePaths });
ensureFileDirectoryExists(outputPath);
fs.writeFileSync(outputPath, output, { encoding });
}
| import fs from 'fs';
import path from 'path';
import dot from 'dot';
import { encoding } from '../constants';
dot.templateSettings.strip = false;
function getRelativePaths(fromDir, files) {
files.sort();
return files.map((file) => {
let relativePath = path.relative(fromDir, file);
if (relativePath.substr(0, 2) !== '..' || relativePath.substr(0, 2) !== './') {
relativePath = `./${relativePath}`;
}
return {
relative: relativePath,
full: file,
};
});
}
function ensureFileDirectoryExists(filePath) {
const directory = path.dirname(filePath);
if (!fs.existsSync(directory)) {
fs.mkdirSync(directory);
}
}
export const templateContents = `
// template for doT (https://github.com/olado/doT)
function loadStories() {
{{~it.files :value:index}}require('{{=value.relative}}');
{{~}}
}
module.exports = {
loadStories,
};
`;
export function writeFile(files, outputPath) {
const template = dot.template(templateContents);
const relativePaths = getRelativePaths(path.dirname(outputPath), files);
const output = template({ files: relativePaths });
ensureFileDirectoryExists(outputPath);
fs.writeFileSync(outputPath, output, { encoding });
}
|
Update timestamps of generated feeds as well | from pelican import signals
import logging
import os
import time
logger = logging.getLogger(__name__)
def set_file_utime(path, datetime):
mtime = time.mktime(datetime.timetuple())
logger.info('touching %s', path)
os.utime(path, (mtime, mtime))
def touch_file(path, context):
content = context.get('article', context.get('page'))
page = context.get('articles_page')
dates = context.get('dates')
if content and hasattr(content, 'date'):
set_file_utime(path, content.date)
elif page:
set_file_utime(path, max(x.date for x in page.object_list))
elif dates:
set_file_utime(path, max(x.date for x in dates))
def touch_feed(path, context, feed):
set_file_utime(path, max(x['pubdate'] for x in feed.items))
def register():
signals.content_written.connect(touch_file)
signals.feed_written.connect(touch_feed)
| from pelican import signals
import logging
import os
import time
logger = logging.getLogger(__name__)
def set_file_utime(path, datetime):
mtime = time.mktime(datetime.timetuple())
logger.info('touching %s', path)
os.utime(path, (mtime, mtime))
def touch_file(path, context):
content = context.get('article', context.get('page'))
page = context.get('articles_page')
dates = context.get('dates')
if content and hasattr(content, 'date'):
set_file_utime(path, content.date)
elif page:
set_file_utime(path, max(x.date for x in page.object_list))
elif dates:
set_file_utime(path, max(x.date for x in dates))
def register():
signals.content_written.connect(touch_file)
|
Resolve a warning in eclipse | /**
* Copyright 2010-2014 Ralph Schaer <ralphschaer@gmail.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 ch.ralscha.extdirectspring;
import org.springframework.context.annotation.ComponentScan;
/**
* No-op marker interface. Helps to configure extdirectspring in a type-safe way with
* {@link ComponentScan#basePackageClasses()}
* <p>
*
* <pre>
* {@literal @}Configuration
* {@literal @}ComponentScan(basePackageClasses=ExtDirectSpring.class)
* public class Application { ... }
* </pre>
*/
public interface ExtDirectSpring {
// nothing here. just a marker interface
}
| /**
* Copyright 2010-2014 Ralph Schaer <ralphschaer@gmail.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 ch.ralscha.extdirectspring;
import org.springframework.context.annotation.ComponentScan;
/**
* No-op marker interface. Helps to configure extdirectspring in a type-safe way with
* {@link ComponentScan#basePackageClasses()}
* <p>
*
* <pre>
* {@literal @}Configuration
* {@literal @}ComponentScan(basePackageClasses=ExtDirectSpring.class)
* public class Application { ... }
* </pre>
*/
public interface ExtDirectSpring {
}
|
Simplify the code a little | from awacs.aws import Statement, Principal, Allow, Policy
from awacs import sts
def make_simple_assume_statement(principal):
return Statement(
Principal=Principal('Service', [principal]),
Effect=Allow,
Action=[sts.AssumeRole])
def get_default_assumerole_policy(region=''):
""" Helper function for building the Default AssumeRole Policy
Taken from here:
https://github.com/boto/boto/blob/develop/boto/iam/connection.py#L29
Used to allow ec2 instances to assume the roles in their InstanceProfile.
"""
service = 'ec2.amazonaws.com'
if region == 'cn-north-1':
service = 'ec2.amazonaws.com.cn'
policy = Policy(
Statement=[make_simple_assume_statement(service)]
)
return policy
def get_ecs_assumerole_policy(region=''):
""" Helper function for building the ECS AssumeRole Policy
"""
service = 'ecs.amazonaws.com'
policy = Policy(
Statement=[make_simple_assume_statement(service)]
)
return policy
| from awacs.aws import Statement, Principal, Allow, Policy
from awacs import sts
def get_default_assumerole_policy(region=''):
""" Helper function for building the Default AssumeRole Policy
Taken from here:
https://github.com/boto/boto/blob/develop/boto/iam/connection.py#L29
Used to allow ec2 instances to assume the roles in their InstanceProfile.
"""
service = 'ec2.amazonaws.com'
if region == 'cn-north-1':
service = 'ec2.amazonaws.com.cn'
policy = Policy(
Statement=[
Statement(
Principal=Principal('Service', [service]),
Effect=Allow,
Action=[sts.AssumeRole]
)
]
)
return policy
def get_ecs_assumerole_policy(region=''):
""" Helper function for building the ECS AssumeRole Policy
"""
service = 'ecs.amazonaws.com'
policy = Policy(
Statement=[
Statement(
Principal=Principal('Service', [service]),
Effect=Allow,
Action=[sts.AssumeRole]
)
]
)
return policy
|
Add some verbosity when there are lock errors | package mig
import (
"errors"
"log"
"sync"
"time"
)
var mutex = sync.Mutex{}
var ErrDatabaseLockTimout = errors.New("mig.WithDatabaseLock timed out")
func WithDatabaseLock(db DB, timeout time.Duration, callback func() error) error {
start := time.Now()
_, _ = db.Exec(`
CREATE TABLE MIG_DATABASE_LOCK (
lock_row int,
UNIQUE (lock_row)
)
`)
for {
_, err := db.Exec(`
INSERT INTO MIG_DATABASE_LOCK (lock_row)
VALUES (1)
`)
if err == nil {
break
}
log.Printf("err: %#v", err)
if time.Now().Sub(start) > timeout {
return ErrDatabaseLockTimout
}
time.Sleep(1500 * time.Millisecond)
}
defer func() {
_, _ = db.Exec(`
DELETE FROM MIG_DATABASE_LOCK
`)
}()
return callback()
}
| package mig
import (
"errors"
"sync"
"time"
)
var mutex = sync.Mutex{}
var ErrDatabaseLockTimout = errors.New("mig.WithDatabaseLock timed out")
func WithDatabaseLock(db DB, timeout time.Duration, callback func() error) error {
start := time.Now()
_, _ = db.Exec(`
CREATE TABLE MIG_DATABASE_LOCK (
lock_row int,
UNIQUE (lock_row)
)
`)
for {
_, err := db.Exec(`
INSERT INTO MIG_DATABASE_LOCK (lock_row)
VALUES (1)
`)
if err == nil {
break
}
if time.Now().Sub(start) > timeout {
return ErrDatabaseLockTimout
}
time.Sleep(500 * time.Millisecond)
}
defer func() {
_, _ = db.Exec(`
DELETE FROM MIG_DATABASE_LOCK
`)
}()
return callback()
}
|
Add setting for enabling / disabling replays | <?php
return [
/*
|--------------------------------------------------------------------------
| The algorithm to sign the request with
|--------------------------------------------------------------------------
|
| This is the algorithm we'll use to sign the request.
*/
'algorithm' => env('SIGNED_REQUEST_ALGORITHM', 'sha256'),
/*
|--------------------------------------------------------------------------
| Allows the application to disable / enable request replay's
|--------------------------------------------------------------------------
|
| If set to false, requests will automatically expire after 5 minutes.
| During the 5 minute window, request id's will only be valid once.
*/
'allow-replays' => env('SIGNED_REQUEST_ALLOW_REPLAYS', false),
/*
|--------------------------------------------------------------------------
| Available header overrides
|--------------------------------------------------------------------------
|
| This allows you to customize the http headers that will be inspected to
| look for the signature and algorithm respectively.
*/
'headers' => [
'signature' => env('SIGNED_REQUEST_SIGNATURE_HEADER', 'X-Signature'),
'algorithm' => env('SIGNED_REQUEST_ALGORITHM_HEADER', 'X-Algorithm')
],
/*
|--------------------------------------------------------------------------
| The key for signing requests for verification.
|--------------------------------------------------------------------------
|
| This value is the key we'll use to verify signatures with. By default this
| key is expected from the environment. You can change this behaviour,
| however it is not recommended.
*/
'key' => env('SIGNED_REQUEST_KEY', 'key')
];
| <?php
return [
/*
|--------------------------------------------------------------------------
| The algorithm to sign the request with
|--------------------------------------------------------------------------
|
| This is the algorithm we'll use to sign the
*/
'algorithm' => env('SIGNED_REQUEST_ALGORITHM', 'sha256'),
/*
|--------------------------------------------------------------------------
| Available header overrides
|--------------------------------------------------------------------------
|
| This allows you to customize the http headers that will be inspected to
| look for the signature and algorithm respectively.
*/
'headers' => [
'signature' => env('SIGNED_REQUEST_SIGNATURE_HEADER', 'X-Signature'),
'algorithm' => env('SIGNED_REQUEST_ALGORITHM_HEADER', 'X-Algorithm')
],
/*
|--------------------------------------------------------------------------
| The key for signing requests for verification.
|--------------------------------------------------------------------------
|
| This value is the key we'll use to verify signatures with. By default this
| key is expected from the environment. You can change this behaviour,
| however it is not recommended.
*/
'key' => env('SIGNED_REQUEST_KEY', 'key')
];
|
Remove dependency install (we don't have any) | 'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var AppengineGenerator = module.exports = function AppengineGenerator(args, options, config) {
yeoman.generators.Base.apply(this, arguments);
this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};
util.inherits(AppengineGenerator, yeoman.generators.Base);
AppengineGenerator.prototype.askFor = function askFor() {
var cb = this.async();
// have Yeoman greet the user.
console.log(this.yeoman);
var prompts = [{
name: 'appId',
message: 'What is the application ID?',
default: 'new-application'
}];
this.prompt(prompts, function (props) {
this.appId = props.appId;
cb();
}.bind(this));
};
AppengineGenerator.prototype.projectfiles = function projectfiles() {
this.copy('editorconfig', '.editorconfig');
};
AppengineGenerator.prototype.AppEngineFiles = function AppEngineFiles() {
this.template('app.yaml');
};
| 'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var AppengineGenerator = module.exports = function AppengineGenerator(args, options, config) {
yeoman.generators.Base.apply(this, arguments);
this.on('end', function () {
this.installDependencies({ skipInstall: options['skip-install'] });
});
this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};
util.inherits(AppengineGenerator, yeoman.generators.Base);
AppengineGenerator.prototype.askFor = function askFor() {
var cb = this.async();
// have Yeoman greet the user.
console.log(this.yeoman);
var prompts = [{
name: 'appId',
message: 'What is the application ID?',
default: 'new-application'
}];
this.prompt(prompts, function (props) {
this.appId = props.appId;
cb();
}.bind(this));
};
AppengineGenerator.prototype.projectfiles = function projectfiles() {
this.copy('editorconfig', '.editorconfig');
};
AppengineGenerator.prototype.AppEngineFiles = function AppEngineFiles() {
this.template('app.yaml');
};
|
Fix observable base for objectsSet | 'use strict';
var setPrototypeOf = require('es5-ext/object/set-prototype-of')
, d = require('d/d')
, PrimitiveSet = require('es6-set/primitive')
, createReadOnly = require('observable-set/create-read-only')
, createObservable = require('observable-set/create-complete')
, serializeObject = require('./serialize/object')
, defFilterByKey = require('./utils/define-filter-by-key')
, keys = Object.keys
, ObjectsSet;
ObjectsSet = function () { PrimitiveSet.call(this); };
setPrototypeOf(ObjectsSet, PrimitiveSet);
ObjectsSet.prototype = Object.create(PrimitiveSet.prototype, {
constructor: d(ObjectsSet),
_serialize: d(serializeObject),
getById: d(function (id) { return this.__setData__[id] || null; }),
_plainForEach_: d(function (cb/*, thisArg*/) {
var thisArg = arguments[1];
keys(this.__setData__).forEach(function (key) {
cb.call(thisArg, this[key]);
}, this.__setData__);
})
});
defFilterByKey(ObjectsSet.prototype);
module.exports = createReadOnly(createObservable(ObjectsSet));
| 'use strict';
var setPrototypeOf = require('es5-ext/object/set-prototype-of')
, d = require('d/d')
, PrimitiveSet = require('observable-set/create-read-only')(
require('observable-set/primitive')
)
, serializeObject = require('./serialize/object')
, defFilterByKey = require('./utils/define-filter-by-key')
, keys = Object.keys
, ObjectsSet;
ObjectsSet = module.exports = function () { PrimitiveSet.call(this); };
setPrototypeOf(ObjectsSet, PrimitiveSet);
ObjectsSet.prototype = Object.create(PrimitiveSet.prototype, {
constructor: d(ObjectsSet),
_serialize: d(serializeObject),
getById: d(function (id) { return this.__setData__[id] || null; }),
_plainForEach_: d(function (cb/*, thisArg*/) {
var thisArg = arguments[1];
keys(this.__setData__).forEach(function (key) {
cb.call(thisArg, this[key]);
}, this.__setData__);
})
});
defFilterByKey(ObjectsSet.prototype);
|
Split the XFR output into an array of values.
Had to split on \n. Need to go through the code more and figure out why it doesn't actually present itself
upon printing | #!/usr/bin/env python
import dns.query
import dns.zone
import sys
from optparse import OptionParser
parser = OptionParser()
parser.add_option("--server", dest="dns_server",
help="DNS server to query.",
type="string")
parser.add_option("--zone", dest="dns_zone",
help="Zone to print.",
type="string")
(options, args) = parser.parse_args()
print "Server: %s Zone: %s" % (options.dns_server, options.dns_zone)
try:
z = dns.zone.from_xfr(dns.query.xfr(options.dns_server, options.dns_zone))
names = z.nodes.keys()
names.sort()
zone_xfr_array = []
for n in names:
current_record = z[n].to_text(n)
for split_record in current_record.split("\n"):
zone_xfr_array.append([split_record])
except dns.exception.FormError:
print "The transfer encountered a problem."
for current_record in zone_xfr_array:
print current_record
| #!/usr/bin/env python
import dns.query
import dns.zone
import sys
from optparse import OptionParser
parser = OptionParser()
parser.add_option("--server", dest="dns_server",
help="DNS server to query.",
type="string")
parser.add_option("--zone", dest="dns_zone",
help="Zone to print.",
type="string")
(options, args) = parser.parse_args()
print "Server: %s Zone: %s" % (options.dns_server, options.dns_zone)
try:
z = dns.zone.from_xfr(dns.query.xfr(options.dns_server, options.dns_zone))
names = z.nodes.keys()
names.sort()
for n in names:
print z[n].to_text(n)
except dns.exception.FormError:
print "The transfer encountered a problem."
|
BootService: Add a check to appease LINT/Android Studio | /*
* Copyright (C) 2015 Willi Ye
*
* 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.grarak.kerneladiutor.services;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.grarak.kerneladiutor.utils.Utils;
import com.grarak.kerneladiutor.utils.database.ProfileDB;
/**
* Created by willi on 27.12.14.
*/
public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if ("BOOT_COMPLETED".equals(intent.getAction())) {
if (Utils.getBoolean("emulateinit.d", false, context))
context.startService(new Intent(context, InitdService.class));
context.startService(new Intent(context, BootService.class));
ProfileTileReceiver.publishProfileTile(new ProfileDB(context).getAllProfiles(), context);
}
}
}
| /*
* Copyright (C) 2015 Willi Ye
*
* 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.grarak.kerneladiutor.services;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.grarak.kerneladiutor.utils.Utils;
import com.grarak.kerneladiutor.utils.database.ProfileDB;
/**
* Created by willi on 27.12.14.
*/
public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Utils.getBoolean("emulateinit.d", false, context))
context.startService(new Intent(context, InitdService.class));
context.startService(new Intent(context, BootService.class));
ProfileTileReceiver.publishProfileTile(new ProfileDB(context).getAllProfiles(), context);
}
}
|
Fix can't publish config file. | <?php
namespace LaravelLb;
use Illuminate\Support\ServiceProvider;
class LaravelLbServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
$this->publishes([
__DIR__.'/../config/logicboxes.php' => config_path('logicboxes.php'),
]);
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->app->bind('LaravelLb\LogicBoxes', function ($app) {
$testMode = config('logicboxes.test_mode');
$userId = config('logicboxes.auth_userid');
$apiKey = config('logicboxes.api_key');
return new LogicBoxes($userId, $apiKey, $testMode);
});
}
}
| <?php
namespace LaravelLb;
use Illuminate\Support\ServiceProvider;
class LaravelLbServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
$this->publishes([
__DIR__.'../config/logicboxes.php' => config_path('logicboxes.php'),
]);
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->app->bind('LaravelLb\LogicBoxes', function ($app) {
$testMode = config('logicboxes.test_mode');
$userId = config('logicboxes.auth_userid');
$apiKey = config('logicboxes.api_key');
return new LogicBoxes($userId, $apiKey, $testMode);
});
}
}
|
Use if/else and direct function calls over try/catch + bind | import CoreObject from './metal/core-object';
function wrapConsole(logCommand) {
const logMethod = function () {
/* eslint-disable no-console */
if (console[logCommand]) {
console[logCommand](...arguments);
} else {
console.log(...arguments);
}
/* eslint-enable no-console */
};
return function () {
const args = [...arguments];
args.unshift('[JS-BUY-SDK]: ');
logMethod(...args);
};
}
const Logger = CoreObject.extend({
/**
* Wrapper around the console log so in the future we can have better dev output.
* Also allows us to disable output in production.
* @class Logger
* @constructor
*/
constructor() { },
debug: wrapConsole('debug'),
info: wrapConsole('info'),
warn: wrapConsole('warn'),
error: wrapConsole('error')
});
export { wrapConsole };
export default new Logger();
| import CoreObject from './metal/core-object';
function wrapConsole(logCommand) {
let logMethod;
/* eslint-disable no-console */
try {
logMethod = Function.prototype.bind.call(console[logCommand], console);
} catch (e) {
logMethod = Function.prototype.bind.call(console.log, console);
}
/* eslint-enable no-console */
return function () {
const args = Array.prototype.slice.call(arguments);
args.unshift('[JS-BUY-SDK]: ');
logMethod.apply(console, args);
};
}
const Logger = CoreObject.extend({
/**
* Wrapper around the console log so in the future we can have better dev output.
* Also allows us to disable output in production.
* @class Logger
* @constructor
*/
constructor() { },
debug: wrapConsole('debug'),
info: wrapConsole('info'),
warn: wrapConsole('warn'),
error: wrapConsole('error')
});
export { wrapConsole };
export default new Logger();
|
Use @clevercloud/client superagent helper instead of request | 'use strict';
const { addOauthHeader } = require('@clevercloud/client/cjs/oauth.node.js');
const { prefixUrl } = require('@clevercloud/client/cjs/prefix-url.js');
const { request } = require('@clevercloud/client/cjs/request.superagent.js');
const { conf, loadOAuthConf } = require('../models/configuration.js');
async function sendToApi (requestParams) {
const tokens = await loadOAuthConf().toPromise();
return Promise.resolve(requestParams)
.then(prefixUrl(conf.API_HOST))
.then(addOauthHeader({
OAUTH_CONSUMER_KEY: conf.OAUTH_CONSUMER_KEY,
OAUTH_CONSUMER_SECRET: conf.OAUTH_CONSUMER_SECRET,
API_OAUTH_TOKEN: tokens.token,
API_OAUTH_TOKEN_SECRET: tokens.secret,
}))
.then(request);
}
async function getHostAndTokens () {
const userTokens = await loadOAuthConf().toPromise();
return {
apiHost: conf.API_HOST,
tokens: {
OAUTH_CONSUMER_KEY: conf.OAUTH_CONSUMER_KEY,
OAUTH_CONSUMER_SECRET: conf.OAUTH_CONSUMER_SECRET,
API_OAUTH_TOKEN: userTokens.token,
API_OAUTH_TOKEN_SECRET: userTokens.secret,
},
};
}
module.exports = { sendToApi, getHostAndTokens };
| 'use strict';
const { addOauthHeader } = require('@clevercloud/client/cjs/oauth.node.js');
const { prefixUrl } = require('@clevercloud/client/cjs/prefix-url.js');
const { request } = require('@clevercloud/client/cjs/request.request.js');
const { conf, loadOAuthConf } = require('../models/configuration.js');
async function sendToApi (requestParams) {
const tokens = await loadOAuthConf().toPromise();
return Promise.resolve(requestParams)
.then(prefixUrl(conf.API_HOST))
.then(addOauthHeader({
OAUTH_CONSUMER_KEY: conf.OAUTH_CONSUMER_KEY,
OAUTH_CONSUMER_SECRET: conf.OAUTH_CONSUMER_SECRET,
API_OAUTH_TOKEN: tokens.token,
API_OAUTH_TOKEN_SECRET: tokens.secret,
}))
.then(request);
}
async function getHostAndTokens () {
const userTokens = await loadOAuthConf().toPromise();
return {
apiHost: conf.API_HOST,
tokens: {
OAUTH_CONSUMER_KEY: conf.OAUTH_CONSUMER_KEY,
OAUTH_CONSUMER_SECRET: conf.OAUTH_CONSUMER_SECRET,
API_OAUTH_TOKEN: userTokens.token,
API_OAUTH_TOKEN_SECRET: userTokens.secret,
},
};
}
module.exports = { sendToApi, getHostAndTokens };
|
Implement from social media methods | package identity
import (
"encoding/json"
"errors"
"github.com/google/uuid"
)
// Identity data to be encode in auth token
type Identity struct {
ID uuid.UUID `json:"id"`
Email string `json:"email"`
Roles []string `json:"roles"`
}
// FromGoogleData sets *i to a copy of data.
func (i *Identity) FromGoogleData(data json.RawMessage) error {
if i == nil {
return errors.New("auth.Identity: FromGoogleData on nil pointer")
}
err := json.Unmarshal(data, i)
if err != nil {
return err
}
id, err := uuid.NewRandom()
if err != nil {
return err
}
var defaultRoles []string
i.ID = id
i.Roles = defaultRoles
return nil
}
// FromFacebookData sets *i to a copy of data.
func (i *Identity) FromFacebookData(data json.RawMessage) error {
if i == nil {
return errors.New("auth.Identity: FromFacebookData on nil pointer")
}
err := json.Unmarshal(data, i)
if err != nil {
return err
}
id, err := uuid.NewRandom()
if err != nil {
return err
}
var defaultRoles []string
i.ID = id
i.Roles = defaultRoles
return nil
}
// New returns a new Identity
func New(id uuid.UUID, email string, roles []string) *Identity {
return &Identity{id, email, roles}
}
| package identity
import (
"encoding/json"
"errors"
"github.com/google/uuid"
)
// Identity data to be encode in auth token
type Identity struct {
ID uuid.UUID `json:"id"`
Email string `json:"email"`
Roles []string `json:"roles"`
}
// FromGoogleData sets *i to a copy of data.
func (i *Identity) FromGoogleData(data json.RawMessage) error {
if i == nil {
return errors.New("auth.Identity: FromGoogleData on nil pointer")
}
//todo set props from google data
return nil
}
// FromFacebookData sets *i to a copy of data.
func (i *Identity) FromFacebookData(data json.RawMessage) error {
if i == nil {
return errors.New("auth.Identity: FromFacebookData on nil pointer")
}
//todo set props from facebook data
return nil
}
// New returns a new Identity
func New(id uuid.UUID, email string, roles []string) *Identity {
return &Identity{id, email, roles}
}
|
Use ip instead of localhost for travis | import unittest
import asyncio
import io
import multiprocessing
import urllib.request
import time
import grole
def simple_server():
app = grole.Grole()
@app.route('/')
def hello(env, req):
return 'Hello, World!'
app.run(host='127.0.0.1')
class TestServe(unittest.TestCase):
def test_simple(self):
p = multiprocessing.Process(target=simple_server)
p.start()
time.sleep(0.1)
with urllib.request.urlopen('http://127.0.0.1:1234') as response:
html = response.read()
self.assertEqual(html, b'Hello, World!')
p.terminate()
def test_fileserver(self):
p = multiprocessing.Process(target=grole.main, args=[['-a', '127.0.0.1']])
p.start()
time.sleep(0.1)
with urllib.request.urlopen('http://127.0.0.1:1234/test/test.dat') as response:
html = response.read()
self.assertEqual(html, b'foo\n')
p.terminate()
| import unittest
import asyncio
import io
import multiprocessing
import urllib.request
import time
import grole
def simple_server():
app = grole.Grole()
@app.route('/')
def hello(env, req):
return 'Hello, World!'
app.run()
class TestServe(unittest.TestCase):
def test_simple(self):
p = multiprocessing.Process(target=simple_server)
p.start()
time.sleep(0.1)
with urllib.request.urlopen('http://localhost:1234') as response:
html = response.read()
self.assertEqual(html, b'Hello, World!')
p.terminate()
def test_fileserver(self):
p = multiprocessing.Process(target=grole.main, args=[[]])
p.start()
time.sleep(0.1)
with urllib.request.urlopen('http://localhost:1234/test/test.dat') as response:
html = response.read()
self.assertEqual(html, b'foo\n')
p.terminate()
|
Fix the findService function, add debug logs | import Bacon from 'baconjs'
import R from 'ramda'
import clone from 'clone'
import slug from 'slug'
import serviceTemplate from '../../service.json'
import colors from 'colors'
let debug = require('debug')('tutum-tagger')
export default function createServiceOrTakeExisting(image, buildSetting, tutum) {
return listAllServices(tutum)
.flatMap((services) => {
let imageWithTag = `${image.name}:${buildSetting.tag}`
let findService = R.find(R.propEq('image_name', imageWithTag))
let service = findService(services.objects)
if (service) {
debug(`Service based on ${imageWithTag.cyan} already exists.`)
return service
}
let options = clone(serviceTemplate, false)
options.image = imageWithTag
options.name = slug(buildSetting.branch)
options.container_envvars.push({
key: 'VIRTUAL_PATH',
value: slug(buildSetting.branch)
})
debug(`Creating a new service based on ${imageWithTag.cyan}.`)
return createService(options, tutum)
})
}
function listAllServices(tutum) {
return Bacon.fromPromise(tutum.listServices())
}
function createService(options, tutum) {
return Bacon.fromPromise(tutum.createService(options))
}
| import Bacon from 'baconjs'
import R from 'ramda'
import clone from 'clone'
import slug from 'slug'
import serviceTemplate from '../../service.json'
export default function createServiceOrTakeExisting(image, buildSetting, tutum) {
return listAllServices(tutum)
.flatMap((services) => {
let findService = R.find(R.propEq('image_name', `${image.name}:${buildSetting.tag}`))
let service = findService(services)
if (service) {
return service
}
let options = clone(serviceTemplate, false)
options.image = `${image.name}:${buildSetting.tag}`
options.name = slug(buildSetting.branch)
options.container_envvars.push({
key: 'VIRTUAL_PATH',
value: slug(buildSetting.branch)
})
return createService(options, tutum)
})
}
function listAllServices(tutum) {
return Bacon.fromPromise(tutum.listServices())
}
function createService(options, tutum) {
return Bacon.fromPromise(tutum.createService(options))
}
|
[SwiftSyntax] Add convenience initializer for `BinaryOperatorExpr` | SYNTAX_BUILDABLE_EXPRESSIBLE_AS_CONFORMANCES = {
'DeclBuildable': [
'CodeBlockItem',
'MemberDeclListItem',
'SyntaxBuildable'
],
'ExprList': [
'ConditionElement',
'SyntaxBuildable'
],
'IdentifierPattern': [
'PatternBuildable'
],
'MemberDeclList': [
'MemberDeclBlock'
],
'SimpleTypeIdentifier': [
'TypeAnnotation',
'TypeBuildable',
'TypeExpr'
],
'StmtBuildable': [
'CodeBlockItem',
'SyntaxBuildable'
],
'TokenSyntax': [
'BinaryOperatorExpr'
]
}
| SYNTAX_BUILDABLE_EXPRESSIBLE_AS_CONFORMANCES = {
'DeclBuildable': [
'CodeBlockItem',
'MemberDeclListItem',
'SyntaxBuildable'
],
'ExprList': [
'ConditionElement',
'SyntaxBuildable'
],
'IdentifierPattern': [
'PatternBuildable'
],
'MemberDeclList': [
'MemberDeclBlock'
],
'SimpleTypeIdentifier': [
'TypeAnnotation',
'TypeBuildable',
'TypeExpr'
],
'StmtBuildable': [
'CodeBlockItem',
'SyntaxBuildable'
]
}
|
Remove blanket protection in preparation for granular access control. | # coding: utf-8
# Copyright (c) 2011-2012 Aymeric Augustin. All rights reserved.
from django.conf.urls import patterns, url
from . import views
urlpatterns = patterns('',
url(r'^$', views.GalleryIndexView.as_view(), name='gallery-index'),
url(r'^year/(?P<year>\d{4})/$', views.GalleryYearView.as_view(), name='gallery-year'),
url(r'^album/(?P<pk>\d+)/$', views.AlbumView.as_view(), name='gallery-album'),
url(r'^photo/(?P<pk>\d+)/$', views.PhotoView.as_view(), name='gallery-photo'),
url(r'^original/(?P<pk>\d+)/$', views.original_photo, name='gallery-photo-original'),
url(r'^(?P<preset>\w+)/(?P<pk>\d+)/$', views.resized_photo, name='gallery-photo-resized'),
)
| # coding: utf-8
# Copyright (c) 2011-2012 Aymeric Augustin. All rights reserved.
from django.conf.urls import patterns, url
from django.contrib.auth.decorators import permission_required
from . import views
protect = permission_required('gallery.view')
urlpatterns = patterns('',
url(r'^$', protect(views.GalleryIndexView.as_view()), name='gallery-index'),
url(r'^year/(?P<year>\d{4})/$', protect(views.GalleryYearView.as_view()), name='gallery-year'),
url(r'^album/(?P<pk>\d+)/$', protect(views.AlbumView.as_view()), name='gallery-album'),
url(r'^photo/(?P<pk>\d+)/$', protect(views.PhotoView.as_view()), name='gallery-photo'),
url(r'^original/(?P<pk>\d+)/$', protect(views.original_photo), name='gallery-photo-original'),
url(r'^(?P<preset>\w+)/(?P<pk>\d+)/$', protect(views.resized_photo), name='gallery-photo-resized'),
)
|
Fix mistake in search index update check | from haystack import indexes
from celery_haystack.indexes import CelerySearchIndex
from .models import FoiRequest
class FoiRequestIndex(CelerySearchIndex, indexes.Indexable):
text = indexes.EdgeNgramField(document=True, use_template=True)
title = indexes.CharField(model_attr='title')
description = indexes.CharField(model_attr='description')
resolution = indexes.CharField(model_attr='resolution', default="")
status = indexes.CharField(model_attr='status')
readable_status = indexes.CharField(model_attr='readable_status')
first_message = indexes.DateTimeField(model_attr='first_message')
last_message = indexes.DateTimeField(model_attr='last_message')
url = indexes.CharField(model_attr='get_absolute_url')
public_body_name = indexes.CharField(model_attr='public_body__name', default="")
def get_model(self):
return FoiRequest
def index_queryset(self):
"""Used when the entire index for model is updated."""
return self.get_model().published.get_for_search_index()
def should_update(self, instance, **kwargs):
return instance.visibility > 1
| from haystack import indexes
from celery_haystack.indexes import CelerySearchIndex
from .models import FoiRequest
class FoiRequestIndex(CelerySearchIndex, indexes.Indexable):
text = indexes.EdgeNgramField(document=True, use_template=True)
title = indexes.CharField(model_attr='title')
description = indexes.CharField(model_attr='description')
resolution = indexes.CharField(model_attr='resolution', default="")
status = indexes.CharField(model_attr='status')
readable_status = indexes.CharField(model_attr='readable_status')
first_message = indexes.DateTimeField(model_attr='first_message')
last_message = indexes.DateTimeField(model_attr='last_message')
url = indexes.CharField(model_attr='get_absolute_url')
public_body_name = indexes.CharField(model_attr='public_body__name', default="")
def get_model(self):
return FoiRequest
def index_queryset(self):
"""Used when the entire index for model is updated."""
return self.get_model().published.get_for_search_index()
def should_update(self, instance, **kwargs):
return self.instance.visibility > 1
|
Correct the registry address for the provider server | package main
import (
"context"
"flag"
"log"
"github.com/hashicorp/terraform-plugin-framework/providerserver"
"github.com/terraform-providers/terraform-provider-null/internal/provider"
)
// Run "go generate" to format example terraform files and generate the docs for the registry/website
// If you do not have terraform installed, you can remove the formatting command, but its suggested to
// ensure the documentation is formatted properly.
//go:generate terraform fmt -recursive ./examples/
// Run the docs generation tool, check its repository for more information on how it works and how docs
// can be customized.
//go:generate go run github.com/hashicorp/terraform-plugin-docs/cmd/tfplugindocs
func main() {
var debug bool
flag.BoolVar(&debug, "debug", false, "set to true to run the provider with support for debuggers like delve")
flag.Parse()
err := providerserver.Serve(context.Background(), provider.New, providerserver.ServeOpts{
Address: "registry.terraform.io/hashicorp/null",
Debug: debug,
ProtocolVersion: 5,
})
if err != nil {
log.Fatal(err)
}
}
| package main
import (
"context"
"flag"
"log"
"github.com/hashicorp/terraform-plugin-framework/providerserver"
"github.com/terraform-providers/terraform-provider-null/internal/provider"
)
// Run "go generate" to format example terraform files and generate the docs for the registry/website
// If you do not have terraform installed, you can remove the formatting command, but its suggested to
// ensure the documentation is formatted properly.
//go:generate terraform fmt -recursive ./examples/
// Run the docs generation tool, check its repository for more information on how it works and how docs
// can be customized.
//go:generate go run github.com/hashicorp/terraform-plugin-docs/cmd/tfplugindocs
func main() {
var debug bool
flag.BoolVar(&debug, "debug", false, "set to true to run the provider with support for debuggers like delve")
flag.Parse()
err := providerserver.Serve(context.Background(), provider.New, providerserver.ServeOpts{
Address: "registry.terraform.io/hashicorp/time",
Debug: debug,
ProtocolVersion: 5,
})
if err != nil {
log.Fatal(err)
}
}
|
Include udiskie-mount in binary distribution | # encoding: utf-8
from distutils.core import setup
with open('README.rst') as readme:
long_description = readme.read()
setup(
name='udiskie',
version='0.4.2',
description='Removable disk automounter for udisks',
long_description=long_description,
author='Byron Clark',
author_email='byron@theclarkfamily.name',
maintainer='Thomas Gläßle',
maintainer_email='t_glaessle@gmx.de',
url='https://github.com/coldfix/udiskie',
license='MIT',
packages=[
'udiskie',
],
scripts=[
'bin/udiskie',
'bin/udiskie-umount',
'bin/udiskie-mount'
],
)
| # encoding: utf-8
from distutils.core import setup
with open('README.rst') as readme:
long_description = readme.read()
setup(
name='udiskie',
version='0.4.2',
description='Removable disk automounter for udisks',
long_description=long_description,
author='Byron Clark',
author_email='byron@theclarkfamily.name',
maintainer='Thomas Gläßle',
maintainer_email='t_glaessle@gmx.de',
url='https://github.com/coldfix/udiskie',
license='MIT',
packages=[
'udiskie',
],
scripts=[
'bin/udiskie',
'bin/udiskie-umount',
],
)
|
Add a new adminarea.header.system menu | <header class="main-header fh-fixedHeader">
<a href="#" class="logo" data-toggle="push-menu" role="button">
<!-- mini logo for sidebar mini 50x50 pixels -->
<span class="logo-mini"><i class="fa fa-home"></i></span>
<!-- logo for regular state and mobile devices -->
<span class="logo-lg"><b>{{ config('app.name') }}</b></span>
</a>
<nav class="navbar navbar-static-top">
<div class="navbar-custom-menu pull-left">
<ul class="nav navbar-nav">
<li><a href="{{ route('adminarea.home') }}"><i class="fa fa-home"></i> {{ trans('cortex/foundation::common.home') }}</a></li>
</ul>
</div>
<div class="navbar-custom-menu">
{!! Menu::render('adminarea.header.language') !!}
{!! Menu::render('adminarea.header.system') !!}
{!! Menu::render('adminarea.header.user') !!}
</div>
</nav>
</header>
| <header class="main-header fh-fixedHeader">
<a href="#" class="logo" data-toggle="push-menu" role="button">
<!-- mini logo for sidebar mini 50x50 pixels -->
<span class="logo-mini"><i class="fa fa-home"></i></span>
<!-- logo for regular state and mobile devices -->
<span class="logo-lg"><b>{{ config('app.name') }}</b></span>
</a>
<nav class="navbar navbar-static-top">
<div class="navbar-custom-menu pull-left">
<ul class="nav navbar-nav">
<li><a href="{{ route('adminarea.home') }}"><i class="fa fa-home"></i> {{ trans('cortex/foundation::common.home') }}</a></li>
</ul>
</div>
<div class="navbar-custom-menu">
{!! Menu::render('adminarea.header.language') !!}
{!! Menu::render('adminarea.header.user') !!}
</div>
</nav>
</header>
|
Fix scope access in index acceptance test 🔨
This somehow only just started causing problems in ember-cli >= 2.8.0 | import { test } from 'qunit';
import moduleForAcceptance from '../../tests/helpers/module-for-acceptance';
moduleForAcceptance('Acceptance | Polymer | index');
test('visiting /', function(assert) {
visit('/');
andThen(function() {
assert.equal(currentURL(), '/');
});
andThen(function() {
let done = assert.async();
let testElement = () => {
assert.ok(document.querySelector('paper-button').shadowRoot,
'paper-button has shadowRoot');
assert.equal($('paper-button').attr('role'), 'button',
'paper-button rendered successfully');
done();
};
if (window.Polymer.Settings.nativeShadow) {
testElement();
} else {
// wait for elements to be polyfilled
window.addEventListener('WebComponentsReady', testElement);
}
});
});
| import { test } from 'qunit';
import moduleForAcceptance from '../../tests/helpers/module-for-acceptance';
moduleForAcceptance('Acceptance | Polymer | index');
test('visiting /', function(assert) {
visit('/');
andThen(function() {
assert.equal(this.currentURL(), '/');
});
andThen(function() {
let done = assert.async();
let testElement = () => {
assert.ok(document.querySelector('paper-button').shadowRoot,
'paper-button has shadowRoot');
assert.equal(this.$('paper-button').attr('role'), 'button',
'paper-button rendered successfully');
done();
};
if (window.Polymer.Settings.nativeShadow) {
testElement();
} else {
// wait for elements to be polyfilled
window.addEventListener('WebComponentsReady', testElement);
}
});
});
|
Add .gz and bgzf.gz files to infer unit tests | package org.seqdoop.hadoop_bam;
import java.io.IOException;
import java.io.InputStream;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public class TestVCFFormat {
@Test
public void testInferFromFilePath() throws IOException {
assertEquals(VCFFormat.VCF, VCFFormat.inferFromFilePath("test.vcf"));
assertEquals(VCFFormat.VCF, VCFFormat.inferFromFilePath("test.vcf.gz"));
assertEquals(VCFFormat.VCF, VCFFormat.inferFromFilePath("test.vcf.bgzf.gz"));
assertNull(VCFFormat.inferFromFilePath("test.sam"));
}
@Test
public void testInferFromData() throws IOException {
assertEquals(VCFFormat.VCF, VCFFormat.inferFromData(stream("test.vcf")));
assertEquals(VCFFormat.VCF, VCFFormat.inferFromData(stream("test.vcf.gz")));
assertEquals(VCFFormat.VCF, VCFFormat.inferFromData(stream("test.vcf.bgzf.gz")));
assertNull(VCFFormat.inferFromData(stream("test.sam")));
}
private InputStream stream(String resource) throws IOException {
return ClassLoader.getSystemClassLoader().getResource(resource).openStream();
}
}
| package org.seqdoop.hadoop_bam;
import java.io.IOException;
import java.io.InputStream;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public class TestVCFFormat {
@Test
public void testInferFromFilePath() throws IOException {
assertEquals(VCFFormat.VCF, VCFFormat.inferFromFilePath("test.vcf"));
assertEquals(VCFFormat.VCF, VCFFormat.inferFromFilePath("test.vcf.gz"));
assertNull(VCFFormat.inferFromFilePath("test.sam"));
}
@Test
public void testInferFromData() throws IOException {
assertEquals(VCFFormat.VCF, VCFFormat.inferFromData(stream("test.vcf")));
assertNull(VCFFormat.inferFromData(stream("test.sam")));
}
private InputStream stream(String resource) throws IOException {
return ClassLoader.getSystemClassLoader().getResource(resource).openStream();
}
}
|
Make use of es6 template literals | const join = require('path').join
const execSync = require('child_process').execSync
const Interactive = require('./interactive')
/**
* Reads a file glob and a commit message, and commits to git.
* @class
*/
class GitAddAndCommit {
constructor(options) {
if (options.help) {
this.showHelpScreen()
} else if (options.interactive) {
new Interactive().run()
} else {
this.normal()
}
}
/**
* Attempts to add and commit. Errors out in a non-ugly way.
*/
normal() {
try {
let args = process.argv.slice(2)
let fileGlob = args[0]
let commitMessage = args[1]
execSync(`git add -- *${fileGlob}*`)
execSync(`git commit -m "${commitMessage}"`)
} catch (e) {
console.log('Encountered error -- aborting.')
process.stdin.write('Reset added files...')
execSync('git reset .')
process.stdin.write('Done.')
console.log()
}
}
/**
* Shows the help screen.
*/
showHelpScreen() {
let helpFile = join(__dirname, './help.txt')
let helpScreen = execSync(`cat ${helpFile}`)
console.log(helpScreen.toString('utf8'))
}
}
module.exports = GitAddAndCommit
| const join = require('path').join
const execSync = require('child_process').execSync
const Interactive = require('./interactive')
/**
* Reads a file glob and a commit message, and commits to git.
* @class
*/
class GitAddAndCommit {
constructor(options) {
if (options.help) {
this.showHelpScreen()
} else if (options.interactive) {
new Interactive().run()
} else {
this.normal()
}
}
/**
* Attempts to add and commit. Errors out in a non-ugly way.
*/
normal() {
try {
let args = process.argv.slice(2)
let fileGlob = args[0]
let commitMessage = args[1]
execSync('git add -- *' + fileGlob + '*')
execSync('git commit -m "' + commitMessage + '"')
} catch (e) {
console.log('Encountered error -- aborting.')
process.stdin.write('Reset added files...')
execSync('git reset .')
process.stdin.write('Done.')
console.log()
}
}
/**
* Shows the help screen.
*/
showHelpScreen() {
let helpFile = join(__dirname, './help.txt')
let helpScreen = execSync('cat ' + helpFile)
console.log(helpScreen.toString('utf8'))
}
}
module.exports = GitAddAndCommit
|
Simulation: Terminate the virtual clock when launch terminated | /**
* Copyright (c) 2012 committers of YAKINDU and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
* Contributors:
* committers of YAKINDU - initial API and implementation
*
*/
package org.yakindu.sct.simulation.core.runtime.impl;
import org.yakindu.sct.simulation.core.runtime.IExecutionFacade;
import org.yakindu.sct.simulation.core.runtime.IExecutionFacadeController;
/**
* Abstract base implementation for {@link IExecutionFacadeController}s
*
* @author andreas muelder - Initial contribution and API
*
*/
public abstract class AbstractExecutionFacadeController implements
IExecutionFacadeController {
protected final IExecutionFacade facade;
protected boolean terminated = false;
protected boolean suspended = false;
public AbstractExecutionFacadeController(IExecutionFacade facade) {
this.facade = facade;
}
public void start() {
facade.enter();
}
public void suspend() {
suspended = true;
}
public void resume() {
suspended = false;
}
public void terminate() {
terminated = true;
facade.tearDown();
facade.getExecutionContext().getVirtualClock().stop();
}
}
| /**
* Copyright (c) 2012 committers of YAKINDU and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
* Contributors:
* committers of YAKINDU - initial API and implementation
*
*/
package org.yakindu.sct.simulation.core.runtime.impl;
import org.yakindu.sct.simulation.core.runtime.IExecutionFacade;
import org.yakindu.sct.simulation.core.runtime.IExecutionFacadeController;
/**
* Abstract base implementation for {@link IExecutionFacadeController}s
*
* @author andreas muelder - Initial contribution and API
*
*/
public abstract class AbstractExecutionFacadeController implements
IExecutionFacadeController {
protected final IExecutionFacade facade;
protected boolean terminated = false;
protected boolean suspended = false;
public AbstractExecutionFacadeController(IExecutionFacade facade) {
this.facade = facade;
}
public void start() {
facade.enter();
}
public void suspend() {
suspended = true;
}
public void resume() {
suspended = false;
}
public void terminate() {
terminated = true;
facade.tearDown();
}
}
|
Fix fail on Object.keys(app.me.installed) which was holding up
page loads.
- fixes #964 | import app from 'ampersand-app';
import Model from 'ampersand-model';
import querystring from 'querystring';
export default Model.extend({
urlRoot: '/api/experiments',
extraProperties: 'allow',
props: {
enabled: {type: 'boolean', default: false}
},
// This shouldn't be necessary; see comments in collections/experiments.js
ajaxConfig: { headers: { 'Accept': 'application/json' }},
// TODO(DJ): this will be removed when we start tracking
// install state through the User Installation model.
// https://github.com/mozilla/testpilot/issues/195
initialize() {
app.on('addon-install:install-ended', addon => {
if (addon.id === this.id) {
this.enabled = true;
}
});
app.on('addon-uninstall:uninstall-ended', addon => {
if (addon.id === this.id) {
this.enabled = false;
}
});
},
buildSurveyURL(ref) {
const queryParams = querystring.stringify({
ref: ref,
experiment: this.title,
installed: app.me.installed ? Object.keys(app.me.installed) : []
});
return `${this.survey_url}?${queryParams}`;
}
});
| import app from 'ampersand-app';
import Model from 'ampersand-model';
import querystring from 'querystring';
export default Model.extend({
urlRoot: '/api/experiments',
extraProperties: 'allow',
props: {
enabled: {type: 'boolean', default: false}
},
// This shouldn't be necessary; see comments in collections/experiments.js
ajaxConfig: { headers: { 'Accept': 'application/json' }},
// TODO(DJ): this will be removed when we start tracking
// install state through the User Installation model.
// https://github.com/mozilla/testpilot/issues/195
initialize() {
app.on('addon-install:install-ended', addon => {
if (addon.id === this.id) {
this.enabled = true;
}
});
app.on('addon-uninstall:uninstall-ended', addon => {
if (addon.id === this.id) {
this.enabled = false;
}
});
},
buildSurveyURL(ref) {
const installed = Object.keys(app.me.installed);
const queryParams = querystring.stringify({
ref: ref,
experiment: this.title,
installed: installed
});
return `${this.survey_url}?${queryParams}`;
}
});
|
Use copied instead of captured Msg and Cfg variables | package sirius
import (
"time"
)
type Execution struct {
Ext Extension
Msg Message
Cfg ExtensionConfig
}
type ExecutionResult struct {
Err error
Action MessageAction
}
type ExtensionRunner interface {
Run([]Execution, chan<- ExecutionResult, time.Duration)
}
type AsyncRunner struct{}
func NewExecution(x Extension, m Message, cfg ExtensionConfig) *Execution {
return &Execution{
Ext: x,
Msg: m,
Cfg: cfg,
}
}
func NewAsyncRunner() *AsyncRunner {
return &AsyncRunner{}
}
// Run executes all extensions in exe, and returns all ExecutionResults that
// are received before timeout has elapsed.
func (r *AsyncRunner) Run(exe []Execution, res chan<- ExecutionResult, timeout time.Duration) {
er := make(chan ExecutionResult, len(exe))
for _, e := range exe {
go func(ex Execution, r chan<- ExecutionResult) {
a, err := ex.Ext.Run(ex.Msg, ex.Cfg)
r <- ExecutionResult{
Err: err,
Action: a,
}
}(e, er)
}
Execution:
for range exe {
select {
case <-time.After(timeout):
break Execution
case res <- <-er:
}
}
close(res)
}
| package sirius
import (
"time"
)
type Execution struct {
Ext Extension
Msg Message
Cfg ExtensionConfig
}
type ExecutionResult struct {
Err error
Action MessageAction
}
type ExtensionRunner interface {
Run([]Execution, chan<- ExecutionResult, time.Duration)
}
type AsyncRunner struct{}
func NewExecution(x Extension, m Message, cfg ExtensionConfig) *Execution {
return &Execution{
Ext: x,
Msg: m,
Cfg: cfg,
}
}
func NewAsyncRunner() *AsyncRunner {
return &AsyncRunner{}
}
// Run executes all extensions in exe, and returns all ExecutionResults that
// are received before timeout has elapsed.
func (r *AsyncRunner) Run(exe []Execution, res chan<- ExecutionResult, timeout time.Duration) {
er := make(chan ExecutionResult, len(exe))
for _, e := range exe {
go func(ex Execution, r chan<- ExecutionResult) {
a, err := ex.Ext.Run(e.Msg, e.Cfg)
r <- ExecutionResult{
Err: err,
Action: a,
}
}(e, er)
}
Execution:
for range exe {
select {
case <-time.After(timeout):
break Execution
case res <- <-er:
}
}
close(res)
}
|
Add newline at the end of a file | package beaform.gui.search.tree;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
/**
* A listener that activates on double clicks.
*
* @author Steven Post
*
*/
public class DoubleClickListener extends MouseAdapter {
private final FormulaTree formulaTree;
/**
* @param formulaTree
*/
DoubleClickListener(FormulaTree formulaTree) {
this.formulaTree = formulaTree;
}
/** The number of clicks to register a double click on the mouse */
private static final int DOUBLE_CLICK = 2;
/**
* This method fires when the mouse is clicked,
* but only does something on double click events.
*
* @param event The event passed to this method when clicks are seen.
*/
@Override
public void mousePressed(final MouseEvent event) {
if(event.getClickCount() == DOUBLE_CLICK) {
this.formulaTree.editSelectedFormula();
}
}
}
| package beaform.gui.search.tree;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
/**
* A listener that activates on double clicks.
*
* @author Steven Post
*
*/
public class DoubleClickListener extends MouseAdapter {
private final FormulaTree formulaTree;
/**
* @param formulaTree
*/
DoubleClickListener(FormulaTree formulaTree) {
this.formulaTree = formulaTree;
}
/** The number of clicks to register a double click on the mouse */
private static final int DOUBLE_CLICK = 2;
/**
* This method fires when the mouse is clicked,
* but only does something on double click events.
*
* @param event The event passed to this method when clicks are seen.
*/
@Override
public void mousePressed(final MouseEvent event) {
if(event.getClickCount() == DOUBLE_CLICK) {
this.formulaTree.editSelectedFormula();
}
}
} |
Fix serving uploaded files during development. |
import os
from django.conf import settings
from django.contrib.staticfiles.management.commands import runserver
from django.contrib.staticfiles.handlers import StaticFilesHandler
from django.views.static import serve
class MezzStaticFilesHandler(StaticFilesHandler):
def get_response(self, request):
response = super(MezzStaticFilesHandler, self).get_response(request)
handled = (settings.STATIC_URL, settings.MEDIA_URL)
if response.status_code == 404 and request.path.startswith(handled):
path = self.file_path(request.path).replace(os.sep, "/")
return serve(request, path, document_root=settings.STATIC_ROOT)
class Command(runserver.Command):
"""
Overrides runserver so that we can serve uploaded files
during development, and not require every single developer on
every single one of their projects to have to set up multiple
web server aliases for serving static content.
See https://code.djangoproject.com/ticket/15199
For ease, we also serve any static files that have been stored
under the project's ``STATIC_ROOT``.
"""
def get_handler(self, *args, **options):
handler = super(Command, self).get_handler(*args, **options)
if settings.DEBUG or options["insecure_serving"]:
handler = MezzStaticFilesHandler(handler)
return handler
|
import os
from django.conf import settings
from django.contrib.staticfiles.management.commands import runserver
from django.contrib.staticfiles.handlers import StaticFilesHandler
from django.http import Http404
from django.views.static import serve
class MezzStaticFilesHandler(StaticFilesHandler):
def get_response(self, request):
try:
return super(MezzStaticFilesHandler, self).get_response(request)
except Http404:
handled = (settings.STATIC_URL, settings.MEDIA_URL)
if request.path.startswith(handled):
path = self.file_path(request.path).replace(os.sep, "/")
return serve(request, path, document_root=settings.STATIC_ROOT)
raise
class Command(runserver.Command):
"""
Overrides runserver so that we can serve uploaded files
during development, and not require every single developer on
every single one of their projects to have to set up multiple
web server aliases for serving static content.
See https://code.djangoproject.com/ticket/15199
For ease, we also serve any static files that have been stored
under the project's ``STATIC_ROOT``.
"""
def get_handler(self, *args, **options):
handler = super(Command, self).get_handler(*args, **options)
if settings.DEBUG or options["insecure_serving"]:
handler = MezzStaticFilesHandler(handler)
return handler
|
Fix double printing the help output | package cli
import "fmt"
import (
"sync"
"github.com/jessevdk/go-flags"
)
var (
globalParser *flags.Parser
globalParserSetup sync.Once
)
func parser() *flags.Parser {
globalParserSetup.Do(func() {
globalParser = flags.NewNamedParser("cypress", flags.Default|flags.PassAfterNonOption)
})
return globalParser
}
func addCommand(name, short, long string, cmd interface{}) {
_, err := parser().AddCommand(name, short, long, cmd)
if err != nil {
panic(err)
}
}
func Run(args []string) int {
defer Lifecycle.RunCleanup()
Lifecycle.Start()
_, err := parser().Parse()
if err != nil {
if ferr, ok := err.(*flags.Error); ok {
if ferr.Type == flags.ErrHelp {
return 1
}
}
fmt.Printf("Error: %s\n", err)
return 1
}
return 0
}
| package cli
import "fmt"
import (
"sync"
"github.com/jessevdk/go-flags"
)
var (
globalParser *flags.Parser
globalParserSetup sync.Once
)
func parser() *flags.Parser {
globalParserSetup.Do(func() {
globalParser = flags.NewNamedParser("cypress", flags.Default|flags.PassAfterNonOption)
})
return globalParser
}
func addCommand(name, short, long string, cmd interface{}) {
_, err := parser().AddCommand(name, short, long, cmd)
if err != nil {
panic(err)
}
}
func Run(args []string) int {
defer Lifecycle.RunCleanup()
Lifecycle.Start()
_, err := parser().Parse()
if err != nil {
fmt.Printf("Error: %s\n", err)
return 1
}
return 0
}
|
Remove unwanted leading newline in error message | /*
* Copyright (C) Red Gate Software Ltd 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.internal.exception;
import org.flywaydb.core.api.ErrorCode;
import org.flywaydb.core.api.FlywayException;
import org.flywaydb.core.internal.util.ExceptionUtils;
import org.flywaydb.core.internal.util.StringUtils;
import java.sql.SQLException;
/**
* The specific exception thrown when Flyway encounters a problem in SQL statement.
*/
public class FlywaySqlException extends FlywayException {
public FlywaySqlException(String message, SQLException sqlException) {
super(message, sqlException, ErrorCode.DB_CONNECTION);
}
@Override
public String getMessage() {
String title = super.getMessage();
String underline = StringUtils.trimOrPad("", title.length(), '-');
return title + "\n" + underline + "\n" + ExceptionUtils.toMessage((SQLException) getCause());
}
} | /*
* Copyright (C) Red Gate Software Ltd 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.internal.exception;
import org.flywaydb.core.api.ErrorCode;
import org.flywaydb.core.api.FlywayException;
import org.flywaydb.core.internal.util.ExceptionUtils;
import org.flywaydb.core.internal.util.StringUtils;
import java.sql.SQLException;
/**
* The specific exception thrown when Flyway encounters a problem in SQL statement.
*/
public class FlywaySqlException extends FlywayException {
public FlywaySqlException(String message, SQLException sqlException) {
super(message, sqlException, ErrorCode.DB_CONNECTION);
}
@Override
public String getMessage() {
String title = super.getMessage();
String underline = StringUtils.trimOrPad("", title.length(), '-');
return "\n" + title + "\n" + underline + "\n" + ExceptionUtils.toMessage((SQLException) getCause());
}
} |
Use API instead of direct calls in GUI event handler
Sorry for no GPG signature, but Git doesn't want to run GPG nor any
other software. Reason: unknown
Signed-off-by: TheSilkMiner <7e811527e53179cd216d0ac71740b4760bead5b2@outlook.com> | package openmods.igw.impl.client;
import com.google.common.base.Preconditions;
import net.minecraft.client.gui.GuiMainMenu;
import net.minecraftforge.client.event.GuiOpenEvent;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import openmods.igw.api.OpenModsIGWApi;
import openmods.igw.api.service.IClassProviderService;
import openmods.igw.api.service.IGuiService;
@SideOnly(Side.CLIENT)
public class GuiOpenEventHandler {
@SubscribeEvent
@SideOnly(Side.CLIENT)
@SuppressWarnings("unused")
//@Explain("Called by Forge, not by us")
public void onMainMenuOpen(final GuiOpenEvent event) {
if (!(event.gui instanceof GuiMainMenu)) return;
final IGuiService it = Preconditions.checkNotNull(OpenModsIGWApi.get().serviceManager()
.obtainAndCastService(IGuiService.class));
if (it.shouldShow(IGuiService.GUIs.WARNING)) {
event.gui = it.construct(IGuiService.GUIs.WARNING);
return;
}
if (it.shouldShow(IGuiService.GUIs.MISMATCHING_MODS)) {
event.gui = it.construct(IGuiService.GUIs.MISMATCHING_MODS, Preconditions.checkNotNull(
Preconditions.checkNotNull(
OpenModsIGWApi.get().serviceManager().obtainAndCastService(IClassProviderService.class)
).proxy()
).getMismatchingMods());
}
}
}
| package openmods.igw.impl.client;
import net.minecraft.client.gui.GuiMainMenu;
import net.minecraftforge.client.event.GuiOpenEvent;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import openmods.igw.OpenModsIGW;
@SideOnly(Side.CLIENT)
public class GuiOpenEventHandler {
@SubscribeEvent
@SideOnly(Side.CLIENT)
@SuppressWarnings("unused")
//@Explain("Called by Forge, not by us")
// TODO Move to API
public void onMainMenuOpen(final GuiOpenEvent event) {
if (!(event.gui instanceof GuiMainMenu)) return;
if (WarningGui.shallShow()) {
event.gui = new WarningGui();
return;
}
if (MismatchingVersionsGui.shouldShow()) {
event.gui = new MismatchingVersionsGui(OpenModsIGW.proxy().getMismatchingMods());
}
}
}
|
Make a comment render more nicely | import restArguments from './restArguments.js';
import now from './now.js';
// When a sequence of calls of the returned function ends, the argument
// function is triggered. The end of a sequence is defined by the `wait`
// parameter. If `immediate` is passed, the argument function will be
// triggered at the beginning of the sequence instead of at the end.
export default function debounce(func, wait, immediate) {
var timeout, previous, args, result, context;
var later = function() {
var passed = now() - previous;
if (wait > passed) {
timeout = setTimeout(later, wait - passed);
} else {
timeout = null;
if (!immediate) result = func.apply(context, args);
// This check is needed because `func` can recursively invoke `debounced`.
if (!timeout) args = context = null;
}
};
var debounced = restArguments(function(_args) {
context = this;
args = _args;
previous = now();
if (!timeout) {
timeout = setTimeout(later, wait);
if (immediate) result = func.apply(context, args);
}
return result;
});
debounced.cancel = function() {
clearTimeout(timeout);
timeout = args = context = null;
};
return debounced;
}
| import restArguments from './restArguments.js';
import now from './now.js';
// When a sequence of calls of the returned function ends, the argument
// function is triggered. The end of a sequence is defined by the `wait`
// parameter. If `immediate` is passed, the argument function will be
// triggered at the beginning of the sequence instead of at the end.
export default function debounce(func, wait, immediate) {
var timeout, previous, args, result, context;
var later = function() {
var passed = now() - previous;
if (wait > passed) {
timeout = setTimeout(later, wait - passed);
} else {
timeout = null;
if (!immediate) result = func.apply(context, args);
// This check is needed because the func can recursively invoke debounced
if (!timeout) args = context = null;
}
};
var debounced = restArguments(function(_args) {
context = this;
args = _args;
previous = now();
if (!timeout) {
timeout = setTimeout(later, wait);
if (immediate) result = func.apply(context, args);
}
return result;
});
debounced.cancel = function() {
clearTimeout(timeout);
timeout = args = context = null;
};
return debounced;
}
|
Disable pointer-events of outline items | // @flow
import styled, { css } from 'styled-components'
import * as vars from 'settings/styles'
import * as colors from 'settings/colors'
type Props = {
depth: '1' | '2' | '3' | '4' | '5' | '6',
}
const fn = ({ depth: depthStr }: Props) => {
const depth = parseInt(depthStr)
return css`
padding-left: ${(2 + (depth > 1 ? depth - 2 : 0)) * vars.spacing}px;
&:before {
content: '${'#'.repeat(depth)}';
}
`
}
const Link = styled.a`
display: block;
height: 100%;
padding-right: ${2 * vars.spacing}px;
border-bottom: 1px solid ${colors.blackForeground200};
text-decoration: none;
font-size: 0.9rem;
color: white;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
pointer-events: none;
${fn}
&:before {
color: ${colors.whiteForeground300};
padding-right: ${vars.spacing}px;
font-size: 0.8rem;
}
&:hover {
background-color: ${colors.blackForeground200};
}
`
export default Link
| // @flow
import styled, { css } from 'styled-components'
import * as vars from 'settings/styles'
import * as colors from 'settings/colors'
type Props = {
depth: '1' | '2' | '3' | '4' | '5' | '6',
}
const fn = ({ depth: depthStr }: Props) => {
const depth = parseInt(depthStr)
return css`
padding-left: ${(2 + (depth > 1 ? depth - 2 : 0)) * vars.spacing}px;
&:before {
content: '${'#'.repeat(depth)}';
}
`
}
const Link = styled.a`
display: block;
height: 100%;
padding-right: ${2 * vars.spacing}px;
border-bottom: 1px solid ${colors.blackForeground200};
text-decoration: none;
font-size: 0.9rem;
color: white;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
${fn}
&:before {
color: ${colors.whiteForeground300};
padding-right: ${vars.spacing}px;
font-size: 0.8rem;
}
&:hover {
background-color: ${colors.blackForeground200};
}
`
export default Link
|
Use short phpdoc @param typename | <?php
/**
* This file has been made by pH7 (Pierre-Henry SORIA).
*/
namespace PFBC\Validation;
use PH7\Framework\Layout\Form\Form as FormMessage;
use PH7\Framework\Security\CSRF\Token as SecurityToken;
class Token extends \PFBC\Validation
{
/** @var string */
private $sName;
/**
* @param string $sName
*/
public function __construct($sName)
{
$this->message = FormMessage::errorTokenMsg();
$this->sName = $sName;
}
/**
* @return bool Returns TRUE if the token is validated, FALSE otherwise.
*/
public function isValid($sValue)
{
return (new SecurityToken)->check($this->sName, $sValue);
}
}
| <?php
/**
* This file has been made by pH7 (Pierre-Henry SORIA).
*/
namespace PFBC\Validation;
use PH7\Framework\Layout\Form\Form as FormMessage;
use PH7\Framework\Security\CSRF\Token as SecurityToken;
class Token extends \PFBC\Validation
{
/** @var string */
private $sName;
/**
* @param string $sName
*/
public function __construct($sName)
{
$this->message = FormMessage::errorTokenMsg();
$this->sName = $sName;
}
/**
* @return boolean Returns TRUE if the token is validated, FALSE otherwise.
*/
public function isValid($sValue)
{
return (new SecurityToken)->check($this->sName, $sValue);
}
}
|
Adjust network_settings config format for salt 2018.3.0.
Before this release the format did not use the 'interfaces' key. | # -*- coding: utf-8 -*-
'''
Beacon to monitor default network adapter setting changes on Linux
'''
from salt.beacons import network_settings
import logging
log = logging.getLogger(__name__)
__virtual_name__ = 'default_network_interface_settings'
def __virtual__():
if network_settings.__virtual__():
return __virtual_name__
return False
def __validate__(config):
return network_settings.__validate__(config)
def beacon(config):
'''
Watch for changes on network settings on the gateway interface.
By default, the beacon will emit when there is a value change on one of the
settings on watch. The config also support the onvalue parameter for each
setting, which instruct the beacon to only emit if the setting changed to the
value defined.
Example Config
.. code-block:: yaml
beacons:
default_network_interface_settings:
interval: 5
watch:
ipaddr:
promiscuity:
onvalue: 1
'''
default_interface = __salt__['network.default_route']()[0]['interface']
config = {default_interface: config['watch']}
if __salt__['test.version']() >= '2018.3.0':
config = [{'interfaces': config}]
log.debug("Newer salt version - adjusted config format: {0}".format(config))
return network_settings.beacon(config)
| # -*- coding: utf-8 -*-
'''
Beacon to monitor default network adapter setting changes on Linux
'''
from salt.beacons import network_settings
import logging
log = logging.getLogger(__name__)
__virtual_name__ = 'default_network_interface_settings'
def __virtual__():
if network_settings.__virtual__():
return __virtual_name__
return False
def __validate__(config):
return network_settings.__validate__(config)
def beacon(config):
'''
Watch for changes on network settings on the gateway interface.
By default, the beacon will emit when there is a value change on one of the
settings on watch. The config also support the onvalue parameter for each
setting, which instruct the beacon to only emit if the setting changed to the
value defined.
Example Config
.. code-block:: yaml
beacons:
default_network_interface_settings:
interval: 5
watch:
ipaddr:
promiscuity:
onvalue: 1
'''
default_interface = __salt__['network.default_route']()[0]['interface']
return network_settings.beacon({default_interface: config['watch']})
|
feat(docscanner): Support passing context to callback
It might be useful to send some additional parameters to the callback
function. For example, you might want to write to a file in the
callback. This commit allows the user to pass an optional context to
the callback everytime it finds a match. | import re
class DocScanner(object):
"""
A class used to find certain tokens in a given document. The tokens can be
specified by regular expressions.
"""
def __init__(self, tokens_dict, callback):
"""
Initialize a new document scanner.
:param tokens_dict: A dictionary whose keys are the types of tokens and
values are the regex for finding such types of tokens.
:param callback: A function to be called whenever a token is found.
"""
self.types = list(tokens_dict.keys())
self.scanning_regex = '|'.join(['(?P<%s>%s)' % (type, regex) for type, regex in tokens_dict.items()])
self.callback = callback
def scan(self, document, context=None):
prev_match = None
prev_type = None
for match in re.finditer(self.scanning_regex, document, flags=re.MULTILINE):
for type in self.types:
if match.group(type) is not None:
self.callback(
type,
prev_type,
match,
prev_match,
document,
context
)
prev_type = type
prev_match = match
break
| import re
class DocScanner(object):
"""
A class used to find certain tokens in a given document. The tokens can be
specified by regular expressions.
"""
def __init__(self, tokens_dict, callback):
"""
Initialize a new document scanner.
:param tokens_dict: A dictionary whose keys are the types of tokens and
values are the regex for finding such types of tokens.
:param callback: A function to be called whenever a token is found.
"""
self.types = list(tokens_dict.keys())
self.scanning_regex = '|'.join(['(?P<%s>%s)' % (type, regex) for type, regex in tokens_dict.items()])
self.callback = callback
def scan(self, document):
prev_match = None
prev_type = None
for curr_match in re.finditer(self.scanning_regex, document, flags=re.MULTILINE):
for type in self.types:
if curr_match.group(type) is not None:
self.callback(
type,
prev_type,
curr_match,
prev_match,
document
)
break
|
Change id from Integer to Long | package nl.wjl.template.springbootjpa.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
/**
* Created by Wouter on 18-2-2016.
*/
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
| package nl.wjl.template.springbootjpa.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
/**
* Created by Wouter on 18-2-2016.
*/
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String firstName;
private String lastName;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
|
Replace refs to 'Keystone API' with 'Identity API'
Formally, OpenStack Keystone implements the OpenStack Identity API, and
this is a client to the API, not to Keystone itself.
Change-Id: If568866221a29ba041f0f2cd56dc81deeb9ebc00 | import os
import sys
import setuptools
from keystoneclient.openstack.common import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
requires = setup.parse_requirements()
depend_links = setup.parse_dependency_links()
tests_require = setup.parse_requirements(['tools/test-requires'])
setuptools.setup(
name="python-keystoneclient",
version=setup.get_post_version('keystoneclient'),
description="Client library for OpenStack Identity API (Keystone)",
long_description=read('README.rst'),
url='https://github.com/openstack/python-keystoneclient',
license='Apache',
author='Nebula Inc, based on work by Rackspace and Jacob Kaplan-Moss',
author_email='gabriel.hurley@nebula.com',
packages=setuptools.find_packages(exclude=['tests', 'tests.*']),
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: Information Technology',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
install_requires=requires,
dependency_links=depend_links,
cmdclass=setup.get_cmdclass(),
tests_require=tests_require,
test_suite="nose.collector",
entry_points={
'console_scripts': ['keystone = keystoneclient.shell:main']
}
)
| import os
import sys
import setuptools
from keystoneclient.openstack.common import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
requires = setup.parse_requirements()
depend_links = setup.parse_dependency_links()
tests_require = setup.parse_requirements(['tools/test-requires'])
setuptools.setup(
name="python-keystoneclient",
version=setup.get_post_version('keystoneclient'),
description="Client library for OpenStack Keystone API",
long_description=read('README.rst'),
url='https://github.com/openstack/python-keystoneclient',
license='Apache',
author='Nebula Inc, based on work by Rackspace and Jacob Kaplan-Moss',
author_email='gabriel.hurley@nebula.com',
packages=setuptools.find_packages(exclude=['tests', 'tests.*']),
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: Information Technology',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
install_requires=requires,
dependency_links=depend_links,
cmdclass=setup.get_cmdclass(),
tests_require=tests_require,
test_suite="nose.collector",
entry_points={
'console_scripts': ['keystone = keystoneclient.shell:main']
}
)
|
Add test for filter removal | // / <reference types="Cypress" />
describe('The Locations Hub', () => {
before(() => {
cy.visit('/#/locations');
});
it('successfully loads', () => {
cy.get('header');
cy.get('main');
cy.get('footer');
cy.get('h1');
});
it('has a header with title and description', () => {
cy.get('h1').should('contain', 'Locations');
cy.get('.inpage__introduction').should(
'contain',
'Lorem ipsum dolor sit amet'
);
});
it('has a results section with a list of location cards', () => {
cy.get('.results-summary')
.invoke('text')
.should('match', /A total of \d+ locations were found/);
cy.get('.card').should('have.length', 15);
cy.get('.pagination').should('exist');
});
it('has some filters with dropdown menus', () => {
cy.get('.filters').should('exist');
cy.get('[title="type__filter"]').click();
cy.get('.drop__menu-item').first().click();
cy.get('.button--filter-pill').should('exist');
cy.get('button').contains('Clear Filters').should('exist');
cy.get('.button--filter-pill').click();
cy.get('.button--filter-pill').should('not.exist');
});
});
| // / <reference types="Cypress" />
describe('The Locations Hub', () => {
before(() => {
cy.visit('/#/locations');
});
it('successfully loads', () => {
cy.get('header');
cy.get('main');
cy.get('footer');
cy.get('h1');
});
it('has a header with title and description', () => {
cy.get('h1').should('contain', 'Locations');
cy.get('.inpage__introduction').should(
'contain',
'Lorem ipsum dolor sit amet'
);
});
it('has a results section with a list of location cards', () => {
cy.get('.results-summary')
.invoke('text')
.should('match', /A total of \d+ locations were found/);
cy.get('.card').should('have.length', 15);
cy.get('.pagination').should('exist');
});
it('has some filters with dropdown menus', () => {
cy.get('.filters').should('exist');
cy.get('[title="type__filter"]').click();
cy.get('.drop__menu-item').first().click();
cy.get('.button--filter-pill').should('exist');
cy.get('button').contains('Clear Filters').should('exist');
});
});
|
[WIP] Improve test coverage for PulsarFormComponent | 'use strict';
var $ = require('jquery'),
PulsarFormComponent = require('../../js/PulsarFormComponent');
describe('Pulsar Form Component', function() {
beforeEach(function() {
this.$html = $('<html></html>');
this.$body = $('<body></body>').appendTo(this.$html);
this.$markup = $('\
<form class="form">\
<select class="js-select2">\
<option>foo</option>\
<option>bar</option>\
<option>baz</option>\
</select>\
<select class="js-select2" data-html="true">\
<option>foo</option>\
<option>bar</option>\
<option>baz</option>\
</select>\
</form>\
').appendTo(this.$html);
this.pulsarForm = new PulsarFormComponent(this.$html);
});
describe('Basic select2 elements', function() {
beforeEach(function() {
sinon.spy($.fn, 'select2');
this.pulsarForm.init();
});
it('should call the select2 plugin', function() {
expect($.fn.select2).to.have.been.called;
});
});
describe('Select2 elements with HTML', function() {
beforeEach(function() {
this.pulsarForm.init();
});
it('should call the select2 plugin', function() {
expect($.fn.select2).to.have.been.called;
});
});
});
| 'use strict';
var $ = require('jquery'),
PulsarFormComponent = require('../../js/PulsarFormComponent');
describe('Pulsar Form Component', function() {
beforeEach(function() {
this.$html = $('<html></html>');
this.$body = $('<body></body>').appendTo(this.$html);
this.$markup = $('\
<form class="form">\
<select class="js-select2" data-html="true">\
<option>foo</option>\
<option>bar</option>\
<option>baz</option>\
</select>\
</form>\
').appendTo(this.$html);
this.pulsarForm = new PulsarFormComponent(this.$html);
});
describe('Select2 elements within a form', function() {
beforeEach(function() {
sinon.spy($.fn, 'select2');
this.pulsarForm.init();
});
it('should call the select2 plugin', function() {
expect($.fn.select2).to.have.been.called;
});
});
});
|
Fix NATSRequester to connect to right URL | package bench
import (
"time"
"github.com/nats-io/nats"
)
// NATSRequester implements Requester by publishing a message to NATS and
// waiting to receive it.
type NATSRequester struct {
URL string
PayloadSize int
Subject string
conn *nats.Conn
sub *nats.Subscription
msg []byte
}
// Setup prepares the Requester for benchmarking.
func (n *NATSRequester) Setup() error {
conn, err := nats.Connect(n.URL)
if err != nil {
return err
}
sub, err := conn.SubscribeSync(n.Subject)
if err != nil {
return err
}
n.conn = conn
n.sub = sub
n.msg = make([]byte, n.PayloadSize)
return nil
}
// Request performs a synchronous request to the system under test.
func (n *NATSRequester) Request() error {
if err := n.conn.Publish(n.Subject, n.msg); err != nil {
return err
}
_, err := n.sub.NextMsg(30 * time.Second)
return err
}
// Teardown is called upon benchmark completion.
func (n *NATSRequester) Teardown() error {
err := n.sub.Unsubscribe()
if err != nil {
return err
}
n.sub = nil
n.conn.Close()
n.conn = nil
return nil
}
| package bench
import (
"time"
"github.com/nats-io/nats"
)
// NATSRequester implements Requester by publishing a message to NATS and
// waiting to receive it.
type NATSRequester struct {
URL string
PayloadSize int
Subject string
conn *nats.Conn
sub *nats.Subscription
msg []byte
}
// Setup prepares the Requester for benchmarking.
func (n *NATSRequester) Setup() error {
conn, err := nats.Connect(nats.DefaultURL)
if err != nil {
return err
}
sub, err := conn.SubscribeSync(n.Subject)
if err != nil {
return err
}
n.conn = conn
n.sub = sub
n.msg = make([]byte, n.PayloadSize)
return nil
}
// Request performs a synchronous request to the system under test.
func (n *NATSRequester) Request() error {
if err := n.conn.Publish(n.Subject, n.msg); err != nil {
return err
}
_, err := n.sub.NextMsg(30 * time.Second)
return err
}
// Teardown is called upon benchmark completion.
func (n *NATSRequester) Teardown() error {
err := n.sub.Unsubscribe()
if err != nil {
return err
}
n.sub = nil
n.conn.Close()
n.conn = nil
return nil
}
|
Swap ids for classes in completion rate template
We have more than one module in a page so ids are bad. | define([
'extensions/views/view',
'common/views/visualisations/volumetrics/number',
'common/views/visualisations/volumetrics/completion-graph'
],
function (View, VolumetricsNumberView, CompletionGraphView) {
return View.extend({
valueAttr: 'completion',
totalAttr: 'totalCompletion',
views: function () {
return {
'.volumetrics-completion-selected': {
view: VolumetricsNumberView,
options: {
valueAttr: this.totalAttr,
selectionValueAttr: this.valueAttr,
formatValue: function (value) {
return this.format(value, 'percent');
}
}
},
'.volumetrics-completion': {
view: CompletionGraphView,
options: {
valueAttr: this.valueAttr
}
}
};
}
});
});
| define([
'extensions/views/view',
'common/views/visualisations/volumetrics/number',
'common/views/visualisations/volumetrics/completion-graph'
],
function (View, VolumetricsNumberView, CompletionGraphView) {
var CompletionRateView = View.extend({
valueAttr: 'completion',
totalAttr: 'totalCompletion',
views: function () {
return {
'#volumetrics-completion-selected': {
view: VolumetricsNumberView,
options: {
valueAttr: this.totalAttr,
selectionValueAttr: this.valueAttr,
formatValue: function (value) {
return this.format(value, 'percent');
}
}
},
'#volumetrics-completion': {
view: CompletionGraphView,
options: {
valueAttr: this.valueAttr
}
}
};
}
});
return CompletionRateView;
});
|
Use with statement to ensure file is closed afterwards | import os
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as file_handle:
README = file_handle.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-speedbar',
version='0.1',
packages = find_packages(),
include_package_data=True,
license='MIT License',
description='Provides a break down of page loading time',
long_description=README,
url='http://github.com/theospears/django-speedbar',
author='Theo Spears',
author_email='theo@mixcloud.com',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
install_requires = [
'ProxyTypes>=0.9',
'Django >=1.5, <1.6a0',
],
)
| import os
from setuptools import setup, find_packages
README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-speedbar',
version='0.1',
packages = find_packages(),
include_package_data=True,
license='MIT License',
description='Provides a break down of page loading time',
long_description=README,
url='http://github.com/theospears/django-speedbar',
author='Theo Spears',
author_email='theo@mixcloud.com',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
install_requires = [
'ProxyTypes>=0.9',
'Django >=1.5, <1.6a0',
],
)
|
Return a boolean instead of void
Signed-off-by: Rick Kerkhof <77953cd64cc4736aae27fa116356e02d2d97f7ce@gmail.com> | <?php
/**
* Copyright 2018 The WildPHP Team
*
* You should have received a copy of the MIT license with the project.
* See the LICENSE file for more information.
*/
namespace WildPHP\Core\Connection;
use WildPHP\Messages\Interfaces\OutgoingMessageInterface;
interface QueueInterface
{
/**
* @param OutgoingMessageInterface $command
*
* @return void
*/
public function insertMessage(OutgoingMessageInterface $command);
/**
* @param QueueItem $item
*
* @return bool
*/
public function removeMessage(QueueItem $item);
/**
* @param int $index
*
* @return void
*/
public function removeMessageByIndex(int $index);
/**
* @param QueueItem $item
*
* @return void
*/
public function scheduleItem(QueueItem $item);
/**
* @return QueueItem[]
*/
public function flush(): array;
} | <?php
/**
* Copyright 2018 The WildPHP Team
*
* You should have received a copy of the MIT license with the project.
* See the LICENSE file for more information.
*/
namespace WildPHP\Core\Connection;
use WildPHP\Messages\Interfaces\OutgoingMessageInterface;
interface QueueInterface
{
/**
* @param OutgoingMessageInterface $command
*
* @return void
*/
public function insertMessage(OutgoingMessageInterface $command);
/**
* @param QueueItem $item
*
* @return void
*/
public function removeMessage(QueueItem $item);
/**
* @param int $index
*
* @return void
*/
public function removeMessageByIndex(int $index);
/**
* @param QueueItem $item
*
* @return void
*/
public function scheduleItem(QueueItem $item);
/**
* @return QueueItem[]
*/
public function flush(): array;
} |
Use custom exception handling for test JANUS client | <?php
if (PHP_SAPI !== 'cli') {
die('Command line access only' . PHP_EOL);
}
if (!isset($argv[1])) {
die("Please supply a method to call, like so: php janus_client.php getMetadata https://example.edu" . PHP_EOL);
}
try {
require './../library/EngineBlock/ApplicationSingleton.php';
$application = EngineBlock_ApplicationSingleton::getInstance();
$application->bootstrap();
$config = EngineBlock_ApplicationSingleton::getInstance()->getConfiguration()->serviceRegistry;
$restClient = new Janus_Rest_Client($config->location, $config->user, $config->user_secret);
$client = new Janus_Client();
$client->setRestClient($restClient);
$methodName = $argv[1];
$arguments = array_slice($argv, 2);
$result = call_user_func_array(array($client, $methodName), $arguments);
var_dump($restClient->getHttpClient()->getLastRequest());
var_dump($restClient->getHttpClient()->getLastResponse()->getHeadersAsString());
var_dump($restClient->getHttpClient()->getLastResponse()->getBody());
var_dump($result);
} catch(Exception $e) {
var_dump($e);
}
| <?php
if (PHP_SAPI !== 'cli') {
die('Command line access only' . PHP_EOL);
}
if (!isset($argv[1])) {
die("Please supply a method to call, like so: php janus_client.php getMetadata https://example.edu" . PHP_EOL);
}
require './../library/EngineBlock/ApplicationSingleton.php';
$application = EngineBlock_ApplicationSingleton::getInstance();
$application->bootstrap();
$config = EngineBlock_ApplicationSingleton::getInstance()->getConfiguration()->serviceRegistry;
$restClient = new Janus_Rest_Client($config->location, $config->user, $config->user_secret);
$client = new Janus_Client();
$client->setRestClient($restClient);
$methodName = $argv[1];
$arguments = array_slice($argv, 2);
$result = call_user_func_array(array($client, $methodName), $arguments);
var_dump($restClient->getHttpClient()->getLastRequest());
var_dump($restClient->getHttpClient()->getLastResponse()->getHeadersAsString());
var_dump($restClient->getHttpClient()->getLastResponse()->getBody());
var_dump($result);
|
Make the RSS feed not slow. | from django.contrib.syndication.views import Feed
from django.db.models import Max
from projects.models import Project
class LatestProjectsFeed(Feed):
title = "Recently updated documentation"
link = "http://readthedocs.org"
description = "Recently updated documentation on Read the Docs"
def items(self):
return Project.objects.order_by('-modified_date')[:10]
def item_title(self, item):
return item.name
def item_description(self, item):
return item.get_latest_build()
class NewProjectsFeed(Feed):
title = "Newest documentation"
link = "http://readthedocs.org"
description = "Recently created documentation on Read the Docs"
def items(self):
return Project.objects.all().order_by('-pk')[:10]
def item_title(self, item):
return item.name
def item_description(self, item):
return item.get_latest_build()
| from django.contrib.syndication.views import Feed
from django.db.models import Max
from projects.models import Project
class LatestProjectsFeed(Feed):
title = "Recently updated documentation"
link = "http://readthedocs.org"
description = "Recently updated documentation on Read the Docs"
def items(self):
return Project.objects.filter(builds__isnull=False).annotate(max_date=Max('builds__date')).order_by('-max_date')[:10]
def item_title(self, item):
return item.name
def item_description(self, item):
return item.get_latest_build()
class NewProjectsFeed(Feed):
title = "Newest documentation"
link = "http://readthedocs.org"
description = "Recently created documentation on Read the Docs"
def items(self):
return Project.objects.all().order_by('-pk')[:10]
def item_title(self, item):
return item.name
def item_description(self, item):
return item.get_latest_build()
|
Allow soft deletion of users | <?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* Should deleted_at be used
*
* @var bool
*/
protected $softDeletes = true;
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = array('pass');
/**
* Get the unique identifier for the user.
*
* @return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* @return string
*/
public function getAuthPassword()
{
return $this->pass;
}
/**
* Get the e-mail address where password reminders are sent.
*
* @return string
*/
public function getReminderEmail()
{
return $this->email;
}
}
| <?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = array('pass');
/**
* Get the unique identifier for the user.
*
* @return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* @return string
*/
public function getAuthPassword()
{
return $this->pass;
}
/**
* Get the e-mail address where password reminders are sent.
*
* @return string
*/
public function getReminderEmail()
{
return $this->email;
}
}
|
Make JS function for preventing body scroll with id more secure
Check if we are dealing with a modal by checking if the first
element in selected element has a class `modal-content`. | (function () {
'use strict';
// Hide overlay when ESC is pressed
document.addEventListener('keyup', function (event) {
var hash = window.location.hash.replace('#', '');
// If hash is not set
if (hash === '' || hash === '!') {
return;
}
// If key ESC is pressed
if (event.keyCode === 27) {
window.location.hash = '!';
}
}, false);
// When showing overlay, prevent background from scrolling
window.addEventListener('hashchange', function () {
var hash = window.location.hash.replace('#', ''),
modalChild;
// If hash is set
if (hash !== '' && hash !== '!') {
// Get first element in selected element
modalChild = document.getElementById(hash).firstElementChild;
// When we deal with a modal and class `has-overlay` is not set on body yet
if (modalChild.className.match(/modal-inner/) && !document.body.className.match(/has-overlay/)) {
document.body.className += ' has-overlay';
}
} else {
document.body.className = document.body.className.replace(' has-overlay', '');
}
}, false);
}());
| (function () {
'use strict';
// Hide overlay when ESC is pressed
document.addEventListener('keyup', function (event) {
var hash = window.location.hash.replace('#', '');
// If hash is not set
if (hash === '' || hash === '!') {
return;
}
// If key ESC is pressed
if (event.keyCode === 27) {
window.location.hash = '!';
}
}, false);
// When showing overlay, prevent background from scrolling
window.addEventListener('hashchange', function () {
var hash = window.location.hash.replace('#', '');
// If hash is set
if (hash !== '' && hash !== '!') {
// And has-overlay is not set yet
if (!document.body.className.match(/has-overlay/)) {
document.body.className += ' has-overlay';
}
} else {
document.body.className = document.body.className.replace(' has-overlay', '');
}
}, false);
}());
|
Fix missed reference to with-action | import React from 'react'
import { displayName } from '../src/addons/with-send'
it('gets a stateless component name', function () {
const name = displayName(function Button () {})
expect(name).toBe('Button')
})
it('gets a class component name', function () {
const name = displayName(class Button extends React.PureComponent {})
expect(name).toBe('Button')
})
it('gets a createClass component name', function () {
const Button = React.createClass({
render () {
var { send } = this.props
return (
<button type="button" onClick={() => send('action')}>Click me</button>
)
}
})
const name = displayName(Button)
expect(name).toBe('Button')
})
it('uses "Component" when there is no name', function () {
// eslint-disable-next-line react/display-name
expect(displayName(React.createClass({
render () { return <p>Hi</p> }
}))).toBe('Component')
})
| import React from 'react'
import { displayName } from '../src/addons/with-action'
it('gets a stateless component name', function () {
const name = displayName(function Button () {})
expect(name).toBe('Button')
})
it('gets a class component name', function () {
const name = displayName(class Button extends React.PureComponent {})
expect(name).toBe('Button')
})
it('gets a createClass component name', function () {
const Button = React.createClass({
render () {
var { send } = this.props
return (
<button type="button" onClick={() => send('action')}>Click me</button>
)
}
})
const name = displayName(Button)
expect(name).toBe('Button')
})
it('uses "Component" when there is no name', function () {
// eslint-disable-next-line react/display-name
expect(displayName(React.createClass({
render () { return <p>Hi</p> }
}))).toBe('Component')
})
|
Make sure tests run on 'setup.py test'
Nose was parsing the argv passed to setup.py (oh, global variables).
Assume that if 'distutils' are loaded then this is the case; and pass
through argv if it isn't. Also, update the suggested commands for the
extra requirements. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This is a convenience nose wrapper, for use with 'coverage' and
'setup.py test'; run it using:
$ ./run_tests.py
You can also pass 'nose' arguments to this script, for instance to run
individual tests or to skip redirection of output so 'pdb.set_trace()'
works:
$ ./run_tests.py -s -v normalize.test_foo
"""
import os
import sys
try:
import nose
except ImportError:
recommend = (
"pip install nose unittest2 -r requirements.txt" if
"VIRTUAL_ENV" in os.environ else
"sudo easy_install nose unittest2 richenum"
)
sys.stderr.write(
"Running the tests requires Nose. Try:\n\n{cmd}\n\nAborting.\n"
.format(cmd=recommend)
)
sys.exit(1)
args = [] if "distutils" in sys.modules else sys.argv[1:]
nose.main(argv=['nosetests'] + args)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This is a convenience nose wrapper, for use with 'coverage' and
'setup.py test'; run it using:
$ ./run_tests.py
You can also pass 'nose' arguments to this script, for instance to run
individual tests or to skip redirection of output so 'pdb.set_trace()'
works:
$ ./run_tests.py -s -v normalize.test_foo
"""
import os
import sys
try:
import nose
except ImportError:
recommend = (
"pip install nose" if "VIRTUAL_ENV" in os.environ else
"sudo easy_install nose"
)
sys.stderr.write(
"Running the tests requires Nose. Try:\n\n{cmd}\n\nAborting.\n"
.format(cmd=recommend)
)
sys.exit(1)
nose.main()
|
Cut a new version to update the README on PyPi. | """A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='class_namespaces',
version='0.3.6',
description='Class Namespaces',
long_description=long_description,
url='https://github.com/mwchase/class-namespaces',
author='Max Woerner Chase',
author_email='max.chase@gmail.com',
license='MIT',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
keywords='class namespaces',
packages=find_packages(exclude=['contrib', 'docs', 'tests']),
extras_require={
'test': ['coverage', 'pytest'],
},
)
| """A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='class_namespaces',
version='0.3.5',
description='Class Namespaces',
long_description=long_description,
url='https://github.com/mwchase/class-namespaces',
author='Max Woerner Chase',
author_email='max.chase@gmail.com',
license='MIT',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
keywords='class namespaces',
packages=find_packages(exclude=['contrib', 'docs', 'tests']),
extras_require={
'test': ['coverage', 'pytest'],
},
)
|
Handle when App.rootElement can be a node, rather than an id | /*globals document */
let hasDOM = typeof document !== 'undefined';
function appendContainerElement(rootElementOrId, id) {
if (!hasDOM) {
return;
}
if (document.getElementById(id)) {
return;
}
let rootEl = rootElementOrId.appendChild ? rootElementOrId : document.querySelector(rootElementOrId);
let modalContainerEl = document.createElement('div');
modalContainerEl.id = id;
rootEl.appendChild(modalContainerEl);
}
export default function(App) {
let emberModalDialog = App.emberModalDialog || {};
let modalContainerElId = emberModalDialog.modalRootElementId || 'modal-overlays';
App.register('config:modals-container-id',
modalContainerElId,
{ instantiate: false });
App.inject('service:modal-dialog',
'destinationElementId',
'config:modals-container-id');
appendContainerElement(App.rootElement, modalContainerElId);
}
| /*globals document */
let hasDOM = typeof document !== 'undefined';
function appendContainerElement(rootElementId, id) {
if (!hasDOM) {
return;
}
if (document.getElementById(id)) {
return;
}
let rootEl = document.querySelector(rootElementId);
let modalContainerEl = document.createElement('div');
modalContainerEl.id = id;
rootEl.appendChild(modalContainerEl);
}
export default function(App) {
let emberModalDialog = App.emberModalDialog || {};
let modalContainerElId = emberModalDialog.modalRootElementId || 'modal-overlays';
App.register('config:modals-container-id',
modalContainerElId,
{ instantiate: false });
App.inject('service:modal-dialog',
'destinationElementId',
'config:modals-container-id');
appendContainerElement(App.rootElement, modalContainerElId);
}
|
Make SimRun a new-style Python class. | #!/usr/bin/env python
from .s_ref import RefTypes
import s_options as o
class SimRun(object):
def __init__(self, options = None, mode = None):
# the options and mode
if options is None:
options = o.default_options[mode]
self.options = options
self.mode = mode
self._exits = [ ]
self._refs = { }
self.options = options
for t in RefTypes:
self._refs[t] = [ ]
def refs(self):
return self._refs
def exits(self):
return self._exits
# Categorize and add a sequence of refs to this run
def add_refs(self, *refs):
for r in refs:
if o.SYMBOLIC not in self.options and r.is_symbolic():
continue
self._refs[type(r)].append(r)
# Categorize and add a sequence of exits to this run
def add_exits(self, *exits):
for e in exits:
if o.SYMBOLIC not in self.options and e.sim_value.is_symbolic():
continue
self._exits.append(e)
# Copy the references
def copy_refs(self, other):
for ref_list in other.refs().itervalues():
self.add_refs(*ref_list)
| #!/usr/bin/env python
from .s_ref import RefTypes
import s_options as o
class SimRun:
def __init__(self, options = None, mode = None):
# the options and mode
if options is None:
options = o.default_options[mode]
self.options = options
self.mode = mode
self._exits = [ ]
self._refs = { }
self.options = options
for t in RefTypes:
self._refs[t] = [ ]
def refs(self):
return self._refs
def exits(self):
return self._exits
# Categorize and add a sequence of refs to this run
def add_refs(self, *refs):
for r in refs:
if o.SYMBOLIC not in self.options and r.is_symbolic():
continue
self._refs[type(r)].append(r)
# Categorize and add a sequence of exits to this run
def add_exits(self, *exits):
for e in exits:
if o.SYMBOLIC not in self.options and e.sim_value.is_symbolic():
continue
self._exits.append(e)
# Copy the references
def copy_refs(self, other):
for ref_list in other.refs().itervalues():
self.add_refs(*ref_list)
|
Use _.defer instead of setTimeout | import $ from 'jquery';
import _ from 'lodash';
import Radio from 'backbone.radio';
import nprogress from 'nprogress';
import Application from '../common/application';
import LayoutView from './layout-view';
let routerChannel = Radio.channel('router');
nprogress.configure({
showSpinner: false
});
export default Application.extend({
initialize() {
this.$body = $(document.body);
this.layout = new LayoutView();
this.layout.render();
this.listenTo(routerChannel, {
'before:enter:route' : this.onBeforeEnterRoute,
'enter:route' : this.onEnterRoute,
'error:route' : this.onErrorRoute
});
},
onBeforeEnterRoute() {
this.transitioning = true;
// Don't show for synchronous route changes
_.defer(() => {
if (this.transitioning) {
nprogress.start();
}
});
},
onEnterRoute() {
this.transitioning = false;
this.$body.scrollTop(0);
nprogress.done();
},
onErrorRoute() {
this.transitioning = false;
nprogress.done(true);
}
});
| import $ from 'jquery';
import Radio from 'backbone.radio';
import nprogress from 'nprogress';
import Application from '../common/application';
import LayoutView from './layout-view';
let routerChannel = Radio.channel('router');
nprogress.configure({
showSpinner: false
});
export default Application.extend({
initialize() {
this.$body = $(document.body);
this.layout = new LayoutView();
this.layout.render();
this.listenTo(routerChannel, {
'before:enter:route' : this.onBeforeEnterRoute,
'enter:route' : this.onEnterRoute,
'error:route' : this.onErrorRoute
});
},
onBeforeEnterRoute() {
this.transitioning = true;
// Don't show for synchronous route changes
setTimeout(() => {
if (this.transitioning) {
nprogress.start();
}
}, 0);
},
onEnterRoute() {
this.transitioning = false;
this.$body.scrollTop(0);
nprogress.done();
},
onErrorRoute() {
this.transitioning = false;
nprogress.done(true);
}
});
|
Update cmd to also print struct field names | package main
import (
"fmt"
"os"
"strings"
"github.com/hackebrot/go-librariesio/librariesio"
)
func loadFromEnv(keys ...string) (map[string]string, error) {
env := make(map[string]string)
for _, key := range keys {
v := os.Getenv(key)
if v == "" {
return nil, fmt.Errorf("environment variable %q is required", key)
}
env[key] = v
}
return env, nil
}
func main() {
env, err := loadFromEnv("LIBRARIESIO_API_KEY")
if err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
c := librariesio.NewClient(strings.TrimSpace(env["LIBRARIESIO_API_KEY"]))
project, _, err := c.GetProject("pypi", "cookiecutter")
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
fmt.Fprintf(os.Stdout, "%+v\n", project)
}
| package main
import (
"fmt"
"os"
"strings"
"github.com/hackebrot/go-librariesio/librariesio"
)
func loadFromEnv(keys ...string) (map[string]string, error) {
env := make(map[string]string)
for _, key := range keys {
v := os.Getenv(key)
if v == "" {
return nil, fmt.Errorf("environment variable %q is required", key)
}
env[key] = v
}
return env, nil
}
func main() {
env, err := loadFromEnv("LIBRARIESIO_API_KEY")
if err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
fmt.Fprintf(os.Stdout, "%v\n", env)
c := librariesio.NewClient(strings.TrimSpace(env["LIBRARIESIO_API_KEY"]))
project, _, err := c.GetProject("pypi", "cookiecutter")
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
fmt.Fprintf(os.Stdout, "%v\n", project)
}
|
Remove unused filename parameter from card image filename function | from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from time import time
def card_image_filename(instance):
timestamp = int(time())
return 'cards/%s%d.jpg' % (instance, timestamp)
@python_2_unicode_compatible
class Card(models.Model):
title = models.CharField(max_length=140, unique=True)
is_title_visible = models.BooleanField(default=True)
text = models.TextField()
secondary_text = models.TextField(null=True, blank=True)
author = models.CharField(max_length=100, null=True, blank=True)
image = models.ImageField(upload_to=card_image_filename, null=True, blank=True)
creation_datetime = models.DateTimeField(auto_now_add=True)
update_datetime = models.DateTimeField(auto_now=True)
is_active = models.BooleanField(default=True)
created_by = models.ForeignKey(User, null=True, blank=True, related_name='%(class)s_created_by')
updated_by = models.ForeignKey(User, null=True, blank=True, related_name='%(class)s_updated_by')
def __str__(self):
return self.title
| from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from time import time
def card_image_filename(instance, filename):
timestamp = int(time())
return 'cards/%s%d.jpg' % (instance, timestamp)
@python_2_unicode_compatible
class Card(models.Model):
title = models.CharField(max_length=140, unique=True)
is_title_visible = models.BooleanField(default=True)
text = models.TextField()
secondary_text = models.TextField(null=True, blank=True)
author = models.CharField(max_length=100, null=True, blank=True)
image = models.ImageField(upload_to=card_image_filename, null=True, blank=True)
creation_datetime = models.DateTimeField(auto_now_add=True)
update_datetime = models.DateTimeField(auto_now=True)
is_active = models.BooleanField(default=True)
created_by = models.ForeignKey(User, null=True, blank=True, related_name='%(class)s_created_by')
updated_by = models.ForeignKey(User, null=True, blank=True, related_name='%(class)s_updated_by')
def __str__(self):
return self.title
|
Fix remote computation document's start date bug.
This ensures that remote computation documents are created with a
dynamically generated start date.
Closes #185. | 'use strict';
const ComputationResult = require('./computation-result');
const joi = require('joi');
/* istanbul ignore next */
/**
* @class RemoteComputationResult
* @extends ComputationResult
* @description RemoteComputationResult result container
* @property {string[]} usernames
* @property {string} _id extends it's parent `PouchDocument` `_id` requirement
* and mandates the format: `runId`
*/
class RemoteComputationResult extends ComputationResult {
constructor(opts) {
super(opts);
this._idRegex = RemoteComputationResult._idRegex;
}
}
RemoteComputationResult._idRegex = /^([^-]+$)/; // format: runId
RemoteComputationResult.schema = Object.assign({}, ComputationResult.schema, {
_id: joi.string().regex(RemoteComputationResult._idRegex).required(),
complete: joi.boolean().default(false), // DecentralizedComputation complete/halted
computationInputs: joi.array().items(joi.array()).required(),
endDate: joi.date().timestamp(),
startDate: joi.date().timestamp()
.default(() => Date.now(), 'time of creation'),
usernames: joi.array().items(joi.string()).default([]),
userErrors: joi.array(),
// runId - derived from _id, enforced on ComputationResult instantiation
});
module.exports = RemoteComputationResult;
| 'use strict';
const ComputationResult = require('./computation-result');
const joi = require('joi');
/* istanbul ignore next */
/**
* @class RemoteComputationResult
* @extends ComputationResult
* @description RemoteComputationResult result container
* @property {string[]} usernames
* @property {string} _id extends it's parent `PouchDocument` `_id` requirement
* and mandates the format: `runId`
*/
class RemoteComputationResult extends ComputationResult {
constructor(opts) {
super(opts);
this._idRegex = RemoteComputationResult._idRegex;
}
}
RemoteComputationResult._idRegex = /^([^-]+$)/; // format: runId
RemoteComputationResult.schema = Object.assign({}, ComputationResult.schema, {
_id: joi.string().regex(RemoteComputationResult._idRegex).required(),
complete: joi.boolean().default(false), // DecentralizedComputation complete/halted
computationInputs: joi.array().items(joi.array()).required(),
endDate: joi.date().timestamp(),
startDate: joi.date().timestamp().default(Date.now()),
usernames: joi.array().items(joi.string()).default([]),
userErrors: joi.array(),
// runId - derived from _id, enforced on ComputationResult instantiation
});
module.exports = RemoteComputationResult;
|
Add AwsS3 to the dist bundle. | const Core = require('./core/index.js')
// Parent
const Plugin = require('./plugins/Plugin')
// Orchestrators
const Dashboard = require('./plugins/Dashboard/index.js')
// Acquirers
const Dummy = require('./plugins/Dummy')
const DragDrop = require('./plugins/DragDrop/index.js')
const FileInput = require('./plugins/FileInput.js')
const GoogleDrive = require('./plugins/GoogleDrive/index.js')
const Dropbox = require('./plugins/Dropbox/index.js')
const Instagram = require('./plugins/Instagram/index.js')
const Webcam = require('./plugins/Webcam/index.js')
// Progressindicators
const ProgressBar = require('./plugins/ProgressBar.js')
const Informer = require('./plugins/Informer.js')
// Modifiers
const MetaData = require('./plugins/MetaData.js')
// Uploaders
const Tus10 = require('./plugins/Tus10')
const XHRUpload = require('./plugins/XHRUpload')
const Transloadit = require('./plugins/Transloadit')
const AwsS3 = require('./plugins/AwsS3')
module.exports = {
Core,
Plugin,
Dummy,
ProgressBar,
Informer,
DragDrop,
GoogleDrive,
Dropbox,
Instagram,
FileInput,
Tus10,
XHRUpload,
Transloadit,
AwsS3,
Dashboard,
MetaData,
Webcam
}
| const Core = require('./core/index.js')
// Parent
const Plugin = require('./plugins/Plugin')
// Orchestrators
const Dashboard = require('./plugins/Dashboard/index.js')
// Acquirers
const Dummy = require('./plugins/Dummy')
const DragDrop = require('./plugins/DragDrop/index.js')
const FileInput = require('./plugins/FileInput.js')
const GoogleDrive = require('./plugins/GoogleDrive/index.js')
const Dropbox = require('./plugins/Dropbox/index.js')
const Instagram = require('./plugins/Instagram/index.js')
const Webcam = require('./plugins/Webcam/index.js')
// Progressindicators
const ProgressBar = require('./plugins/ProgressBar.js')
const Informer = require('./plugins/Informer.js')
// Modifiers
const MetaData = require('./plugins/MetaData.js')
// Uploaders
const Tus10 = require('./plugins/Tus10')
const XHRUpload = require('./plugins/XHRUpload')
const Transloadit = require('./plugins/Transloadit')
module.exports = {
Core,
Plugin,
Dummy,
ProgressBar,
Informer,
DragDrop,
GoogleDrive,
Dropbox,
Instagram,
FileInput,
Tus10,
XHRUpload,
Transloadit,
Dashboard,
MetaData,
Webcam
}
|
Use briefer url views import. | from django.conf.urls import patterns, url
from . import views
urlpatterns = patterns(
'',
url(r'^$', views.{{ cookiecutter.model_name }}List.as_view(), name='{{ cookiecutter.model_name|lower }}_list'),
url(r'^new/$', views.{{ cookiecutter.model_name }}Create.as_view(), name='{{ cookiecutter.model_name|lower }}_create'),
url(r'^(?P<pk>\d+)/$', views.{{ cookiecutter.model_name }}Detail.as_view(), name='{{ cookiecutter.model_name|lower }}_detail'),
url(r'^(?P<pk>\d+)/update/$', views.{{ cookiecutter.model_name }}Update.as_view(), name='{{ cookiecutter.model_name|lower }}_update'),
url(r'^(?P<pk>\d+)/delete/$', views.{{ cookiecutter.model_name }}Delete.as_view(), name='{{ cookiecutter.model_name|lower }}_delete'),
)
| from django.conf.urls import patterns, url
from .views import {{ cookiecutter.model_name }}List, {{ cookiecutter.model_name }}Create, {{ cookiecutter.model_name }}Detail, {{ cookiecutter.model_name }}Update, {{ cookiecutter.model_name }}Delete
urlpatterns = patterns(
'',
url(r'^$', {{ cookiecutter.model_name }}List.as_view(), name='{{ cookiecutter.model_name|lower }}_list'),
url(r'^new/$', {{ cookiecutter.model_name }}Create.as_view(), name='{{ cookiecutter.model_name|lower }}_create'),
url(r'^(?P<pk>\d+)/$', {{ cookiecutter.model_name }}Detail.as_view(), name='{{ cookiecutter.model_name|lower }}_detail'),
url(r'^(?P<pk>\d+)/update/$', {{ cookiecutter.model_name }}Update.as_view(), name='{{ cookiecutter.model_name|lower }}_update'),
url(r'^(?P<pk>\d+)/delete/$', {{ cookiecutter.model_name }}Delete.as_view(), name='{{ cookiecutter.model_name|lower }}_delete'),
)
|
Add a default fixed fee currency
This prevents an unhandled error when mobile nodes are returned as moderators without a fixedFee object. | import BaseModel from '../BaseModel';
import app from '../../app';
import { getCurrencyByCode } from '../../data/currencies';
import is from 'is_js';
export default class extends BaseModel {
defaults() {
return {
currencyCode: 'USD',
amount: 0,
};
}
validate(attrs) {
const errObj = {};
const addError = (fieldName, error) => {
errObj[fieldName] = errObj[fieldName] || [];
errObj[fieldName].push(error);
};
if (is.not.existy(attrs.currencyCode) || typeof attrs.currencyCode !== 'string') {
addError('feeType', app.polyglot.t('fixedFeeModelErrors.noCurrency'));
}
if (typeof attrs.currencyCode !== 'string' ||
!attrs.currencyCode ||
!getCurrencyByCode(attrs.currencyCode)) {
addError('feeType', app.polyglot.t('fixedFeeModelErrors.noCurrency'));
}
if (typeof attrs.amount !== 'number' || attrs.amount < 0) {
addError('feeType', app.polyglot.t('fixedFeeModelErrors.noAmount'));
}
if (Object.keys(errObj).length) return errObj;
return undefined;
}
}
| import BaseModel from '../BaseModel';
import app from '../../app';
import { getCurrencyByCode } from '../../data/currencies';
import is from 'is_js';
export default class extends BaseModel {
defaults() {
return {
currencyCode: '',
amount: 0,
};
}
validate(attrs) {
const errObj = {};
const addError = (fieldName, error) => {
errObj[fieldName] = errObj[fieldName] || [];
errObj[fieldName].push(error);
};
if (is.not.existy(attrs.currencyCode) || typeof attrs.currencyCode !== 'string') {
addError('feeType', app.polyglot.t('fixedFeeModelErrors.noCurrency'));
}
if (typeof attrs.currencyCode !== 'string' ||
!attrs.currencyCode ||
!getCurrencyByCode(attrs.currencyCode)) {
addError('feeType', app.polyglot.t('fixedFeeModelErrors.noCurrency'));
}
if (typeof attrs.amount !== 'number' || attrs.amount < 0) {
addError('feeType', app.polyglot.t('fixedFeeModelErrors.noAmount'));
}
if (Object.keys(errObj).length) return errObj;
return undefined;
}
}
|
Add mock as it's required by the unit tests. | import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='mdot-rest',
version='0.1',
packages=['mdot_rest'],
include_package_data=True,
install_requires=[
'setuptools',
'django',
'djangorestframework',
'django-filter',
'Pillow',
'mock',
],
license='Apache License, Version 2.0',
description='A RESTful API server for references to mobile resources.',
long_description=README,
url='',
author='Craig M. Stimmel',
author_email='cstimmel@uw.edu',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
| import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='mdot-rest',
version='0.1',
packages=['mdot_rest'],
include_package_data=True,
install_requires=[
'setuptools',
'django',
'djangorestframework',
'django-filter',
'Pillow',
],
license='Apache License, Version 2.0',
description='A RESTful API server for references to mobile resources.',
long_description=README,
url='',
author='Craig M. Stimmel',
author_email='cstimmel@uw.edu',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
|
Use log dir from global context instead of hard-coded string. | package bio.terra.cli.command.config.getvalue;
import bio.terra.cli.context.GlobalContext;
import java.util.concurrent.Callable;
import org.slf4j.LoggerFactory;
import picocli.CommandLine.Command;
/** This class corresponds to the fourth-level "terra config get-value logging" command. */
@Command(name = "logging", description = "Get the logging level.")
public class Logging implements Callable<Integer> {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(Logging.class);
@Override
public Integer call() {
GlobalContext globalContext = GlobalContext.readFromFile();
System.out.println(
"[console] logging level for printing directly to the terminal = "
+ globalContext.consoleLoggingLevel);
System.out.println(
"[file] logging level for writing to files in "
+ GlobalContext.getLogFile().getParent()
+ " = "
+ globalContext.fileLoggingLevel);
return 0;
}
}
| package bio.terra.cli.command.config.getvalue;
import bio.terra.cli.context.GlobalContext;
import java.util.concurrent.Callable;
import org.slf4j.LoggerFactory;
import picocli.CommandLine.Command;
/** This class corresponds to the fourth-level "terra config get-value logging" command. */
@Command(name = "logging", description = "Get the logging level.")
public class Logging implements Callable<Integer> {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(Logging.class);
@Override
public Integer call() {
GlobalContext globalContext = GlobalContext.readFromFile();
System.out.println(
"[console] logging level for printing directly to the terminal = "
+ globalContext.consoleLoggingLevel);
System.out.println(
"[file] logging level for writing to files in $HOME/.terra/logs/ = "
+ globalContext.fileLoggingLevel);
return 0;
}
}
|
Add optional args for container_class for nav-menu container default class is 'sailen_short_menu_con'
<code> [menu name="Primary" class="my_custom_class" con="my_custom_class"] </code> | <?php
class Sailen_Short_Menu{
/**
*
* @var string A unique string prefix for properties to avoid conflict
*/
public $prefix = 'ssmSavp_';
function __construct(){
add_shortcode('menu', array($this,'ssmSavpDisplaySc'));
}
/**
*
* @var string A unique string prefix for properties to avoid conflict
*/
/**
* @param array $atts
* @return HTML ENTITIES filter applied
*/
function ssmSavpDisplaySc($atts) {
$def=$atts['class']; //ul class
$con=$atts['con'];//Container class
if(!isset($atts['class']) || strlen(trim($atts['class']))<=0 ){
$def='sailen_short_menu'; //default class to plugin namesapce
}
if(!isset($atts['con']) || strlen(trim($atts['con']))<=0 ){
$con='sailen_short_menu_con'; //default class to plugin namesapce
}
return apply_filters('ssmSavpfilter_style',wp_nav_menu( array('menu' => $atts['name'], 'menu_class'=> $def,'echo' => false, 'container_class'=>$con )));
}
}
| <?php
class Sailen_Short_Menu{
/**
*
* @var string A unique string prefix for properties to avoid conflict
*/
public $prefix = 'ssmSavp_';
function __construct(){
add_shortcode('menu', array($this,'ssmSavpDisplaySc'));
}
/**
*
* @var string A unique string prefix for properties to avoid conflict
*/
/**
* @param array $atts
* @return HTML ENTITIES filter applied
*/
function ssmSavpDisplaySc($atts) {
$def=$atts['class'];
if(!isset($atts['class']) || strlen(trim($atts['class']))<=0 ){
$def='sailen_short_menu'; //default class to plugin namesapce
}
return apply_filters('ssmSavpfilter_style',wp_nav_menu( array('menu' => $atts['name'], 'menu_class'=> $def,'echo' => false )));
}
}
|
Allow count method to be used the same way as find. | class Countable(object):
@classmethod
def count(cls, _options=None, **kwargs):
if _options is None:
_options = kwargs
return int(cls.get("count", **_options))
class Metafields(object):
def metafields(self):
return Metafield.find(resource=self.__class__.plural, resource_id=self.id)
def add_metafield(self, metafield):
if self.is_new():
raise ValueError("You can only add metafields to a resource that has been saved")
metafield._prefix_options = dict(resource=self.__class__.plural, resource_id=self.id)
metafield.save()
return metafield
class Events(object):
def events(self):
return Event.find(resource=self.__class__.plural, resource_id=self.id)
| class Countable(object):
@classmethod
def count(cls, options={}):
return int(cls.get("count", **options))
class Metafields(object):
def metafields(self):
return Metafield.find(resource=self.__class__.plural, resource_id=self.id)
def add_metafield(self, metafield):
if self.is_new():
raise ValueError("You can only add metafields to a resource that has been saved")
metafield._prefix_options = dict(resource=self.__class__.plural, resource_id=self.id)
metafield.save()
return metafield
class Events(object):
def events(self):
return Event.find(resource=self.__class__.plural, resource_id=self.id)
|
Remove the Pythonic Soul Trademark for now.. causing unicode issues with python2 | import click
import requests
import os
import shutil
from appdirs import user_data_dir
from airpy.install import airinstall
from airpy.list import airlist
from airpy.start import airstart
from airpy.remove import airremove
from airpy.autopilot import airautopilot
def main():
@click.group()
def airpy():
"""AirPy : Documentation Installer for the Pythonic Soul"""
pass
@airpy.command(help = 'Install offline doc of a Python module.')
@click.argument('name')
def install(name):
airinstall(name)
@airpy.command(help = 'Start a doc in a browser.')
@click.argument('name')
def start(name):
airstart(name)
@airpy.command(help = 'Remove an installed doc.')
@click.argument('name')
@click.option('--all')
def remove(name, all):
airremove(name)
@airpy.command(help = 'List installed docs.')
def list():
airlist()
@airpy.command(help = 'Auto install docs.')
def autopilot():
airautopilot()
airpy()
if __name__ == '__main__':
main()
| import click
import requests
import os
import shutil
from appdirs import user_data_dir
from airpy.install import airinstall
from airpy.list import airlist
from airpy.start import airstart
from airpy.remove import airremove
from airpy.autopilot import airautopilot
def main():
@click.group()
def airpy():
"""AirPy : Documentation Installer for the Pythonic Soul™"""
pass
@airpy.command(help = 'Install offline doc of a Python module.')
@click.argument('name')
def install(name):
airinstall(name)
@airpy.command(help = 'Start a doc in a browser.')
@click.argument('name')
def start(name):
airstart(name)
@airpy.command(help = 'Remove an installed doc.')
@click.argument('name')
@click.option('--all')
def remove(name, all):
airremove(name)
@airpy.command(help = 'List installed docs.')
def list():
airlist()
@airpy.command(help = 'Auto install docs.')
def autopilot():
airautopilot()
airpy()
if __name__ == '__main__':
main() |
Update of the environment detect using hosts | <?php namespace Exolnet\Core;
class EnvironmentDetector
{
private static $environments = [
'development.exolnet.com' => 'local',
'staging.exolnet.com' => 'staging',
'testing.exolnet.com' => 'staging',
];
/**
* @param $environments
* @return callable
*/
public static function detect($environments)
{
// TODO: Do not allow $is_behat = true in production environment
$is_behat = self::is_remote_test();
if ($is_behat) {
return function() { return 'test'; };
}
if (isset($_SERVER['HTTP_HOST']))
{
$host = $_SERVER['HTTP_HOST'];
if (array_key_exists($host, self::$environments)) {
return function() use ($host) { return self::$environments[$host]; };
}
}
return $environments;
}
/**
* Add environements to host detector.
*
* @param array $environments
*/
public static function addEnvironments(array $environments)
{
static::$environments = $environments + static::$environments;
}
/**
* @return bool
*/
public static function is_remote_test()
{
return array_get($_COOKIE, 'test-env') === 'true';
}
}
| <?php namespace Exolnet\Core;
class EnvironmentDetector
{
private static $environments = [
'development.exolnet.com' => 'local',
'staging.exolnet.com' => 'staging',
'testing.exolnet.com' => 'staging',
];
/**
* @param $environments
* @return callable
*/
public static function detect($environments)
{
// TODO: Do not allow $is_behat = true in production environment
$is_behat = self::is_remote_test();
if ($is_behat) {
return function() { return 'test'; };
}
if (isset($_SERVER['HTTP_HOST']))
{
$host = $_SERVER['HTTP_HOST'];
if (array_key_exists($host, self::$environments)) {
return function() use ($host) { return self::$environments[$host]; };
}
}
return $environments;
}
/**
* @return bool
*/
public static function is_remote_test()
{
return array_get($_COOKIE, 'test-env') === 'true';
}
} |
Simplify and remove unused imports | import { mix } from 'mixwith';
import PixiTrack from './PixiTrack';
import { RuleMixin } from './RuleMixin';
import { HorizontalRuleMixin } from './HorizontalRule';
import { VerticalRuleMixin } from './VerticalRule';
export class CrossRule extends mix(PixiTrack).with(RuleMixin, HorizontalRuleMixin, VerticalRuleMixin) {
constructor(stage, xPosition, yPosition, options, animate) {
super(stage, options, animate);
this.xPosition = xPosition;
this.yPosition = yPosition;
}
draw() {
const graphics = this.pMain;
graphics.clear();
this.drawHorizontalRule(graphics);
this.drawVerticalRule(graphics);
}
mouseMoveHandler(mousePos) {
this.highlighted = (
this.isWithin(mousePos.x, mousePos.y)
&& (
this.isMouseOverHorizontalLine(mousePos)
|| this.isMouseOverVerticalLine(mousePos)
)
);
this.draw();
}
}
export default CrossRule;
| import { mix, Mixin } from 'mixwith';
import PixiTrack from './PixiTrack.js';
import { colorToHex } from './utils';
import { RuleMixin } from './RuleMixin';
import { HorizontalRuleMixin } from './HorizontalRule.js';
import { VerticalRuleMixin } from './VerticalRule.js';
export class CrossRule extends mix(PixiTrack).with(RuleMixin, HorizontalRuleMixin, VerticalRuleMixin) {
constructor(stage, xPosition, yPosition, options, animate) {
super(stage, options, animate);
this.xPosition = xPosition;
this.yPosition = yPosition;
}
draw() {
const graphics = this.pMain;
graphics.clear();
this.drawHorizontalRule(graphics);
this.drawVerticalRule(graphics);
}
mouseMoveHandler(mousePos) {
if (this.isWithin(mousePos.x, mousePos.y) &&
this.isMouseOverHorizontalLine(mousePos) || this.isMouseOverVerticalLine(mousePos)) {
this.highlighted = true;
this.draw();
return;
}
this.highlighted = false;
this.draw();
}
}
export default CrossRule;
|
Make handhistory speed test work from root dir | from timeit import timeit, repeat
results, single_results = [], []
for handnr in range(1, 5):
single_results.append(
timeit(f'PokerStarsHandHistory(HAND{handnr})', number=100000,
setup="from poker.room.pokerstars import PokerStarsHandHistory; "
f"from tests.handhistory.stars_hands import HAND{handnr}")
)
results.extend(repeat(f'PokerStarsHandHistory(HAND{handnr})', repeat=3, number=100000,
setup="from poker.room.pokerstars import PokerStarsHandHistory; "
f"from tests.handhistory.stars_hands import HAND{handnr}")
)
print("Single results average:", sum(single_results) / len(single_results))
print("Repeated results average:", sum(results) / len(results))
| from timeit import timeit, repeat
results, single_results = [], []
for handnr in range(1, 5):
single_results.append(
timeit(f'PokerStarsHandHistory(HAND{handnr})', number=100000,
setup="from handhistory import PokerStarsHandHistory; "
f"from stars_hands import HAND{handnr}")
)
results.extend(repeat(f'PokerStarsHandHistory(HAND{handnr})', repeat=3, number=100000,
setup="from handhistory import PokerStarsHandHistory; "
f"from stars_hands import HAND{handnr}")
)
print("Single results average:", sum(single_results) / len(single_results))
print("Repeated results average:", sum(results) / len(results))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.