text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Increase the frequency of the sensing checks (important for the color sensor/simple line following. | import threading
import time
class SensorThread(object):
def __init__(self, notify, delay=0):
self.notify = notify
self.delay = delay
self.interval = 0.1
self.color = -1
def start(self, control, robot):
self.control = control
self.robot = robot
thread = threading.Thread(target=self.run, args=())
thread.daemon = True # Daemonize thread
thread.start() # Start the execution
def run(self):
while True:
color = int(self.robot.color())
touch = self.robot.touch()
try:
direction = self.robot.direction()
except:
direction = 0
self.control.readings(color, touch, direction)
time.sleep(self.interval)
def sensors(self, color, touch, direction):
#print "sense: %s %s" % (touch, direction)
if not self.color == color:
self.notify.emit('sense', color)
self.color = color
print "color %s%%" % color
| import threading
import time
class SensorThread(object):
def __init__(self, notify, delay=0):
self.notify = notify
self.delay = delay
self.interval = 0.2
self.color = -1
def start(self, control, robot):
self.control = control
self.robot = robot
thread = threading.Thread(target=self.run, args=())
thread.daemon = True # Daemonize thread
thread.start() # Start the execution
def run(self):
while True:
color = int(self.robot.color())
touch = self.robot.touch()
try:
direction = self.robot.direction()
except:
direction = 0
self.control.readings(color, touch, direction)
time.sleep(self.interval)
def sensors(self, color, touch, direction):
#print "sense: %s %s" % (touch, direction)
if not self.color == color:
self.notify.emit('sense', color)
self.color = color
print "color %s%%" % color
|
Remove sorting by hashCode() - All right that was not a good idea - it breaks those from Migrators which don't set dependency yet... | package org.jboss.loom.actions;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Sorts a list of actions so that dependencies go first, and depending actions go after.
*
* @Jira MIGR-104
* @author Ondrej Zizka, ozizka at redhat.com
*/
public class ActionDependencySorter {
public static <T extends IMigrationAction> List<T> sort( List<T> actions ){
List<T> ret = new ArrayList(actions);
Collections.sort( ret, new DepComparator() );
return ret;
}
static class DepComparator implements Comparator<IMigrationAction> {
@Override
public int compare( IMigrationAction o1, IMigrationAction o2 ) {
try {
int a = o1.dependsOn( o2 );
if( a != -1 ) return -a;
int b = o2.dependsOn( o1 );
if( b != -1 ) return -b;
//return Integer.compare( o1.hashCode(), o2.hashCode() ); // For deterministic behavior.
return 0; // All right that was not a good idea - it breaks those from Migrators which don't set dependency yet...
}
catch( AbstractStatefulAction.CircularDependencyException ex ){
throw new RuntimeException( ex );
}
}
}
}// class
| package org.jboss.loom.actions;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Sorts a list of actions so that dependencies go first, and depending actions go after.
*
* @Jira MIGR-104
* @author Ondrej Zizka, ozizka at redhat.com
*/
public class ActionDependencySorter {
public static <T extends IMigrationAction> List<T> sort( List<T> actions ){
List<T> ret = new ArrayList(actions);
Collections.sort( ret, new DepComparator() );
return ret;
}
static class DepComparator implements Comparator<IMigrationAction> {
@Override
public int compare( IMigrationAction o1, IMigrationAction o2 ) {
try {
int a = o1.dependsOn( o2 );
if( a != -1 ) return -a;
int b = o2.dependsOn( o1 );
if( b != -1 ) return -b;
return Integer.compare( o1.hashCode(), o2.hashCode() ); // For deterministic behavior.
}
catch( AbstractStatefulAction.CircularDependencyException ex ){
throw new RuntimeException( ex );
}
}
}
}// class
|
Improve the stack returned from PdfkiwiError | class PdfkiwiError extends Error {
constructor(message, code, status) {
super(message);
const hasValidCode = code !== null && code !== undefined;
Object.defineProperty(this, 'message', {
configurable : true,
enumerable : false,
value : hasValidCode ? `${code}: ${message}` : message,
writable : true
});
Object.defineProperty(this, 'name', {
configurable : true,
enumerable : false,
value : this.constructor.name,
writable : true
});
Object.defineProperty(this, 'code', {
configurable : true,
enumerable : false,
value : code,
writable : true
});
Object.defineProperty(this, 'status', {
configurable : true,
enumerable : false,
value : status,
writable : true
});
// eslint-disable-next-line no-prototype-builtins
if (Error.hasOwnProperty('captureStackTrace')) {
Error.captureStackTrace(this, this.constructor);
return;
}
Object.defineProperty(this, 'stack', {
configurable : true,
enumerable : false,
value : (new Error(message)).stack,
writable : true
});
}
}
module.exports = PdfkiwiError;
| class PdfkiwiError extends Error {
constructor(message, code, status) {
super(message);
const hasValidCode = code !== null && code !== undefined;
Object.defineProperty(this, 'message', {
configurable : true,
enumerable : false,
value : hasValidCode ? `${code}: ${message}` : message,
writable : true
});
Object.defineProperty(this, 'name', {
configurable : true,
enumerable : false,
value : this.constructor.name,
writable : true
});
Object.defineProperty(this, 'code', {
configurable : true,
enumerable : false,
value : code,
writable : true
});
Object.defineProperty(this, 'status', {
configurable : true,
enumerable : false,
value : status,
writable : true
});
}
}
module.exports = PdfkiwiError;
|
Test with default value fails on new query serializer | <?php
namespace GuzzleHttp\Tests\Command\Guzzle;
use GuzzleHttp\Command\Command;
use GuzzleHttp\Command\Guzzle\Description;
use GuzzleHttp\Command\Guzzle\Serializer;
use GuzzleHttp\Psr7\Request;
/**
* @covers \GuzzleHttp\Command\Guzzle\Serializer
*/
class SerializerTest extends \PHPUnit_Framework_TestCase
{
public function testAllowsUriTemplates()
{
$description = new Description([
'baseUri' => 'http://test.com',
'operations' => [
'test' => [
'httpMethod' => 'GET',
'uri' => '/api/{key}/foo',
'parameters' => [
'key' => [
'required' => true,
'type' => 'string',
'location' => 'uri'
],
]
]
]
]);
$command = new Command('test', ['key' => 'bar']);
$serializer = new Serializer($description);
/** @var Request $request */
$request = $serializer($command);
$this->assertEquals('http://test.com/api/bar/foo', $request->getUri());
}
public function testAllowsDefaultParameterUriTemplates()
{
$description = new Description([
'baseUri' => 'http://test.com',
'operations' => [
'test' => [
'httpMethod' => 'GET',
'uri' => '/api/{key}/foo',
'parameters' => [
'key' => [
'required' => true,
'type' => 'string',
'location' => 'uri',
'default' => 'bar',
],
]
]
]
]);
$command = new Command('test');
$serializer = new Serializer($description);
/** @var Request $request */
$request = $serializer($command);
$this->assertEquals('http://test.com/api/bar/foo', $request->getUri());
}
}
| <?php
namespace GuzzleHttp\Tests\Command\Guzzle;
use GuzzleHttp\Command\Command;
use GuzzleHttp\Command\Guzzle\Description;
use GuzzleHttp\Command\Guzzle\Serializer;
use GuzzleHttp\Psr7\Request;
/**
* @covers \GuzzleHttp\Command\Guzzle\Serializer
*/
class SerializerTest extends \PHPUnit_Framework_TestCase
{
public function testAllowsUriTemplates()
{
$description = new Description([
'baseUri' => 'http://test.com',
'operations' => [
'test' => [
'httpMethod' => 'GET',
'uri' => '/api/{key}/foo',
'parameters' => [
'key' => [
'required' => true,
'type' => 'string',
'location' => 'uri'
],
]
]
]
]);
$command = new Command('test', ['key' => 'bar']);
$serializer = new Serializer($description);
/** @var Request $request */
$request = $serializer($command);
$this->assertEquals('http://test.com/api/bar/foo', $request->getUri());
}
}
|
Check version for latest cask behaviour changed | #! /usr/bin/env python
# -*- coding: utf8 -*-
import argparse
import shutil
from subprocess import check_output, run
parser = argparse.ArgumentParser(description='Update every entries found in cask folder.')
parser.add_argument('--pretend', dest='pretend', action='store_true',
help='Pretend to take action.')
parser.set_defaults(pretend=False)
args = parser.parse_args()
brew_bin = 'brew'
if not shutil.which(brew_bin):
raise FileExistsError(brew_bin + ' not exists')
list_command = [
brew_bin,
'cask',
'list'
]
list_installed = str.split(check_output(list_command).decode(), '\n')
list_installed = [i for i in list_installed if i is not '']
for cask in list_installed:
info_command = [
brew_bin,
'cask',
'info',
cask
]
try:
install_status = str.splitlines(check_output(info_command).decode())
except:
install_status = 'Not installed'
version = str.strip(str.split(install_status[0], ':')[1])
is_version_installed = False
for line in install_status:
if not line.startswith(cask) and line.__contains__(cask) and line.__contains__(version):
is_version_installed = True
if not is_version_installed:
print('Installing', cask)
install_command = [
brew_bin,
'cask',
'install',
'--force',
cask
]
if args.pretend:
print(' '.join(install_command))
else:
run(install_command)
print('Installed', cask)
| #! /usr/bin/env python
# -*- coding: utf8 -*-
import argparse
import shutil
from subprocess import check_output, run
parser = argparse.ArgumentParser(description='Update every entries found in cask folder.')
parser.add_argument('--pretend', dest='pretend', action='store_true',
help='Pretend to take action.')
parser.set_defaults(pretend=False)
args = parser.parse_args()
brew_bin = 'brew'
if not shutil.which(brew_bin):
raise FileExistsError(brew_bin + ' not exists')
list_command = [
brew_bin,
'cask',
'list'
]
list_installed = str.split(check_output(list_command).decode(), '\n')
list_installed = [i for i in list_installed if i is not '']
for cask in list_installed:
info_command = [
brew_bin,
'cask',
'info',
cask
]
try:
install_status = check_output(info_command).decode()
except:
install_status = 'Not installed'
if 'Not installed' in install_status:
print('Installing', cask)
install_command = [
brew_bin,
'cask',
'install',
'--force',
cask
]
if args.pretend:
print(' '.join(install_command))
else:
run(install_command)
print('Installed', cask)
|
Replace \n with %n so that tests work on Windows. | package cucumber.runtime.java.test;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
public class SubstitutionStepdefs {
private static final Map<String, String> ROLES = new HashMap<String, String>() {{
put("Manager", "now able to manage your employee accounts");
put("Admin", "able to manage any user account on the system");
}};
private String name;
private String role;
private String details;
@Given("^I have a user account with my name \"([^\"]*)\"$")
public void I_have_a_user_account_with_my_name(String name) throws Throwable {
this.name = name;
}
@When("^an Admin grants me (.+) rights$")
public void an_Admin_grants_me_role_rights(String role) throws Throwable {
this.role = role;
this.details = ROLES.get(role);
}
@Then("^I should receive an email with the body:$")
public void I_should_receive_an_email_with_the_body(String body) throws Throwable {
String expected = String.format("Dear %s,%n" +
"You have been granted %s rights. You are %s. Please be responsible.%n" +
"-The Admins", name, role, details);
assertEquals(expected, body);
}
}
| package cucumber.runtime.java.test;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
public class SubstitutionStepdefs {
private static final Map<String, String> ROLES = new HashMap<String, String>() {{
put("Manager", "now able to manage your employee accounts");
put("Admin", "able to manage any user account on the system");
}};
private String name;
private String role;
private String details;
@Given("^I have a user account with my name \"([^\"]*)\"$")
public void I_have_a_user_account_with_my_name(String name) throws Throwable {
this.name = name;
}
@When("^an Admin grants me (.+) rights$")
public void an_Admin_grants_me_role_rights(String role) throws Throwable {
this.role = role;
this.details = ROLES.get(role);
}
@Then("^I should receive an email with the body:$")
public void I_should_receive_an_email_with_the_body(String body) throws Throwable {
String expected = String.format("Dear %s,\n" +
"You have been granted %s rights. You are %s. Please be responsible.\n" +
"-The Admins", name, role, details);
assertEquals(expected, body);
}
}
|
Add 404 head for not found routes | <?hh // decl
class Route {
public static function dispatch(string $path, string $method): void {
// Get the auto-generated URI Map
$routes = require('build/URIMap.php');
// Match the path
foreach($routes as $route_path => $controller_name) {
$uri = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
if(preg_match(
"@^$route_path$@i",
"$uri",
$_SESSION['route_params'])
) {
$controller = new $controller_name();
invariant($controller instanceof BaseController);
Auth::verifyStatus($controller->getConfig()->getUserState());
Auth::verifyRoles($controller->getConfig()->getUserRoles());
$content = $controller::$method();
if(is_object($content) && is_a($content, :xhp::class)) {
Render::go($content, $controller_name);
} elseif (
(is_array($content)) ||
(is_object($content) && is_a($content, Map::class))
) {
header('Content-Type: application/json');
print json_encode($content, JSON_PRETTY_PRINT);
}
return;
}
}
// No path was matched
http_response_code(404);
Render::go(FourOhFourController::get(), 'FourOhFourController');
}
public static function redirect(string $path): void {
header('Location: ' . $path);
exit();
}
}
| <?hh // decl
class Route {
public static function dispatch(string $path, string $method): void {
// Get the auto-generated URI Map
$routes = require('build/URIMap.php');
// Match the path
foreach($routes as $route_path => $controller_name) {
$uri = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
if(preg_match(
"@^$route_path$@i",
"$uri",
$_SESSION['route_params'])
) {
$controller = new $controller_name();
invariant($controller instanceof BaseController);
Auth::verifyStatus($controller->getConfig()->getUserState());
Auth::verifyRoles($controller->getConfig()->getUserRoles());
$content = $controller::$method();
if(is_object($content) && is_a($content, :xhp::class)) {
Render::go($content, $controller_name);
} elseif (
(is_array($content)) ||
(is_object($content) && is_a($content, Map::class))
) {
header('Content-Type: application/json');
print json_encode($content, JSON_PRETTY_PRINT);
}
return;
}
}
// No path was matched
Render::go(FourOhFourController::get(), 'FourOhFourController');
}
public static function redirect(string $path): void {
header('Location: ' . $path);
exit();
}
}
|
Make video a little bit smaller | import PropTypes from 'prop-types'
import React, { Component } from 'react'
import YouTube from 'react-youtube'
import config from '../../../config'
import { StaticPage } from '../components'
import { translate } from '../services/i18n'
import { withAuthState } from '../containers'
const videoOptions = {
playerVars: {
autoplay: 0,
cc_load_policy: 0,
controls: 1,
disablekb: 1,
fs: 0,
iv_load_policy: 3,
modestbranding: 1,
playsinline: 1,
showinfo: 0,
rel: 0,
},
}
const videoId = config.video.tutorial
class Home extends Component {
static propTypes = {
isAdmin: PropTypes.bool.isRequired,
isAuthenticated: PropTypes.bool.isRequired,
isParticipant: PropTypes.bool.isRequired,
}
render() {
const { isAdmin, isAuthenticated, isParticipant } = this.props
if (isAuthenticated && (isParticipant || isAdmin)) {
return (
<section>
<StaticPage slug="home-with-video" />
<hr />
<h2>{ translate('views.home.platformTutorial') }</h2>
<div className="form">
<div className="youtube">
<YouTube
className="youtube__container"
opts={videoOptions}
videoId={videoId}
/>
</div>
</div>
</section>
)
}
return (
<section>
<StaticPage slug="home" />
</section>
)
}
}
export default withAuthState(Home)
| import PropTypes from 'prop-types'
import React, { Component } from 'react'
import YouTube from 'react-youtube'
import config from '../../../config'
import { StaticPage } from '../components'
import { translate } from '../services/i18n'
import { withAuthState } from '../containers'
const videoOptions = {
playerVars: {
autoplay: 0,
cc_load_policy: 0,
controls: 1,
disablekb: 1,
fs: 0,
iv_load_policy: 3,
modestbranding: 1,
playsinline: 1,
showinfo: 0,
rel: 0,
},
}
const videoId = config.video.tutorial
class Home extends Component {
static propTypes = {
isAdmin: PropTypes.bool.isRequired,
isAuthenticated: PropTypes.bool.isRequired,
isParticipant: PropTypes.bool.isRequired,
}
render() {
const { isAdmin, isAuthenticated, isParticipant } = this.props
if (isAuthenticated && (isParticipant || isAdmin)) {
return (
<section>
<StaticPage slug="home-with-video" />
<hr />
<h2>{ translate('views.home.platformTutorial') }</h2>
<div className="youtube">
<YouTube
className="youtube__container"
opts={videoOptions}
videoId={videoId}
/>
</div>
</section>
)
}
return (
<section>
<StaticPage slug="home" />
</section>
)
}
}
export default withAuthState(Home)
|
Support arrays and array-like objects | ;(function(root) {
'use strict';
var handler = function(e) {
var href, usedModifier, child;
href = e.target.getAttribute('href');
if (!href) return;
usedModifier = (e.ctrlKey || e.shiftKey || e.metaKey);
if (!usedModifier && e.target.getAttribute('target') !== '_blank') {
return;
}
child = window.open(href);
child.opener = null;
e.preventDefault();
};
var blankshield = function(target) {
if (typeof target.length === 'undefined') {
addEvent(target, 'click', handler);
} else if (typeof target !== 'string' && !(target instanceof String)) {
for (var i = 0; i < target.length; i++) {
addEvent(target[i], 'click', handler);
}
}
};
function addEvent(target, type, listener) {
if (target.addEventListener) {
target.addEventListener(type, listener, false);
} else if (target.attachEvent) {
target.attachEvent('on' + type, listener);
} else {
target['on' + type] = listener;
}
}
/**
* Export for various environments.
*/
// Export CommonJS
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
module.exports = blankshield;
} else {
exports.blankshield = blankshield;
}
}
// Register with AMD
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
define('blankshield', [], function() {
return blankshield;
});
}
// export default blankshield function
root.blankshield = blankshield;
}(this));
| ;(function(root) {
'use strict';
var blankshield = function(ele) {
addEvent(ele, 'click', function(e) {
var href, usedModifier, child;
href = e.target.getAttribute('href');
if (!href) return;
usedModifier = (e.ctrlKey || e.shiftKey || e.metaKey);
if (!usedModifier && e.target.getAttribute('target') !== '_blank') {
return;
}
child = window.open(href);
child.opener = null;
e.preventDefault();
return false;
});
};
function addEvent(target, type, listener) {
if (target.addEventListener) {
target.addEventListener(type, listener, false);
} else if (target.attachEvent) {
target.attachEvent('on' + type, listener);
} else {
target['on' + type] = listener;
}
}
/**
* Export for various environments.
*/
// Export CommonJS
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
module.exports = blankshield;
} else {
exports.blankshield = blankshield;
}
}
// Register with AMD
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
define('blankshield', [], function() {
return blankshield;
});
}
// export default blankshield function
root.blankshield = blankshield;
}(this));
|
Check config and show what required options not exists | /*
* grunt-browser-extension
* https://github.com/addmitriev/grunt-browser-extension
*
* Copyright (c) 2015 Aleksey Dmitriev
* Licensed under the MIT license.
*/
'use strict';
var util = require('util');
var path = require('path');
var fs = require('fs-extra');
module.exports = function (grunt) {
var BrowserExtension = require('./lib/browser-extension')(grunt);
grunt.registerMultiTask('browser_extension', 'Grunt plugin to create any browser website extension', function () {
if(this.target){
var options = this.options();
var required_options = [];
for(var required_options_id in required_options){
if(required_options_id){
var required_option = required_options[required_options_id];
if(!util.isString(options[required_option])){
grunt.fail.fatal("Please set up all required options. All options must be string value! You have not setted " + required_option);
}
}
}
var pluginRoot = path.join(path.dirname(fs.realpathSync(__filename)), '../');
var bExt = new BrowserExtension(pluginRoot, options, this.target, grunt);
bExt.copyUserFiles();
grunt.verbose.ok('User files copied');
bExt.copyBrowserFiles();
grunt.verbose.ok('Extension files copied');
bExt.buildNsisIE();
grunt.verbose.ok('NSIS installer for IE builded');
bExt.build();
grunt.verbose.ok('Extensions builded');
}
});
};
| /*
* grunt-browser-extension
* https://github.com/addmitriev/grunt-browser-extension
*
* Copyright (c) 2015 Aleksey Dmitriev
* Licensed under the MIT license.
*/
'use strict';
var util = require('util');
var path = require('path');
var fs = require('fs-extra');
module.exports = function (grunt) {
var BrowserExtension = require('./lib/browser-extension')(grunt);
grunt.registerMultiTask('browser_extension', 'Grunt plugin to create any browser website extension', function () {
if(this.target){
var options = this.options();
var required_options = [];
for(var required_options_id in required_options){
if(required_options_id){
var required_option = required_options[required_options_id];
if(!options[required_option]){
grunt.fail.fatal("Please set up all required options. All options must be string value! You have not setted " + required_option);
}
}
}
var pluginRoot = path.join(path.dirname(fs.realpathSync(__filename)), '../');
var bExt = new BrowserExtension(pluginRoot, options, this.target, grunt);
bExt.copyUserFiles();
grunt.verbose.ok('User files copied');
bExt.copyBrowserFiles();
grunt.verbose.ok('Extension files copied');
bExt.buildNsisIE();
grunt.verbose.ok('NSIS installer for IE builded');
bExt.build();
grunt.verbose.ok('Extensions builded');
}
});
};
|
Update to work with new Geostore API | define([
'Class', 'uri', 'bluebird',
'map/services/DataService'
], function(Class, UriTemplate, Promise, ds) {
'use strict';
var GET_REQUEST_ID = 'GeostoreService:get',
SAVE_REQUEST_ID = 'GeostoreService:save';
var URL = window.gfw.config.GFW_API_HOST + '/geostore/{id}';
var GeostoreService = Class.extend({
get: function(id) {
return new Promise(function(resolve, reject) {
var url = new UriTemplate(URL).fillFromObject({id: id});
ds.define(GET_REQUEST_ID, {
cache: {type: 'persist', duration: 1, unit: 'days'},
url: url,
type: 'GET'
});
var requestConfig = {
resourceId: GET_REQUEST_ID,
success: resolve
};
ds.request(requestConfig);
});
},
save: function(geojson) {
return new Promise(function(resolve, reject) {
var url = new UriTemplate(URL).fillFromObject({});
ds.define(SAVE_REQUEST_ID, {
url: url,
type: 'POST'
});
var requestConfig = {
resourceId: SAVE_REQUEST_ID,
data: JSON.stringify(geojson),
success: function(response) {
resolve(response.id);
},
error: reject
};
ds.request(requestConfig);
});
}
});
return new GeostoreService();
});
| define([
'Class', 'uri', 'bluebird',
'map/services/DataService'
], function(Class, UriTemplate, Promise, ds) {
'use strict';
var GET_REQUEST_ID = 'GeostoreService:get',
SAVE_REQUEST_ID = 'GeostoreService:save';
var URL = window.gfw.config.GFW_API_HOST + '/geostore/{id}';
var GeostoreService = Class.extend({
get: function(id) {
return new Promise(function(resolve, reject) {
var url = new UriTemplate(URL).fillFromObject({id: id});
ds.define(GET_REQUEST_ID, {
cache: {type: 'persist', duration: 1, unit: 'days'},
url: url,
type: 'GET'
});
var requestConfig = {
resourceId: GET_REQUEST_ID,
success: resolve
};
ds.request(requestConfig);
});
},
save: function(geojson) {
return new Promise(function(resolve, reject) {
var url = new UriTemplate(URL).fillFromObject({});
ds.define(SAVE_REQUEST_ID, {
url: url,
type: 'POST'
});
var params = { geojson: geojson };
var requestConfig = {
resourceId: SAVE_REQUEST_ID,
data: JSON.stringify(params),
success: function(response) {
resolve(response.id);
},
error: reject
};
ds.request(requestConfig);
});
}
});
return new GeostoreService();
});
|
Fix init of local recognizer | import unittest
import os
from speech_recognition import WavFile
from mycroft.client.speech.listener import RecognizerLoop
__author__ = 'seanfitz'
DATA_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), "data")
class LocalRecognizerTest(unittest.TestCase):
def setUp(self):
rl = RecognizerLoop()
self.recognizer = RecognizerLoop.create_mycroft_recognizer(rl,
16000,
"en-us")
def testRecognizerWrapper(self):
source = WavFile(os.path.join(DATA_DIR, "hey_mycroft.wav"))
with source as audio:
hyp = self.recognizer.transcribe(audio.stream.read())
assert self.recognizer.key_phrase in hyp.hypstr.lower()
source = WavFile(os.path.join(DATA_DIR, "mycroft.wav"))
with source as audio:
hyp = self.recognizer.transcribe(audio.stream.read())
assert self.recognizer.key_phrase in hyp.hypstr.lower()
def testRecognitionInLongerUtterance(self):
source = WavFile(os.path.join(DATA_DIR, "weather_mycroft.wav"))
with source as audio:
hyp = self.recognizer.transcribe(audio.stream.read())
assert self.recognizer.key_phrase in hyp.hypstr.lower()
| import unittest
import os
from speech_recognition import WavFile
from mycroft.client.speech.listener import RecognizerLoop
__author__ = 'seanfitz'
DATA_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), "data")
class LocalRecognizerTest(unittest.TestCase):
def setUp(self):
self.recognizer = RecognizerLoop.create_mycroft_recognizer(16000,
"en-us")
def testRecognizerWrapper(self):
source = WavFile(os.path.join(DATA_DIR, "hey_mycroft.wav"))
with source as audio:
hyp = self.recognizer.transcribe(audio.stream.read())
assert self.recognizer.key_phrase in hyp.hypstr.lower()
source = WavFile(os.path.join(DATA_DIR, "mycroft.wav"))
with source as audio:
hyp = self.recognizer.transcribe(audio.stream.read())
assert self.recognizer.key_phrase in hyp.hypstr.lower()
def testRecognitionInLongerUtterance(self):
source = WavFile(os.path.join(DATA_DIR, "weather_mycroft.wav"))
with source as audio:
hyp = self.recognizer.transcribe(audio.stream.read())
assert self.recognizer.key_phrase in hyp.hypstr.lower()
|
Fix bug: must specify the port number. | from os.path import dirname
from restclients.dao_implementation.mock import get_mockdata_url
from restclients.dao_implementation.live import get_con_pool, get_live_url
import logging
from myuw_mobile.logger.logback import log_info
class File(object):
"""
This implementation returns mock/static content.
Use this DAO with this configuration:
RESTCLIENTS_HFS_DAO_CLASS = 'myuw_mobile.restclients.dao_implementation.hfs.File'
"""
def getURL(self, url, headers):
"""
Return the url for accessing the mock data in local file
:param url:
in the format of "hfs/servlet/hfservices?sn=<student number>"
"""
return get_mockdata_url("hfs", "file", url, headers,
dir_base=dirname(__file__))
class Live(object):
"""
This DAO provides real data.
Access is restricted to localhost.
"""
logger = logging.getLogger('myuw_mobile.restclients.dao_implementation.hfs.Live')
pool = None
def getURL(self, url, headers):
"""
Return the absolute url for accessing live data
:param url:
in the format of "hfs/servlet/hfservices?sn=<student number>"
"""
host = 'http://localhost:80/'
if Live.pool is None:
Live.pool = get_con_pool(host, None, None,
socket_timeout=5.0,
max_pool_size=5)
log_info(Live.logger, Live.pool)
return get_live_url (Live.pool, 'GET',
host, url, headers=headers)
| from os.path import dirname
from restclients.dao_implementation.mock import get_mockdata_url
from restclients.dao_implementation.live import get_con_pool, get_live_url
class File(object):
"""
This implementation returns mock/static content.
Use this DAO with this configuration:
RESTCLIENTS_HFS_DAO_CLASS = 'myuw_mobile.restclients.dao_implementation.hfs.File'
"""
def getURL(self, url, headers):
"""
Return the url for accessing the mock data in local file
:param url:
in the format of "hfs/servlet/hfservices?sn=<student number>"
"""
return get_mockdata_url("hfs", "file", url, headers,
dir_base=dirname(__file__))
class Live(object):
"""
This DAO provides real data.
Access is restricted to localhost.
"""
pool = None
def getURL(self, url, headers):
"""
Return the absolute url for accessing live data
:param url:
in the format of "hfs/servlet/hfservices?sn=<student number>"
"""
host = 'http://localhost/'
if Live.pool == None:
Live.pool = get_con_pool(host, None, None)
return get_live_url (Live.pool, 'GET',
host, url, headers=headers)
|
Fix: Fix bug in register aftter login | from copy import deepcopy
from django.conf import settings
from django.contrib.auth import login
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from users.models import User
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = (
'username',
'email',
'gravatar',
'password',
'password_repeat',
settings.DRF_URL_FIELD_NAME,
)
extra_kwargs = {
settings.DRF_URL_FIELD_NAME: {
"view_name": "users:user-detail",
},
}
password = serializers.CharField(
write_only=True,
required=True,
allow_blank=False,
min_length=6,
max_length=32,
)
password_repeat = serializers.CharField(
write_only=True,
required=True,
allow_blank=False,
min_length=6,
max_length=32,
)
def create(self, validated_data):
if validated_data['password'] != validated_data['password']:
raise ValidationError(
detail={
"password_repeat": "Tow password doesn't match",
}
)
validated_data.pop('password_repeat')
password = validated_data.pop('password')
user = super(UserSerializer, self).create(
validated_data,
)
user.set_password(password)
user.save()
login(
self.context['request'],
user=user,
backend=settings.AUTHENTICATION_BACKENDS[0],
)
return user
| from django.conf import settings
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from users.models import User
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = (
'username',
'email',
'gravatar',
'password',
'password_repeat',
settings.DRF_URL_FIELD_NAME,
)
extra_kwargs = {
settings.DRF_URL_FIELD_NAME: {
"view_name": "users:user-detail",
},
}
password = serializers.CharField(
write_only=True,
required=True,
allow_blank=False,
min_length=6,
max_length=32,
)
password_repeat = serializers.CharField(
write_only=True,
required=True,
allow_blank=False,
min_length=6,
max_length=32,
)
def create(self, validated_data):
if validated_data['password'] != validated_data['password']:
raise ValidationError(
detail={
"password_repeat": "Tow password doesn't match",
}
)
validated_data.pop('password_repeat')
password = validated_data.pop('password')
user = super(UserSerializer, self).create(
validated_data,
)
user.set_password(password)
user.save()
return user
|
Update view dengan template header faq | <?php get_header('faq'); ?>
<!-- start:main content -->
<div class="container landing-content-faq">
<section id="content">
<!-- start:content -->
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<!-- start:content main -->
<?php
foreach($faq as $f){
?>
<div class="faq-content">
<div class="faq-content-question">
<h3><em><?php echo $f->question; ?></em></h3>
</div>
<div class="faq-content-answer">
<?php echo $f->answer; ?>
</div>
</div>
<?php
}
?>
<!-- end:content main -->
</div>
</div>
<!-- end:content -->
</section>
</div>
<!-- end:main content -->
<?php get_footer('private'); ?> | <?php get_header('private'); ?>
<!-- start:main content -->
<div class="container landing-content-faq">
<section id="content">
<!-- start:content -->
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<!-- start:content main -->
<?php
foreach($faq as $f){
?>
<div class="faq-content">
<div class="faq-content-question">
<h3><em><?php echo $f->question; ?></em></h3>
</div>
<div class="faq-content-answer">
<?php echo $f->answer; ?>
</div>
</div>
<?php
}
?>
<!-- end:content main -->
</div>
</div>
<!-- end:content -->
</section>
</div>
<!-- end:main content -->
<?php get_footer('private'); ?> |
Fix the parallel env variable test to reset the env correctly | from numba.np.ufunc.parallel import get_thread_count
from os import environ as env
from numba.core import config
import unittest
class TestParallelEnvVariable(unittest.TestCase):
"""
Tests environment variables related to the underlying "parallel"
functions for npyufuncs.
"""
_numba_parallel_test_ = False
def test_num_threads_variable(self):
"""
Tests the NUMBA_NUM_THREADS env variable behaves as expected.
"""
key = 'NUMBA_NUM_THREADS'
current = str(getattr(env, key, config.NUMBA_DEFAULT_NUM_THREADS))
threads = "3154"
env[key] = threads
try:
config.reload_config()
except RuntimeError as e:
# This test should fail if threads have already been launched
self.assertIn("Cannot set NUMBA_NUM_THREADS", e.args[0])
else:
self.assertEqual(threads, str(get_thread_count()))
self.assertEqual(threads, str(config.NUMBA_NUM_THREADS))
finally:
# reset the env variable/set to default. Should not fail even if
# threads are launched because the value is the same.
env[key] = current
config.reload_config()
if __name__ == '__main__':
unittest.main()
| from numba.np.ufunc.parallel import get_thread_count
from os import environ as env
from numba.core import config
import unittest
class TestParallelEnvVariable(unittest.TestCase):
"""
Tests environment variables related to the underlying "parallel"
functions for npyufuncs.
"""
_numba_parallel_test_ = False
def test_num_threads_variable(self):
"""
Tests the NUMBA_NUM_THREADS env variable behaves as expected.
"""
key = 'NUMBA_NUM_THREADS'
current = str(getattr(env, key, config.NUMBA_DEFAULT_NUM_THREADS))
threads = "3154"
env[key] = threads
try:
config.reload_config()
except RuntimeError as e:
# This test should fail if threads have already been launched
self.assertIn("Cannot set NUMBA_NUM_THREADS", e.args[0])
else:
try:
self.assertEqual(threads, str(get_thread_count()))
self.assertEqual(threads, str(config.NUMBA_NUM_THREADS))
finally:
# reset the env variable/set to default
env[key] = current
config.reload_config()
if __name__ == '__main__':
unittest.main()
|
Add GitHub icon. Remove articles link | import React from 'react'
import { Link } from 'gatsby'
import MeImg from '../images/me.jpg'
import { MenuIcon } from './icons/Menu'
import { GitHubIcon } from './icons/GitHub'
const Nav = ({ onClick }) => {
return (
<div className="flex items-center border-b justify-between py-8 text-gray-800">
<Link to="/" aria-label="link to home page">
<div className="flex flex-row items-center">
<img
className="block w-10 h-10 mr-3 rounded-full"
src={MeImg}
alt="pic of david"
/>
<span className="text-xl font-extrabold">David Valles</span>
</div>
</Link>
<MenuIcon
className="w-6 h-6 sm:hidden"
onClick={() => onClick((prevState) => !prevState)}
/>
<div className="hidden sm:flex space-x-4">
<Link
to="/projects"
className="font-bold text-gray-500 text-normal hover:underline"
>
Projects
</Link>
<a href="https://github.com/dtjv">
<GitHubIcon className="w-6 h-6 ml-3 text-color-800 hover:text-blue-400" />
</a>
</div>
</div>
)
}
export { Nav }
| import React from 'react'
import { Link } from 'gatsby'
import MeImg from '../images/me.jpg'
import { MenuIcon } from './icons/Menu'
const Nav = ({ onClick }) => {
return (
<div className="flex items-center justify-between py-8 text-gray-800">
<Link to="/" aria-label="link to home page">
<div className="flex flex-row items-center">
<img
className="block w-10 h-10 mr-3 rounded-full"
src={MeImg}
alt="pic of david"
/>
<span className="text-xl font-extrabold">David Valles</span>
</div>
</Link>
<MenuIcon
className="w-6 h-6 sm:hidden"
onClick={() => onClick((prevState) => !prevState)}
/>
<div className="hidden sm:block space-x-4">
<Link
to="/articles"
className="font-bold text-gray-500 text-normal hover:underline"
>
Articles
</Link>
<Link
to="/projects"
className="font-bold text-gray-500 text-normal hover:underline"
>
Projects
</Link>
</div>
</div>
)
}
export { Nav }
|
Revert ":bug: fixes datastore class name in example import"
This reverts commit 1cf3a99a267679a7d422e2fb53c625e1e7f0a81f. |
const { App, Util } = require('jovo-framework');
const { GoogleAssistant } = require('jovo-platform-googleassistant');
const { Alexa } = require('jovo-platform-alexa');
const { JovoDebugger } = require('jovo-plugin-debugger');
const { FileDb } = require('jovo-db-filedb');
const { DynamoDb } = require('jovo-db-dynamodb');
const { DataStoreDb } = require('jovo-db-datastore');
const { MySQL } = require('jovo-db-mysql');
const app = new App();
Util.consoleLog();
app.use(
new GoogleAssistant(),
new Alexa(),
new JovoDebugger(),
new FileDb(),
new MySQL({
tableName: 'users',
connection: {
host : 'localhost',
user : 'root',
password : '',
database : 'test'
}
})
);
app.setHandler({
async LAUNCH() {
console.log(this.$user.$data.lastVisit);
if (!this.$user.$data.lastVisit) {
this.$user.$data.lastVisit = new Date().toISOString();
this.tell('Hello new friend');
} else {
this.tell('Last visit: ' + this.$user.$data.lastVisit);
}
},
async DeleteIntent() {
await this.$user.delete();
this.tell('User Deleted');
}
});
module.exports.app = app;
|
const { App, Util } = require('jovo-framework');
const { GoogleAssistant } = require('jovo-platform-googleassistant');
const { Alexa } = require('jovo-platform-alexa');
const { JovoDebugger } = require('jovo-plugin-debugger');
const { FileDb } = require('jovo-db-filedb');
const { DynamoDb } = require('jovo-db-dynamodb');
const { DatastoreDb } = require('jovo-db-datastore');
const { MySQL } = require('jovo-db-mysql');
const app = new App();
Util.consoleLog();
app.use(
new GoogleAssistant(),
new Alexa(),
new JovoDebugger(),
// new FileDb(),
// new MySQL({
// tableName: 'users',
// connection: {
// host : 'localhost',
// user : 'root',
// password : '',
// database : 'test'
// }
// })
new DatastoreDb()
);
app.setHandler({
async LAUNCH() {
console.log(this.$user.$data.lastVisit);
if (!this.$user.$data.lastVisit) {
this.$user.$data.lastVisit = new Date().toISOString();
this.tell('Hello new friend');
} else {
this.tell('Last visit: ' + this.$user.$data.lastVisit);
}
},
async DeleteIntent() {
await this.$user.delete();
this.tell('User Deleted');
}
});
module.exports.app = app;
|
Allow https in body url | /*global describe:true it:true */
'use strict';
var app = require('../app').app
var request = require('supertest')
describe('The router', function() {
describe('index page', function() {
it('should return HTTP 200 OK', function(done) {
request(app)
.get('/')
.set('Accept', 'text/html')
.expect('Content-Type', 'text/html; charset=utf-8')
.expect(200, done)
})
it("should contain the current app's URL in the <body> tag", function(done) {
request(app)
.get('/')
.set('Accept', 'text/html')
.expect('Content-Type', 'text/html; charset=utf-8')
.expect(200, /<body data-url="https?:\/\/[^/]+">/, done)
})
})
describe('404 page', function() {
it('should return HTTP 404 Not Found', function(done) {
request(app)
.get('/404')
.set('Accept', 'text/html')
.expect('Content-Type', 'text/html; charset=utf-8')
.expect(404, done)
})
it('should contain the URL not found in the page', function(done) {
request(app)
.get('/404')
.set('Accept', 'text/html')
.expect(404, /<div id="url-requested">\/404<\/div>/, done)
})
})
})
| /*global describe:true it:true */
'use strict';
var app = require('../app').app
var request = require('supertest')
describe('The router', function() {
describe('index page', function() {
it('should return HTTP 200 OK', function(done) {
request(app)
.get('/')
.set('Accept', 'text/html')
.expect('Content-Type', 'text/html; charset=utf-8')
.expect(200, done)
})
it("should contain the current app's URL in the <body> tag", function(done) {
request(app)
.get('/')
.set('Accept', 'text/html')
.expect('Content-Type', 'text/html; charset=utf-8')
.expect(200, /<body data-url="http:\/\/[^/]+">/, done)
})
})
describe('404 page', function() {
it('should return HTTP 404 Not Found', function(done) {
request(app)
.get('/404')
.set('Accept', 'text/html')
.expect('Content-Type', 'text/html; charset=utf-8')
.expect(404, done)
})
it('should contain the URL not found in the page', function(done) {
request(app)
.get('/404')
.set('Accept', 'text/html')
.expect(404, /<div id="url-requested">\/404<\/div>/, done)
})
})
})
|
Enable bignumber support by default
Configure mathjs so it uses bignums by default (with a somewhat excessive precision). | 'use strict';
var math = require('mathjs'),
async = require('async');
var errors;
exports.name = 'Math';
exports.version = '0.1.2';
exports.description = 'Do mathematics!';
exports.configuration = {
enabled: false
};
exports.commands = {
calc: {
handler: calc,
defaults: {},
params: ['expression'],
description: 'The mathematical expression to calculate.'
}
};
exports.begin = function begin(_, config) {
errors = config.errors;
math.config({
number: 'bignumber',
precision: 4096
});
};
function calc(payload, callback) {
async.series([function () {
var args = payload.$arguments;
args.unshift(payload.expression);
var realExpression = args.join(' ');
try {
var result = math.eval(realExpression);
var message = [
'Expression: ',
realExpression.trim(),
'\nResult: ',
result,
''
];
callback(null, message.join('\n'));
} catch (e) {
var error = [
'Unable to evaluate expression ' + realExpression,
errors[Math.floor(Math.random() * errors.length)],
''
];
callback(null, error.join('\n'));
}
}
]);
}
| 'use strict';
var math = require('mathjs'),
async = require('async');
var errors;
exports.name = 'Math';
exports.version = '0.1.2';
exports.description = 'Do mathematics!';
exports.configuration = {
enabled: false
};
exports.commands = {
calc: {
handler: calc,
defaults: {},
params: ['expression'],
description: 'The mathematical expression to calculate.'
}
};
exports.begin = function begin(_, config) {
errors = config.errors;
};
function calc(payload, callback) {
async.series([function () {
var args = payload.$arguments;
args.unshift(payload.expression);
var realExpression = args.join(' ');
try {
var result = math.eval(realExpression);
var message = [
'Expression: ',
realExpression.trim(),
'\nResult: ',
result,
''
];
callback(null, message.join('\n'));
} catch (e) {
var error = [
'Unable to evaluate expression ' + realExpression,
errors[Math.floor(Math.random() * errors.length)],
''
];
callback(null, error.join('\n'));
}
}
]);
}
|
Fix bug global leaks, `;` to `,` | (function (tree) {
tree.Extend = function Extend(elements, index) {
this.selector = new(tree.Selector)(elements);
this.index = index;
};
tree.Extend.prototype.eval = function Extend_eval(env) {
var selfSelectors = findSelfSelectors(env.selectors),
targetValue = this.selector.elements[0].value;
env.frames.forEach(function(frame) {
frame.rulesets().forEach(function(rule) {
rule.selectors.forEach(function(selector) {
selector.elements.forEach(function(element, idx) {
if (element.value === targetValue) {
selfSelectors.forEach(function(_selector) {
rule.selectors.push(new tree.Selector(
selector.elements
.slice(0, idx)
.concat(_selector.elements)
.concat(selector.elements.slice(idx + 1))
));
});
}
});
});
});
});
return this;
};
function findSelfSelectors(selectors) {
var ret = [];
(function loop(elem, i) {
if (selectors[i] && selectors[i].length) {
selectors[i].forEach(function(s) {
loop(s.elements.concat(elem), i + 1);
});
}
else {
ret.push({ elements: elem });
}
})([], 0);
return ret;
}
})(require('../tree'));
| (function (tree) {
tree.Extend = function Extend(elements, index) {
this.selector = new(tree.Selector)(elements);
this.index = index;
};
tree.Extend.prototype.eval = function Extend_eval(env) {
var selfSelectors = findSelfSelectors(env.selectors);
targetValue = this.selector.elements[0].value;
env.frames.forEach(function(frame) {
frame.rulesets().forEach(function(rule) {
rule.selectors.forEach(function(selector) {
selector.elements.forEach(function(element, idx) {
if (element.value === targetValue) {
selfSelectors.forEach(function(_selector) {
rule.selectors.push(new tree.Selector(
selector.elements
.slice(0, idx)
.concat(_selector.elements)
.concat(selector.elements.slice(idx + 1))
));
});
}
});
});
});
});
return this;
};
function findSelfSelectors(selectors) {
var ret = [];
(function loop(elem, i) {
if (selectors[i] && selectors[i].length) {
selectors[i].forEach(function(s) {
loop(s.elements.concat(elem), i + 1);
});
}
else {
ret.push({ elements: elem });
}
})([], 0);
return ret;
}
})(require('../tree'));
|
docs: Fix example of services for IAM Policies
See also: PSOBAT-1482 | """Construct an IAM Policy from templates.
Examples:
pipeline.json:
{
"services": {
"dynamodb": [
"another_app"
],
"lambda": true,
"s3": true
}
}
"""
import json
import logging
from ..utils import get_template, get_env_credential
LOG = logging.getLogger(__name__)
def construct_policy(app='coreforrest',
env='dev',
group='forrest',
region='us-east-1',
pipeline_settings=None):
"""Assemble IAM Policy for _app_.
Args:
app (str): Name of Spinnaker Application.
pipeline_settings (dict): Settings from *pipeline.json*.
Returns:
str: Custom IAM Policy for _app_.
"""
LOG.info('Create custom IAM Policy for %s.', app)
services = pipeline_settings['services']
LOG.debug('Found requested services: %s', services)
credential = get_env_credential(env=env)
account_number = credential['accountId']
statements = []
for service, value in services.items():
if isinstance(value, (bool, str)):
items = [value]
else:
items = value
statement = json.loads(get_template('iam/{0}.json.j2'.format(service),
account_number=account_number,
app=app,
env=env,
group=group,
region=region,
items=items))
statements.append(statement)
policy_json = get_template('iam/wrapper.json.j2',
statements=json.dumps(statements))
return policy_json
| """Construct an IAM Policy from templates.
Examples:
pipeline.json:
{
"services": {
"dynamodb": [
"another_app"
]
"lambda": true,
"s3": true
}
}
"""
import json
import logging
from ..utils import get_template, get_env_credential
LOG = logging.getLogger(__name__)
def construct_policy(app='coreforrest',
env='dev',
group='forrest',
region='us-east-1',
pipeline_settings=None):
"""Assemble IAM Policy for _app_.
Args:
app (str): Name of Spinnaker Application.
pipeline_settings (dict): Settings from *pipeline.json*.
Returns:
str: Custom IAM Policy for _app_.
"""
LOG.info('Create custom IAM Policy for %s.', app)
services = pipeline_settings['services']
LOG.debug('Found requested services: %s', services)
credential = get_env_credential(env=env)
account_number = credential['accountId']
statements = []
for service, value in services.items():
if isinstance(value, (bool, str)):
items = [value]
else:
items = value
statement = json.loads(get_template('iam/{0}.json.j2'.format(service),
account_number=account_number,
app=app,
env=env,
group=group,
region=region,
items=items))
statements.append(statement)
policy_json = get_template('iam/wrapper.json.j2',
statements=json.dumps(statements))
return policy_json
|
Make find_versions return a namedtuple as documented | import collections
import git
import version_info.exceptions
__all__ = (
'get_git_version',
'find_versions',
)
VersionSpec = collections.namedtuple('VersionSpec', ('name', 'tag', 'commit'))
def get_git_version(path):
repo = git.Repo(path)
head_commit = repo.head.ref.commit
for tag in repo.tags:
if tag.commit == head_commit:
return tag.name, head_commit.hexsha
return None, head_commit.hexsha
GET_VERSION_MAPPING = {
'git': get_git_version,
}
def find_versions(repo_list):
"""
Passing a list of tuples that consist of:
('reference_name', 'git', '/full/path/to/repo')
Where:
* reference_name can be anything and it will be yielded back in name
* second element is the VCS type; for a list of supported VCS's see
README.rst
You receive a list of namedtuples:
[
(name='reference_name', tag='1.0', commit='fb666d55d3')
]
:param repo_list: list of tuples as specified
:return: list of namedtuples
"""
for name, vcs_type, path in repo_list:
vcs_type_normalized = vcs_type.lower()
try:
version_func = GET_VERSION_MAPPING[vcs_type_normalized]
except KeyError as exc:
raise version_info.exceptions.VCSNotSupported(exc.args[0])
yield VersionSpec(name, *version_func(path))
| import git
import version_info.exceptions
__all__ = (
'get_git_version',
'find_versions',
)
def get_git_version(path):
repo = git.Repo(path)
head_commit = repo.head.ref.commit
for tag in repo.tags:
if tag.commit == head_commit:
return tag.name, head_commit.hexsha
return None, head_commit.hexsha
GET_VERSION_MAPPING = {
'git': get_git_version,
}
def find_versions(repo_list):
"""
Passing a list of tuples that consist of:
('reference_name', 'git', '/full/path/to/repo')
Where:
* reference_name can be anything and it will be yielded back in name
* second element is the VCS type; for a list of supported VCS's see
README.rst
You receive a list of namedtuples:
[
(name='reference_name', tag='1.0', commit='fb666d55d3')
]
:param repo_list: list of tuples as specified
:return: list of namedtuples
"""
for name, vcs_type, path in repo_list:
vcs_type_normalized = vcs_type.lower()
try:
version_func = GET_VERSION_MAPPING[vcs_type_normalized]
except KeyError as exc:
raise version_info.exceptions.VCSNotSupported(exc.args[0])
yield (name,) + version_func(path)
|
Fix bug in ipay config sample | <?php
return array(
//-------------------------------
// Timezone for insert dates in database
// If you want IPay not set timezone, just leave it empty
//--------------------------------
'timezone' => 'Asia/Tehran',
//--------------------------------
// Database configuration
//--------------------------------
'database' => array(
'host' => '127.0.0.1',
'dbname' => '',
'username' => '',
'password' => '',
'create' => true // For first time you must set this to true for create tables in database
),
//--------------------------------
// Zarinpal gateway
//--------------------------------
'zarinpal' => array(
'merchant-id' => 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
'type' => 'zarin-gate', // Types: [zarin-gate || normal]
'callback-url' => 'http://www.example.org/result',
'server' => 'germany', // Servers: [germany || iran]
'email' => '[email protected]',
'mobile' => '09xxxxxxxxx',
'description' => 'description',
),
//--------------------------------
// Mellat gateway
//--------------------------------
'mellat' => array(
'username' => '',
'password' => '',
'terminalId' => 0000000,
'callback-url' => 'http://www.example.org/result'
)
);
| <?php
return array(
//-------------------------------
// Timezone for insert dates in database
// If you want IPay not set timezone, just leave it empty
//--------------------------------
'timezone' => 'Asia/Tehran',
//--------------------------------
// Database configuration
//--------------------------------
'database-poolticket' => array(
'host' => '127.0.0.1',
'dbname' => '',
'username' => '',
'password' => '',
'create' => true // For first time you must set this to true for create tables in database
),
//--------------------------------
// Zarinpal gateway
//--------------------------------
'zarinpal' => array(
'merchant-id' => 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
'type' => 'zarin-gate', // Types: [zarin-gate || normal]
'callback-url' => 'http://www.example.org/result',
'server' => 'germany', // Servers: [germany || iran]
'email' => '[email protected]',
'mobile' => '09xxxxxxxxx',
'description' => 'description',
),
//--------------------------------
// Mellat gateway
//--------------------------------
'mellat' => array(
'username' => '',
'password' => '',
'terminalId' => 0000000,
'callback-url' => 'http://www.example.org/result'
)
);
|
Remove IF EXISTS from fix_fee_product_index | # -*- coding: utf-8 -*-
# Generated by Django 1.11.22 on 2019-10-31 16:33
from __future__ import unicode_literals
from django.db import migrations, OperationalError, ProgrammingError
def fix_fee_product_index(apps, schema_editor):
table_name = 'cfpb.ratechecker_fee'
index_name = 'idx_16977_product_id'
try:
schema_editor.execute(
'DROP INDEX idx_16977_product_id;'
'ALTER TABLE cfpb.ratechecker_fee '
'DROP CONSTRAINT IF EXISTS idx_16977_product_id;'
'ALTER TABLE cfpb.ratechecker_fee '
'ADD CONSTRAINT idx_16977_product_id '
'UNIQUE (product_id, state_id, lender, single_family, condo, coop);'
)
except (ProgrammingError, OperationalError):
pass
class Migration(migrations.Migration):
dependencies = [
('ratechecker', '0001_initial'),
]
operations = [
migrations.RunPython(fix_fee_product_index),
migrations.AlterUniqueTogether(
name='fee',
unique_together=set([]),
),
migrations.RemoveField(
model_name='fee',
name='plan',
),
migrations.DeleteModel(
name='Fee',
),
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.11.22 on 2019-10-31 16:33
from __future__ import unicode_literals
from django.db import migrations, OperationalError, ProgrammingError
def fix_fee_product_index(apps, schema_editor):
try:
schema_editor.execute(
'DROP INDEX IF EXISTS idx_16977_product_id;'
)
except (ProgrammingError, OperationalError):
pass
try:
schema_editor.execute(
'ALTER TABLE IF EXISTS cfpb.ratechecker_fee '
'DROP CONSTRAINT IF EXISTS idx_16977_product_id;'
)
except (ProgrammingError, OperationalError):
pass
try:
schema_editor.execute(
'ALTER TABLE IF EXISTS cfpb.ratechecker_fee '
'ADD CONSTRAINT idx_16977_product_id '
'UNIQUE (product_id, state_id, lender, single_family, condo, coop);'
)
except (ProgrammingError, OperationalError):
pass
class Migration(migrations.Migration):
dependencies = [
('ratechecker', '0001_initial'),
]
operations = [
migrations.RunPython(fix_fee_product_index),
migrations.AlterUniqueTogether(
name='fee',
unique_together=set([]),
),
migrations.RemoveField(
model_name='fee',
name='plan',
),
migrations.DeleteModel(
name='Fee',
),
]
|
SPRO-37: Fix M2 Admin store selection refresh loop
Make sure adding a card in Stored Payment Methods works as well |
define(
['underscore'],
function(_) {
'use strict';
var code = 'subscribe_pro';
return {
getCode: function () {
return code;
},
getVaultCode: function () {
return this.getConfig().vaultCode;
},
isActive: function () {
return this.getConfig().isActive;
},
isThreeDSActive: function () {
return this.getConfig().isThreeDSActive;
},
getBrowserSize: function () {
return this.getConfig().browserSize;
},
getAcceptHeader: function () {
return this.getConfig().acceptHeader;
},
getEnvironmentKey: function () {
return this.getConfig().environmentKey;
},
hasVerification: function () {
return this.getConfig().hasVerification;
},
getIcons: function () {
return this.getConfig().icons;
},
getAvailableCardTypes: function () {
return this.getConfig().availableCardTypes;
},
getCcTypesMapper: function () {
return this.getConfig().ccTypesMapper;
},
getCvvImageUrl: function () {
return this.getConfig().cvvImageUrl;
},
getConfig: function () {
var config = {};
if (window['checkoutConfig'] != undefined) { // frontend checkout
config = window.checkoutConfig.payment[code];
} else if (window['subscribeProPaymentConfig'] != undefined && window.order) { // backend checkout
config = window.subscribeProPaymentConfig[window.order.storeId];
} else if (window['subscribeProPaymentConfig'] != undefined ) { // ading a card in My Stored Methods
config = window.subscribeProPaymentConfig;
}
return config;
}
};
}
);
|
define(
['underscore'],
function(_) {
'use strict';
var code = 'subscribe_pro';
return {
getCode: function () {
return code;
},
getVaultCode: function () {
return this.getConfig().vaultCode;
},
isActive: function () {
return this.getConfig().isActive;
},
isThreeDSActive: function () {
return this.getConfig().isThreeDSActive;
},
getBrowserSize: function () {
return this.getConfig().browserSize;
},
getAcceptHeader: function () {
return this.getConfig().acceptHeader;
},
getEnvironmentKey: function () {
return this.getConfig().environmentKey;
},
hasVerification: function () {
return this.getConfig().hasVerification;
},
getIcons: function () {
return this.getConfig().icons;
},
getAvailableCardTypes: function () {
return this.getConfig().availableCardTypes;
},
getCcTypesMapper: function () {
return this.getConfig().ccTypesMapper;
},
getCvvImageUrl: function () {
return this.getConfig().cvvImageUrl;
},
getConfig: function () {
var config = {};
let storeId = window.order.storeId;
if (window['checkoutConfig'] != undefined) {
config = window.checkoutConfig.payment[code];
} else if (window['subscribeProPaymentConfig'] != undefined) {
config = window.subscribeProPaymentConfig[storeId];
}
return config;
}
};
}
);
|
Add date to response body | var os = require( "os" );
var throng = require( "throng" );
var connections = require( "./shared/connections" );
var utils = require( "./shared/utils" );
var logger = connections.logger( [ "Pi-System-RPC-Service" ] );
var run = function () {
logger.log( "Starting Pi-System-RPC-Service" );
var broker = connections.jackrabbit();
var handleMessage = function ( message, ack ) {
utils.readCPUTemperature( function ( err, data ) {
if ( err ) {
logger.log( "Error with: 'utils.readCPUTemperature'" );
process.exit();
}
ack( JSON.stringify( {
date: new Date(),
cpu_temp_c: data.celsius,
cpu_temp_f: data.fahrenheit
} ) );
} );
};
var serve = function () {
logger.log( "Broker ready" );
broker.handle( "system.get", handleMessage );
};
var create = function () {
logger.log( "Broker connected" );
broker.create( "system.get", { prefetch: 5 }, serve );
};
process.once( "uncaughtException", function ( err ) {
logger.log( "Stopping Pi-System-RPC-Service" );
logger.log( err );
process.exit();
} );
broker.once( "connected", create );
};
throng( run, {
workers: os.cpus().length,
lifetime: Infinity
} );
| var os = require( "os" );
var throng = require( "throng" );
var connections = require( "./shared/connections" );
var utils = require( "./shared/utils" );
var logger = connections.logger( [ "Pi-System-RPC-Service" ] );
var run = function () {
logger.log( "Starting Pi-System-RPC-Service" );
var broker = connections.jackrabbit();
var handleMessage = function ( message, ack ) {
utils.readCPUTemperature( function ( err, data ) {
if ( err ) {
logger.log( "Error with: 'utils.readCPUTemperature'" );
process.exit();
}
ack( JSON.stringify( {
cpu_temp_c: data.celsius,
cpu_temp_f: data.fahrenheit
} ) );
} );
};
var serve = function () {
logger.log( "Broker ready" );
broker.handle( "system.get", handleMessage );
};
var create = function () {
logger.log( "Broker connected" );
broker.create( "system.get", { prefetch: 5 }, serve );
};
process.once( "uncaughtException", function ( err ) {
logger.log( "Stopping Pi-System-RPC-Service" );
logger.log( err );
process.exit();
} );
broker.once( "connected", create );
};
throng( run, {
workers: os.cpus().length,
lifetime: Infinity
} );
|
Enable native async/await in Node 8. | "use strict";
module.exports = function (babel) {
const t = babel.types;
return {
visitor: {
Function: {
exit: function (path) {
const node = path.node;
if (! node.async) {
return;
}
// The original function becomes a non-async function that
// returns a Promise.
node.async = false;
const innerFn = t.functionExpression(
null, // anonymous
node.params.slice(0),
node.body
);
if (this.opts.useNativeAsyncAwait) {
// The inner function called by Promise.asyncApply should be
// async if we have native async/await support.
innerFn.async = true;
}
// Calling the async function with Promise.asyncApply is
// important to ensure that the part before the first await
// expression runs synchronously in its own Fiber, even when
// there is native support for async/await.
node.body = t.blockStatement([
t.expressionStatement(t.stringLiteral("use strict")),
t.returnStatement(
t.callExpression(
t.memberExpression(
t.identifier("Promise"),
t.identifier("asyncApply"),
false
), [
innerFn,
t.thisExpression(),
t.identifier("arguments")
]
)
)
]);
}
},
AwaitExpression: function (path) {
if (this.opts.useNativeAsyncAwait) {
// No need to transform await expressions if we have native
// support for them.
return;
}
const node = path.node;
path.replaceWith(t.callExpression(
t.memberExpression(
t.identifier("Promise"),
t.identifier(node.all ? "awaitAll" : "await"),
false
),
[node.argument]
));
}
}
};
};
| module.exports = function (babel) {
var t = babel.types;
return {
visitor: {
Function: function (path) {
var node = path.node;
if (! node.async) {
return;
}
node.async = false;
node.body = t.blockStatement([
t.expressionStatement(t.stringLiteral("use strict")),
t.returnStatement(
t.callExpression(
t.memberExpression(
t.identifier("Promise"),
t.identifier("asyncApply"),
false
),
[
t.functionExpression(
null, // anonymous
node.params.slice(0),
node.body
),
t.thisExpression(),
t.identifier("arguments")
]
)
)
]);
},
AwaitExpression: function (path) {
var node = path.node;
path.replaceWith(t.callExpression(
t.memberExpression(
t.identifier("Promise"),
t.identifier(node.all ? "awaitAll" : "await"),
false
),
[node.argument]
));
}
}
};
};
|
Remove bare except in unnecessary try block
From a comment by @gasman on #1684:
> It appears the try/catch in ImageEmbedHandler was added here: 74b9f43
>
> Since the rest of the commit doesn't deal with images at all, and the
> commit makes it clear that the corresponding change to
> MediaEmbedHandler was intended to preserve the existing 'fail
> silently' behaviour in the light of the new exceptions added for media
> embeds - I think this try/catch is redundant. `Format.image_to_html`
> does its own catching of image IO errors, which seems to be
> sufficiently robust (if it wasn't, we'd be seeing errors on front-end
> page rendering), so I think this try/catch can reasonably be deleted.
https://github.com/torchbox/wagtail/pull/1684#issuecomment-140695060 | from wagtail.wagtailimages.models import get_image_model
from wagtail.wagtailimages.formats import get_image_format
class ImageEmbedHandler(object):
"""
ImageEmbedHandler will be invoked whenever we encounter an element in HTML content
with an attribute of data-embedtype="image". The resulting element in the database
representation will be:
<embed embedtype="image" id="42" format="thumb" alt="some custom alt text">
"""
@staticmethod
def get_db_attributes(tag):
"""
Given a tag that we've identified as an image embed (because it has a
data-embedtype="image" attribute), return a dict of the attributes we should
have on the resulting <embed> element.
"""
return {
'id': tag['data-id'],
'format': tag['data-format'],
'alt': tag['data-alt'],
}
@staticmethod
def expand_db_attributes(attrs, for_editor):
"""
Given a dict of attributes from the <embed> tag, return the real HTML
representation.
"""
Image = get_image_model()
try:
image = Image.objects.get(id=attrs['id'])
except Image.DoesNotExist:
return "<img>"
format = get_image_format(attrs['format'])
if for_editor:
return format.image_to_editor_html(image, attrs['alt'])
else:
return format.image_to_html(image, attrs['alt'])
| from wagtail.wagtailimages.models import get_image_model
from wagtail.wagtailimages.formats import get_image_format
class ImageEmbedHandler(object):
"""
ImageEmbedHandler will be invoked whenever we encounter an element in HTML content
with an attribute of data-embedtype="image". The resulting element in the database
representation will be:
<embed embedtype="image" id="42" format="thumb" alt="some custom alt text">
"""
@staticmethod
def get_db_attributes(tag):
"""
Given a tag that we've identified as an image embed (because it has a
data-embedtype="image" attribute), return a dict of the attributes we should
have on the resulting <embed> element.
"""
return {
'id': tag['data-id'],
'format': tag['data-format'],
'alt': tag['data-alt'],
}
@staticmethod
def expand_db_attributes(attrs, for_editor):
"""
Given a dict of attributes from the <embed> tag, return the real HTML
representation.
"""
Image = get_image_model()
try:
image = Image.objects.get(id=attrs['id'])
format = get_image_format(attrs['format'])
if for_editor:
try:
return format.image_to_editor_html(image, attrs['alt'])
except:
return ''
else:
return format.image_to_html(image, attrs['alt'])
except Image.DoesNotExist:
return "<img>"
|
Use tracer in debug IR interpretation mode | # -*- coding: utf-8 -*-
"""
IR interpreter. Run a series of translation phases on a numba function, and
interpreter the IR with the arguments.
"""
from __future__ import print_function, division, absolute_import
from numba2 import typeof, jit
from numba2.compiler.frontend import translate, interpret
from numba2.pipeline import environment, phase
from pykit.ir import interp, tracing
#===------------------------------------------------------------------===
# Helpers
#===------------------------------------------------------------------===
def expect(nb_func, phase, args, expected, handlers=None, debug=False):
result = interpret(nb_func, phase, args, handlers, debug)
assert result == expected, "Got %s, expected %s" % (result, expected)
def interpret(nb_func, phase, args, handlers=None, debug=False):
# Translate numba function
argtypes = [typeof(arg) for arg in args]
env = environment.fresh_env(nb_func, argtypes)
f, env = phase(nb_func, env)
if debug:
print("---------------- Interpreting function %s ----------------" % (
f.name,))
print(f)
print("----------------------- End of %s ------------------------" % (
f.name,))
tracer = tracing.Tracer()
else:
tracer = tracing.DummyTracer()
# Interpreter function
env.setdefault('interp.handlers', {}).update(handlers or {})
return interp.run(f, env, args=args, tracer=tracer) | # -*- coding: utf-8 -*-
"""
IR interpreter. Run a series of translation phases on a numba function, and
interpreter the IR with the arguments.
"""
from __future__ import print_function, division, absolute_import
from numba2 import typeof, jit
from numba2.compiler.frontend import translate, interpret
from numba2.pipeline import environment, phase
from pykit.ir import interp
#===------------------------------------------------------------------===
# Helpers
#===------------------------------------------------------------------===
def expect(nb_func, phase, args, expected, handlers=None, debug=False):
result = interpret(nb_func, phase, args, handlers, debug)
assert result == expected, "Got %s, expected %s" % (result, expected)
def interpret(nb_func, phase, args, handlers=None, debug=False):
# Translate numba function
argtypes = [typeof(arg) for arg in args]
env = environment.fresh_env(nb_func, argtypes)
f, env = phase(nb_func, env)
if debug:
print("---------------- Interpreting function %s ----------------" % (
f.name,))
print(f)
print("----------------------- End of %s ------------------------" % (
f.name,))
# Interpreter function
env.setdefault('interp.handlers', {}).update(handlers or {})
return interp.run(f, env, args=args) |
Update doc: changing command isn't a thing | // Description:
// Returns a randomly selected url to something in an s3 bucket.
//
// Dependencies:
// aws-sdk
// random.js
// sprintf
//
// Configuration:
// AWS_ACCESS_KEY_ID
// AWS_ACCESS_SECRET
// WOO_BUCKET
//
// Commands:
// hubot woo - Returns a randomly selected url to something in an s3 bucket.
//
// Author:
// apechimp
var Random = require('random-js');
var sprintf = require('sprintf');
var s3 = require('./s3');
var mt = Random.engines.mt19937();
mt.seed(Date.now());
var command_regex = /^woo\b/i;
var bucket = process.env.WOO_BUCKET;
module.exports = function (robot) {
robot.respond(command_regex, function (msg) {
s3.listObjects(
{ Bucket: bucket },
function (err, data) {
if(err) {
console.error(err);
msg.send('the gods of woo are displeased.');
}
else if(!data.Contents.length) {
msg.send('no woo pics :\'(');
}
else {
msg.send(
sprintf(
'https://s3.amazonaws.com/%s/%s',
bucket,
Random.pick(mt, data.Contents).Key
)
);
}
}
);
});
};
| // Description:
// Returns a randomly selected url to something in an s3 bucket.
//
// Dependencies:
// aws-sdk
// random.js
// sprintf
//
// Configuration:
// AWS_ACCESS_KEY_ID
// AWS_ACCESS_SECRET
// WOO_BUCKET
// WOO_COMMAND (defaults to woo)
//
// Commands:
// hubot woo - Returns a randomly selected url to something in an s3 bucket.
//
// Author:
// apechimp
var Random = require('random-js');
var sprintf = require('sprintf');
var s3 = require('./s3');
var mt = Random.engines.mt19937();
mt.seed(Date.now());
var command_regex = /^woo\b/i;
var bucket = process.env.WOO_BUCKET;
module.exports = function (robot) {
robot.respond(command_regex, function (msg) {
s3.listObjects(
{ Bucket: bucket },
function (err, data) {
if(err) {
console.error(err);
msg.send('the gods of woo are displeased.');
}
else if(!data.Contents.length) {
msg.send('no woo pics :\'(');
}
else {
msg.send(
sprintf(
'https://s3.amazonaws.com/%s/%s',
bucket,
Random.pick(mt, data.Contents).Key
)
);
}
}
);
});
};
|
Fix for de-serialization.
Using vanilla django-money, when one did the following:
./manage.py dumpdata
the values were saved properly, i.e:
{
'amount': '12',
'amount_currency': 'USD',
}
however, after the de-serialization:
./manage.py loaddata [fixtures]
the currencies were omitted.
i have no idea (yet) how to write a test that proves that.. :/ | # coding=utf-8
import json
from decimal import Decimal
from django.core.serializers.python import Deserializer as PythonDeserializer
from django.core.serializers.json import Serializer as JSONSerializer
from django.core.serializers.python import _get_model
from django.utils import six
from djmoney.models.fields import MoneyField
from moneyed import Money
Serializer = JSONSerializer
def Deserializer(stream_or_string, **options):
"""
Deserialize a stream or string of JSON data.
"""
if not isinstance(stream_or_string, (bytes, six.string_types)):
stream_or_string = stream_or_string.read()
if isinstance(stream_or_string, bytes):
stream_or_string = stream_or_string.decode('utf-8')
try:
obj_list = []
for obj in json.loads(stream_or_string):
money_fields = {}
fields = {}
Model = _get_model(obj["model"])
for (field_name, field_value) in obj['fields'].iteritems():
field = Model._meta.get_field(field_name)
if isinstance(field, MoneyField):
money_fields[field_name] = Money(field_value, obj['fields']['%s_currency' % field_name])
else:
fields[field_name] = field_value
obj['fields'] = fields
for obj in PythonDeserializer([obj], **options):
for field, value in money_fields.items():
setattr(obj.object, field, value)
yield obj
except GeneratorExit:
raise
| # coding=utf-8
import json
from decimal import Decimal
from django.core.serializers.python import Deserializer as PythonDeserializer
from django.core.serializers.json import Serializer as JSONSerializer
from django.core.serializers.python import _get_model
from django.utils import six
from djmoney.models.fields import MoneyField
Serializer = JSONSerializer
def Deserializer(stream_or_string, **options):
"""
Deserialize a stream or string of JSON data.
"""
if not isinstance(stream_or_string, (bytes, six.string_types)):
stream_or_string = stream_or_string.read()
if isinstance(stream_or_string, bytes):
stream_or_string = stream_or_string.decode('utf-8')
try:
obj_list = []
for obj in json.loads(stream_or_string):
money_fields = {}
fields = {}
Model = _get_model(obj["model"])
for (field_name, field_value) in obj['fields'].iteritems():
field = Model._meta.get_field(field_name)
if isinstance(field, MoneyField):
money_fields[field_name] = Decimal(
field_value.split(" ")[0])
else:
fields[field_name] = field_value
obj['fields'] = fields
for obj in PythonDeserializer([obj], **options):
for field, value in money_fields.items():
setattr(obj.object, field, value)
yield obj
except GeneratorExit:
raise
|
Add wheel as a requirement | #!/usr/bin/env python
from setuptools import setup, find_packages
__version__ = '0.50.1'
with open("README.md", "r") as fh:
long_description = fh.read()
setup(name='lcapy',
version=__version__,
author='Michael Hayes',
author_email='[email protected]',
description='Symbolic linear circuit analysis',
long_description = long_description,
long_description_content_type="text/markdown",
url='https://github.com/mph-/lcapy',
download_url='https://github.com/mph-/lcapy',
install_requires=['matplotlib',
'scipy',
'numpy',
'sympy',
'networkx',
'setuptools',
'wheel'
],
packages=find_packages(exclude=['demo']),
entry_points={
'console_scripts': [
'schtex=lcapy.scripts.schtex:main',
],
},
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: GNU Lesser General Public License v2 or later (LGPLv2+)",
"Operating System :: OS Independent",
],
)
| #!/usr/bin/env python
from setuptools import setup, find_packages
__version__ = '0.50.1'
with open("README.md", "r") as fh:
long_description = fh.read()
setup(name='lcapy',
version=__version__,
author='Michael Hayes',
author_email='[email protected]',
description='Symbolic linear circuit analysis',
long_description = long_description,
long_description_content_type="text/markdown",
url='https://github.com/mph-/lcapy',
download_url='https://github.com/mph-/lcapy',
install_requires=['matplotlib',
'scipy',
'numpy',
'sympy',
'networkx',
'setuptools'
],
packages=find_packages(exclude=['demo']),
entry_points={
'console_scripts': [
'schtex=lcapy.scripts.schtex:main',
],
},
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: GNU Lesser General Public License v2 or later (LGPLv2+)",
"Operating System :: OS Independent",
],
)
|
Check for array before forEach | var config = require('../settings.json'),
log4js = require('log4js').getLogger(),
fs = require('fs');
module.exports = {
logger: {
debug: (log) => {
log4js.debug(log);
},
error: (log) => {
log4js.error(log);
}
},
// steps -> how many times to call
// speed -> the FPS
preciseSetTimeout: (steps, speed, oninstance, oncomplete) => {
var count = 0,
start = new Date().getTime();
function loop() {
if (count++ >= steps) {
oncomplete()
} else {
oninstance(count);
var diff = (new Date().getTime() - start) - (count * speed);
setTimeout(loop, (speed - diff));
}
}
setTimeout(loop, speed);
},
quatInverse: (q) => {
var len = Math.sqrt(q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w);
return {
w: q.w / len,
x: -q.x / len,
y: -q.y / len,
z: -q.z / len
};
},
clearTimers: (animation) => {
var noop = () => {};
Object.keys(animation).forEach((key) => {
if (key == 'TIMERS' && Array.isArray(animation[key])) {
animation[key].forEach((timer) => {
clearTimeout(timer);
});
}
animation[key] = noop;
});
animation = null;
}
}
| var config = require('../settings.json'),
log4js = require('log4js').getLogger(),
fs = require('fs');
module.exports = {
logger: {
debug: (log) => {
log4js.debug(log);
},
error: (log) => {
log4js.error(log);
}
},
// steps -> how many times to call
// speed -> the FPS
preciseSetTimeout: (steps, speed, oninstance, oncomplete) => {
var count = 0,
start = new Date().getTime();
function loop() {
if (count++ >= steps) {
oncomplete()
} else {
oninstance(count);
var diff = (new Date().getTime() - start) - (count * speed);
setTimeout(loop, (speed - diff));
}
}
setTimeout(loop, speed);
},
quatInverse: (q) => {
var len = Math.sqrt(q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w);
return {
w: q.w / len,
x: -q.x / len,
y: -q.y / len,
z: -q.z / len
};
},
clearTimers: (animation) => {
var noop = () => {};
Object.keys(animation).forEach((key) => {
if (key == 'TIMERS') {
animation[key].forEach((timer) => {
clearTimeout(timer);
});
}
animation[key] = noop;
});
animation = null;
}
}
|
Use long display name on profile | from django.contrib.auth.decorators import login_required
from django.core.exceptions import ObjectDoesNotExist
from django.http import Http404, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from judge.forms import ProfileForm
from judge.models import Profile
def user(request, user):
try:
user = Profile.objects.get(user__username=user)
return render_to_response('user.html', {'user': user, 'title': 'User %s' % user.long_display_name()},
context_instance=RequestContext(request))
except ObjectDoesNotExist:
return Http404()
@login_required
def edit_profile(request):
profile = Profile.objects.get(user=request.user)
if request.method == 'POST':
form = ProfileForm(request.POST, instance=profile)
if form.is_valid():
form.save()
return HttpResponseRedirect(request.path)
else:
form = ProfileForm(instance=profile)
return render_to_response('edit_profile.html', {'form': form, 'title': 'Edit profile'},
context_instance=RequestContext(request))
def users(request):
return render_to_response('users.html', {'users': Profile.objects.all(), 'title': 'Users'},
context_instance=RequestContext(request))
| from django.contrib.auth.decorators import login_required
from django.core.exceptions import ObjectDoesNotExist
from django.http import Http404, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from judge.forms import ProfileForm
from judge.models import Profile
def user(request, user):
try:
user = Profile.objects.get(user__username=user)
return render_to_response('user.html', {'user': user, 'title': 'User %s' % user.display_name()},
context_instance=RequestContext(request))
except ObjectDoesNotExist:
return Http404()
@login_required
def edit_profile(request):
profile = Profile.objects.get(user=request.user)
if request.method == 'POST':
form = ProfileForm(request.POST, instance=profile)
if form.is_valid():
form.save()
return HttpResponseRedirect(request.path)
else:
form = ProfileForm(instance=profile)
return render_to_response('edit_profile.html', {'form': form, 'title': 'Edit profile'},
context_instance=RequestContext(request))
def users(request):
return render_to_response('users.html', {'users': Profile.objects.all(), 'title': 'Users'},
context_instance=RequestContext(request))
|
Use appropriate package for mxchip_az3166 | # Copyright 2014-present PlatformIO <[email protected]>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from platformio.managers.platform import PlatformBase
class Ststm32Platform(PlatformBase):
def configure_default_packages(self, variables, targets):
board = variables.get("board")
if "mbed" in variables.get("pioframework",
[]) or board == "mxchip_az3166":
self.packages['toolchain-gccarmnoneeabi'][
'version'] = ">=1.60301.0"
if board == "mxchip_az3166":
self.frameworks['arduino'][
'package'] = "framework-arduinostm32mxchip"
self.frameworks['arduino'][
'script'] = "builder/frameworks/arduino/mxchip.py"
self.packages['tool-openocd']['type'] = "uploader"
return PlatformBase.configure_default_packages(self, variables,
targets)
| # Copyright 2014-present PlatformIO <[email protected]>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from platformio.managers.platform import PlatformBase
class Ststm32Platform(PlatformBase):
def configure_default_packages(self, variables, targets):
board = variables.get("board")
if "mbed" in variables.get("pioframework",
[]) or board == "mxchip_az3166":
self.packages['toolchain-gccarmnoneeabi'][
'version'] = ">=1.60301.0"
if board == "mxchip_az3166":
self.frameworks['arduino'][
'script'] = "builder/frameworks/arduino/mxchip.py"
self.packages['tool-openocd']['type'] = "uploader"
return PlatformBase.configure_default_packages(self, variables,
targets)
|
Build may or may not exist | <?php
/**
* Copyright 2015-2018 ppy Pty. Ltd.
*
* This file is part of osu!web. osu!web is distributed with the hope of
* attracting more community contributions to the core ecosystem of osu!.
*
* osu!web is free software: you can redistribute it and/or modify
* it under the terms of the Affero GNU General Public License version 3
* as published by the Free Software Foundation.
*
* osu!web is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with osu!web. If not, see <http://www.gnu.org/licenses/>.
*/
namespace App\Models;
class UserClient extends Model
{
const CREATED_AT = 'timestamp';
protected $table = 'osu_user_security';
protected $dates = ['timestamp'];
public $timestamps = false;
public function build()
{
return $this->belongsTo(Build::class, 'osu_md5', 'hash');
}
public function isLatest()
{
if ($this->build === null) {
return false;
}
$latestBuild = Build::select('build_id')
->where([
'test_build' => false,
'stream_id' => $this->build->stream_id,
])->last();
return $this->build->getKey() === optional($latestBuild)->getKey();
}
}
| <?php
/**
* Copyright 2015-2018 ppy Pty. Ltd.
*
* This file is part of osu!web. osu!web is distributed with the hope of
* attracting more community contributions to the core ecosystem of osu!.
*
* osu!web is free software: you can redistribute it and/or modify
* it under the terms of the Affero GNU General Public License version 3
* as published by the Free Software Foundation.
*
* osu!web is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with osu!web. If not, see <http://www.gnu.org/licenses/>.
*/
namespace App\Models;
class UserClient extends Model
{
const CREATED_AT = 'timestamp';
protected $table = 'osu_user_security';
protected $dates = ['timestamp'];
public $timestamps = false;
public function build()
{
return $this->belongsTo(Build::class, 'osu_md5', 'hash');
}
public function isLatest()
{
if ($this->build === null) {
return false;
}
$latestBuildId = Build::select('build_id')
->where([
'test_build' => false,
'stream_id' => $this->build->stream_id,
])->last()
->getKey();
return $this->build->getKey() === $latestBuildId;
}
}
|
Fix slug on many method calls | <?php
namespace Rudolf\Component\Helpers\Navigation;
class MenuItem
{
private $data;
public function __construct(array $data)
{
$this->data = $data;
}
public function setId($id)
{
$this->data['id'] = $id;
}
public function getId()
{
return isset($this->data['id']) ? $this->data['id'] : null;
}
public function getParentId()
{
return $this->data['parent_id'];
}
public function getTitle()
{
return $this->data['title'];
}
public function getSlug()
{
$slug = $this->data['slug'];
switch ($this->data['item_type']) {
case 'absolute':
// $newItems[$key];
break;
case 'app':
default:
$slug = DIR.'/'.$slug;
break;
}
return $slug;
}
public function getCaption()
{
return $this->data['caption'];
}
public function getType()
{
return $this->data['menu_type'];
}
public function getPosition()
{
return $this->data['position'];
}
public function getIco()
{
return isset($this->data['ico']) ? $this->data['ico'] : null;
}
}
| <?php
namespace Rudolf\Component\Helpers\Navigation;
class MenuItem
{
private $data;
public function __construct(array $data)
{
$this->data = $data;
}
public function setId($id)
{
$this->data['id'] = $id;
}
public function getId()
{
return isset($this->data['id']) ? $this->data['id'] : null;
}
public function getParentId()
{
return $this->data['parent_id'];
}
public function getTitle()
{
return $this->data['title'];
}
public function getSlug()
{
switch ($this->data['item_type']) {
case 'absolute':
// $newItems[$key];
break;
case 'app':
default:
$this->data['slug'] = DIR.'/'.$this->data['slug'];
break;
}
return $this->data['slug'];
}
public function getCaption()
{
return $this->data['caption'];
}
public function getType()
{
return $this->data['menu_type'];
}
public function getPosition()
{
return $this->data['position'];
}
public function getIco()
{
return isset($this->data['ico']) ? $this->data['ico'] : null;
}
}
|
Fix redirect bug for new users | var server = require('./server'),
models = require('./models');
/*
* GET home page.
*/
exports.index = function(req, res) {
if (req.isAuthenticated()) {
res.redirect('/lobby');
return;
}
res.render('index', {
title: 'SwiftCODE',
error: req.flash('error')
});
};
/*
* GET lobby page.
*/
exports.lobby = function(req, res) {
res.render('lobby', {
title: 'Lobby',
exercises: server.getApp().getExercises()
});
};
/*
* GET help page.
*/
exports.help = function(req, res) {
res.render('help', {
title: 'Help'
});
};
/*
* POST signup page.
*/
exports.signup = function(req, res) {
var username = req.body.username,
password = req.body.password;
if (username && password) {
models.User.findOne({ username: username }, function(err, user) {
// Create a new user if none exists
if (!user) {
user = new models.User({ username: username, password: password });
user.save(function(err, saved) {
req.logIn(user, function(err) {
return res.redirect('/lobby');
});
});
} else {
req.flash('error', 'That username is already in use.');
res.redirect('/');
}
});
}
};
| var server = require('./server'),
models = require('./models');
/*
* GET home page.
*/
exports.index = function(req, res) {
res.render('index', {
title: 'SwiftCODE',
error: req.flash('error')
});
};
/*
* GET lobby page.
*/
exports.lobby = function(req, res) {
res.render('lobby', {
title: 'Lobby',
exercises: server.getApp().getExercises()
});
};
/*
* GET help page.
*/
exports.help = function(req, res) {
res.render('help', {
title: 'Help'
});
};
/*
* POST signup page.
*/
exports.signup = function(req, res) {
var username = req.body.username,
password = req.body.password;
if (username && password) {
models.User.findOne({ username: username }, function(err, user) {
// Create a new user if none exists
if (!user) {
user = new models.User({ username: username, password: password });
user.save();
req.logIn(user, function(err) {
res.redirect('/lobby');
});
} else {
req.flash('error', 'That username is already in use.');
res.redirect('/');
}
});
}
};
|
Fix canvas not restored properly | package it.sephiroth.android.library.tooltip;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Rect;
import android.graphics.Region;
import android.graphics.drawable.Drawable;
import android.view.View;
import java.util.List;
public class TooltipBackgroundDrawable extends Drawable {
private int mBackgroundColor;
private List<View> mHighlightViews;
private Drawable mHighlightDrawable;
public TooltipBackgroundDrawable(Context context, TooltipManager.Builder builder) {
mBackgroundColor = context.getResources().getColor(builder.backgroundColorResId);
mHighlightViews = builder.highlightViews;
if (builder.highlightDrawableResId > 0) {
mHighlightDrawable = context.getResources().getDrawable(builder.highlightDrawableResId);
}
}
@Override
public void draw(Canvas canvas) {
canvas.save();
if (mHighlightViews != null) {
Rect highlightRect = new Rect();
Rect vRect = new Rect();
for(View v: mHighlightViews) {
v.getGlobalVisibleRect(vRect);
highlightRect.union(vRect);
}
if (mHighlightDrawable != null) {
mHighlightDrawable.setBounds(highlightRect);
mHighlightDrawable.draw(canvas);
}
canvas.clipRect(highlightRect, Region.Op.DIFFERENCE);
}
canvas.drawColor(mBackgroundColor);
canvas.restore();
}
@Override
public void setAlpha(int alpha) {
}
@Override
public void setColorFilter(ColorFilter cf) {
}
@Override
public int getOpacity() {
return 0;
}
}
| package it.sephiroth.android.library.tooltip;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Rect;
import android.graphics.Region;
import android.graphics.drawable.Drawable;
import android.view.View;
import java.util.List;
public class TooltipBackgroundDrawable extends Drawable {
private int mBackgroundColor;
private List<View> mHighlightViews;
private Drawable mHighlightDrawable;
public TooltipBackgroundDrawable(Context context, TooltipManager.Builder builder) {
mBackgroundColor = context.getResources().getColor(builder.backgroundColorResId);
mHighlightViews = builder.highlightViews;
if (builder.highlightDrawableResId > 0) {
mHighlightDrawable = context.getResources().getDrawable(builder.highlightDrawableResId);
}
}
@Override
public void draw(Canvas canvas) {
if (mHighlightViews != null) {
Rect highlightRect = new Rect();
Rect vRect = new Rect();
for(View v: mHighlightViews) {
v.getGlobalVisibleRect(vRect);
highlightRect.union(vRect);
}
if (mHighlightDrawable != null) {
mHighlightDrawable.setBounds(highlightRect);
mHighlightDrawable.draw(canvas);
}
canvas.clipRect(highlightRect, Region.Op.DIFFERENCE);
}
canvas.drawColor(mBackgroundColor);
}
@Override
public void setAlpha(int alpha) {
}
@Override
public void setColorFilter(ColorFilter cf) {
}
@Override
public int getOpacity() {
return 0;
}
}
|
Change cancel_invited_user client to not return anything. |
from notifications_python_client.base import BaseAPIClient
from app.notify_client.models import User
class InviteApiClient(BaseAPIClient):
def __init__(self, base_url=None, client_id=None, secret=None):
super(self.__class__, self).__init__(base_url=base_url or 'base_url',
client_id=client_id or 'client_id',
secret=secret or 'secret')
def init_app(self, app):
self.base_url = app.config['API_HOST_NAME']
self.client_id = app.config['ADMIN_CLIENT_USER_NAME']
self.secret = app.config['ADMIN_CLIENT_SECRET']
def create_invite(self, invite_from_id, service_id, email_address, permissions):
data = {
'service': str(service_id),
'email_address': email_address,
'from_user': invite_from_id,
'permissions': permissions
}
resp = self.post(url='/service/{}/invite'.format(service_id), data=data)
return resp['data']
def get_invites_for_service(self, service_id):
endpoint = '/service/{}/invite'.format(service_id)
resp = self.get(endpoint)
return [User(data) for data in resp['data']]
def cancel_invited_user(self, service_id, invited_user_id):
data = {'status': 'cancelled'}
self.post(url='/service/{0}/invite/{1}'.format(service_id, invited_user_id),
data=data)
|
from notifications_python_client.base import BaseAPIClient
from app.notify_client.models import User
class InviteApiClient(BaseAPIClient):
def __init__(self, base_url=None, client_id=None, secret=None):
super(self.__class__, self).__init__(base_url=base_url or 'base_url',
client_id=client_id or 'client_id',
secret=secret or 'secret')
def init_app(self, app):
self.base_url = app.config['API_HOST_NAME']
self.client_id = app.config['ADMIN_CLIENT_USER_NAME']
self.secret = app.config['ADMIN_CLIENT_SECRET']
def create_invite(self, invite_from_id, service_id, email_address, permissions):
data = {
'service': str(service_id),
'email_address': email_address,
'from_user': invite_from_id,
'permissions': permissions
}
resp = self.post(url='/service/{}/invite'.format(service_id), data=data)
return resp['data']
def get_invites_for_service(self, service_id):
endpoint = '/service/{}/invite'.format(service_id)
resp = self.get(endpoint)
return [User(data) for data in resp['data']]
def cancel_invited_user(self, service_id, invited_user_id):
data = {'status': 'cancelled'}
resp = self.post(url='/service/{0}/invite/{1}'.format(service_id, invited_user_id),
data=data)
return resp['data']
|
Update isActive when destroying the promiseMonitor | (function () {
angular.module('eyecatch.promise-monitor', []).provider('promiseMonitor', function () {
this.$get = ['$q', function ($q) {
// ReSharper disable once InconsistentNaming
function PromiseMonitor(options) {
var monitored = [];
var self = this;
// Set default options if necessary
self.options = options || {};
self.isActive = false;
var updateActive = function () {
self.isActive = monitored.length > 0;
};
self.addPromise = function (promise) {
var deferred = $q.defer();
monitored.push(deferred);
updateActive();
deferred.promise.then(function () {
monitored.splice(monitored.indexOf(deferred), 1);
updateActive();
}, function () {
monitored.splice(monitored.indexOf(deferred), 1);
updateActive();
});
// Resolve deferred when promise has completed
if (promise) {
promise.then(function (value) {
deferred.resolve(value);
return value;
}, function (value) {
deferred.reject(value);
return $q.reject(value);
});
}
return deferred;
};
self.destroy = self.cancel = function () {
// Resolve all promises
for (var i = monitored.length - 1; i >= 0; i--) {
monitored[i].resolve();
}
// Reset monitored list
monitored = [];
updateActive();
};
return self;
}
return {
create: function (options) {
return new PromiseMonitor(options);
}
};
}];
return this;
});
})();
| (function () {
angular.module('eyecatch.promise-monitor', []).provider('promiseMonitor', function () {
this.$get = ['$q', function ($q) {
// ReSharper disable once InconsistentNaming
function PromiseMonitor(options) {
var monitored = [];
var self = this;
// Set default options if necessary
self.options = options || {};
self.isActive = false;
var updateActive = function () {
self.isActive = monitored.length > 0;
};
self.addPromise = function (promise) {
var deferred = $q.defer();
monitored.push(deferred);
updateActive();
deferred.promise.then(function () {
monitored.splice(monitored.indexOf(deferred), 1);
updateActive();
}, function () {
monitored.splice(monitored.indexOf(deferred), 1);
updateActive();
});
// Resolve deferred when promise has completed
if (promise) {
promise.then(function (value) {
deferred.resolve(value);
return value;
}, function (value) {
deferred.reject(value);
return $q.reject(value);
});
}
return deferred;
};
self.destroy = self.cancel = function () {
// Resolve all promises
for (var i = monitored.length - 1; i >= 0; i--) {
monitored[i].resolve();
}
// Reset monitored list
monitored = [];
};
return self;
}
return {
create: function (options) {
return new PromiseMonitor(options);
}
};
}];
return this;
});
})();
|
Create tabular q-function with kwarg random_state | from ..learner import Learner
from ..policies import RandomPolicy
from ..value_functions import TabularQ
from ...utils import check_random_state
class Sarsa(Learner):
def __init__(self, env, policy=None, learning_rate=0.1, discount_factor=0.99,
n_episodes=1000, verbose=True, random_state=None):
super(Sarsa, self).__init__(env, n_episodes=n_episodes, verbose=verbose)
self.policy = policy
self.learning_rate = learning_rate
self.discount_factor = discount_factor
self.random_state = check_random_state(random_state)
self.policy = policy or RandomPolicy(env.actions, random_state=self.random_state)
self.qf = TabularQ(random_state=self.random_state)
###########
# Learner #
###########
def episode(self):
state = self.env.cur_state()
action = self.policy.action(state)
while not self.env.is_terminal():
reward, next_state = self.env.do_action(action)
next_action = self.policy.action(next_state)
target = reward + (self.discount_factor * self.qf[next_state, next_action])
td_error = target - self.qf[state, action]
self.qf[state, action] += self.learning_rate * td_error
state, action = next_state, next_action
| from ..learner import Learner
from ..policies import RandomPolicy
from ..value_functions import TabularQ
from ...utils import check_random_state
class Sarsa(Learner):
def __init__(self, env, policy=None, learning_rate=0.1, discount_factor=0.99,
n_episodes=1000, verbose=True, random_state=None):
super(Sarsa, self).__init__(env, n_episodes=n_episodes, verbose=verbose)
self.policy = policy
self.learning_rate = learning_rate
self.discount_factor = discount_factor
self.random_state = check_random_state(random_state)
self.policy = policy or RandomPolicy(env.actions, self.random_state)
self.qf = TabularQ(self.random_state)
###########
# Learner #
###########
def episode(self):
state = self.env.cur_state()
action = self.policy.action(state)
while not self.env.is_terminal():
reward, next_state = self.env.do_action(action)
next_action = self.policy.action(next_state)
target = reward + (self.discount_factor * self.qf[next_state, next_action])
td_error = target - self.qf[state, action]
self.qf[state, action] += self.learning_rate * td_error
state, action = next_state, next_action
|
Clock: Improve behavior on rack load | export default class EventScheduler {
constructor(audioContext) {
this.audioContext = audioContext;
this.running = false;
this.timeoutID = null;
}
start(callback) {
const TIMEOUT_DELAY = 0.05; // in seconds
const BUFFER_DEPTH = 0.3; // in seconds
const _this = this;
let startTime = null;
let bufferedUntil = null;
const timeoutFunc = function() {
if (!_this.running) {
throw new Error('Internal error: timeoutFunc called but scheduler not running');
}
const t = _this.audioContext.currentTime;
if (startTime === null) {
startTime = t;
bufferedUntil = t;
}
if (bufferedUntil < t) {
console.log('FELL BEHIND BY', t - bufferedUntil);
}
const bufferUntil = t + BUFFER_DEPTH;
callback({
begin: bufferedUntil,
end: bufferUntil,
relativeBegin: bufferedUntil - startTime,
relativeEnd: bufferUntil - startTime,
start: startTime,
});
bufferedUntil = bufferUntil;
_this.timeoutID = setTimeout(timeoutFunc, 1000*TIMEOUT_DELAY);
}
this.running = true;
_this.timeoutID = setTimeout(timeoutFunc, 0);
}
stop() {
this.running = false;
if (this.timeoutID) {
clearTimeout(this.timeoutID);
this.timeoutID = null;
}
}
}
| export default class EventScheduler {
constructor(audioContext) {
this.audioContext = audioContext;
this.running = false;
this.timeoutID = null;
}
start(callback) {
const TIMEOUT_DELAY = 0.05; // in seconds
const BUFFER_DEPTH = 0.10; // in seconds
const _this = this;
let startTime = null;
let bufferedUntil = null;
const timeoutFunc = function() {
if (!_this.running) {
throw new Error('Internal error: timeoutFunc called but scheduler not running');
}
const t = _this.audioContext.currentTime;
if (startTime === null) {
startTime = t;
bufferedUntil = t;
}
if (bufferedUntil < t) {
console.log('FELL BEHIND BY', t - bufferedUntil);
}
const bufferUntil = t + BUFFER_DEPTH;
callback({
begin: bufferedUntil,
end: bufferUntil,
relativeBegin: bufferedUntil - startTime,
relativeEnd: bufferUntil - startTime,
start: startTime,
});
bufferedUntil = bufferUntil;
_this.timeoutID = setTimeout(timeoutFunc, 1000*TIMEOUT_DELAY);
}
this.running = true;
timeoutFunc();
}
stop() {
this.running = false;
if (this.timeoutID) {
clearTimeout(this.timeoutID);
this.timeoutID = null;
}
}
}
|
Print h2 connection info when using -DkeepAlive | package au.gov.ga.geodesy;
import java.security.Permission;
import org.testng.IExecutionListener;
public class TestSuiteListener implements IExecutionListener {
@SuppressWarnings("serial")
public class ExitInterceptedException extends SecurityException {
public ExitInterceptedException() {
super("Keeping the JVM alive, so you can inspect the in-memory database at http://localhost:8082/."
+ " Connection details: jdbc:h2:./h2-test-db, username: \"\", password: \"\". Type ctrl-c to exit.");
}
}
public void onExecutionStart() {
Thread.currentThread().setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread t, Throwable x) {
if (x.getClass() == ExitInterceptedException.class) {
new Thread() {
public void run() {
try {
Thread.sleep(Long.MAX_VALUE);
} catch (InterruptedException ok) {
}
}
}.start();
}
}
});
}
public void onExecutionFinish() {
if (System.getProperty("keepAlive") != null) {
final SecurityManager securityManager = new SecurityManager() {
public void checkPermission(Permission permission) {
if (permission.getName().startsWith("exitVM.")) {
throw new ExitInterceptedException();
}
}
};
System.setSecurityManager(securityManager);
}
}
}
| package au.gov.ga.geodesy;
import java.security.Permission;
import org.testng.IExecutionListener;
public class TestSuiteListener implements IExecutionListener {
@SuppressWarnings("serial")
public class ExitInterceptedException extends SecurityException {
public ExitInterceptedException() {
super("Keeping the JVM alive, so you can inspect the in-memory database at http://localhost:8082/. Type ctrl-c to exit.");
}
}
public void onExecutionStart() {
Thread.currentThread().setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread t, Throwable x) {
if (x.getClass() == ExitInterceptedException.class) {
new Thread() {
public void run() {
try {
Thread.sleep(Long.MAX_VALUE);
} catch (InterruptedException ok) {
}
}
}.start();
}
}
});
}
public void onExecutionFinish() {
if (System.getProperty("keepAlive") != null) {
final SecurityManager securityManager = new SecurityManager() {
public void checkPermission(Permission permission) {
if (permission.getName().startsWith("exitVM.")) {
throw new ExitInterceptedException();
}
}
};
System.setSecurityManager(securityManager);
}
}
}
|
feat(shop): Update Interface to Category Index page
Update Interface to Category Index page
see #298 | @extends('layouts.admin')
@section('content')
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">
List of Categories
<div class="pull-right"><a href="{{ route('adminCategoriesCreate') }}"><button class="btn btn-xs btn-primary">Add Category</button></a></div>
</div>
<div class="panel-body">
<table class="table table-hover">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Type</th>
<th class="text-right">Actions</th>
</tr>
</thead>
<tbody>
@foreach($categories as $category)
<tr>
<td>{{ $category->id }}</td>
<td>{{ $category->name }}</td>
<td>{{ $category->type->name }}</td>
<td class="text-right">
<a href="{{ route('adminCategoriesEdit', ['id' => $category->id] ) }}"><button class="btn btn-xs btn-primary">Edit</button></a>
<a href="{{ route('adminCategoriesDelete', ['id' => $category->id] ) }}"><button class="btn btn-xs btn-primary">Delete</button></a>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
@endsection
| @extends('layouts.admin')
@section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">List of Categories</div>
<div class="panel-body">
<table class="table table-striped table-bordered table-hover" id="dataTables-example">
<thead>
<tr align="center">
<th>Category Name</th>
<th>Type</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
@foreach($categories as $category)
<tr class="odd gradeX" align="center">
<td>{{ $category->name }}</td>
<td>{{ $category->type->name }}</td>
<td class="center"><i class="fa fa-trash-o fa-fw"></i><a href="{{ route('adminCategoriesEdit', ['id' => $category->id] ) }}">Edit</a></td>
<td class="center"><i class="fa fa-pencil fa-fw"></i> <a href="{{ route('adminCategoriesDelete', ['id' => $category->id] ) }}">Delete</a></td>
</tr>
@endforeach
</tbody>
</table>
<a href="{{ route('adminCategoriesCreate') }}">Add Category</a>
</div>
</div>
</div>
</div>
</div>
@endsection
|
Fix for unescapedHtml.cmp losing rendering after empty value. | /*
* Copyright (C) 2013 salesforce.com, inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
({
render : function(cmp){
var elements=$A.util.createElementsFromMarkup(cmp.get("v.value"));
if(!elements.length){
elements=$A.renderingService.renderFacet(cmp,elements);
}
return elements;
},
rerender : function(cmp){
if (cmp.isDirty("v.value")) {
var el = cmp.getElement();
var placeholder=null;
if(el){
placeholder = document.createTextNode("");
$A.util.insertBefore(placeholder, el);
}else{
placeholder=$A.renderingService.getMarker(cmp);
}
$A.unrender(cmp);
var results = $A.render(cmp);
if(results.length){
$A.util.insertBefore(results, placeholder);
$A.afterRender(cmp);
}
}
}
})
| /*
* Copyright (C) 2013 salesforce.com, inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
({
render : function(cmp){
var elements=$A.util.createElementsFromMarkup(cmp.get("v.value"));
if(!elements.length){
$A.renderingService.renderFacet(cmp,elements);
}
return elements;
},
rerender : function(cmp){
if (cmp.isDirty("v.value")) {
var el = cmp.getElement();
var placeholder=null;
if(el){
placeholder = document.createTextNode("");
$A.util.insertBefore(placeholder, el);
}else{
placeholder=$A.renderingService.getMarker(cmp);
}
$A.unrender(cmp);
var results = $A.render(cmp);
if(results.length){
$A.util.insertBefore(results, placeholder);
$A.afterRender(cmp);
}
}
}
})
|
Check for beeing a function | var excludeMethods = [
/^constructor$/,
/^render$/,
/^component[A-Za-z]+$/
];
var displayNameReg = /^function\s+([a-zA-Z]+)/;
function isExcluded(methodName) {
return excludeMethods.some(function (reg) {
return reg.test(methodName) === false;
});
}
function bindToClass(scope, methods) {
var componentName = scope.constructor.toString().match(displayNameReg)[1];
methods = Array.isArray(methods) ? methods : [];
methods.forEach(function(methodName) {
if (methodName in scope) {
scope[methodName] = scope[methodName].bind(scope);
} else {
throw new Error('Method "' + methodName + '" does not exists in "' + componentName + '"');
}
});
// for debugging purposes only?
// if (process.env.NODE_ENV != 'production') {
if (Object.getOwnPropertyNames) {
var proto = scope.constructor.prototype;
Object.getOwnPropertyNames(proto).forEach(function(methodName) {
var original = scope[methodName];
if (typeof original === 'function' && isExcluded(methodName) && methods.indexOf(methodName) === -1) {
scope[methodName] = function () {
// test whether the scope is different
if (this !== scope) {
var e = 'Warning: Method "' + methodName + '" of "' + componentName + '" is not bound. Bad you!';
console.error(e);
}
return original.apply(scope, arguments);
};
}
});
}
// }
}
module.exports = bindToClass;
| var excludeMethods = [
/^constructor$/,
/^render$/,
/^component[A-Za-z]+$/
];
var displayNameReg = /^function\s+([a-zA-Z]+)/;
function isExcluded(methodName) {
return excludeMethods.some(function (reg) {
return reg.test(methodName) === false;
});
}
function bindToClass(scope, methods) {
var componentName = scope.constructor.toString().match(displayNameReg)[1];
methods = Array.isArray(methods) ? methods : [];
methods.forEach(function(methodName) {
if (methodName in scope) {
scope[methodName] = scope[methodName].bind(scope);
} else {
throw new Error('Method "' + methodName + '" does not exists in "' + componentName + '"');
}
});
// for debugging purposes only?
// if (process.env.NODE_ENV != 'production') {
if (Object.getOwnPropertyNames) {
var proto = scope.constructor.prototype;
Object.getOwnPropertyNames(proto).forEach(function(methodName) {
if (isExcluded(methodName) && methods.indexOf(methodName) === -1) {
var original = scope[methodName];
scope[methodName] = function () {
// test whether the scope is different
if (this !== scope) {
var e = 'Warning: Method "' + methodName + '" of "' + componentName + '" is not bound. Bad you!';
console.error(e);
}
return original.apply(scope, arguments);
};
}
});
}
// }
}
module.exports = bindToClass;
|
Fix "Uncaught exception: Error [ERR_STREAM_DESTROYED]: Cannot call write after a stream was destroyed" | 'use strict';
var bunyan = require('bunyan');
var Source = require('../node/nodes/source');
function AnalysisLogger(stream, user) {
this.logger = bunyan.createLogger({
name: 'camshaft',
streams: [{
level: 'info',
stream: stream || process.stdout
}]
});
this.user = user;
// TODO: be able to configure the event and its convenience
process.on('SIGHUP', () => this.reopenFileStreams());
}
module.exports = AnalysisLogger;
AnalysisLogger.prototype.log = function (analysis) {
var self = this;
analysis.getSortedNodes()
.forEach(function (node) {
if (node.getType() !== Source.TYPE) {
self.logger.info({
analysis: analysis.id(),
node: node.id(),
type: node.getType(),
queued: node.didQueueWork(),
username: self.user
}, 'analysis:node');
}
});
};
AnalysisLogger.prototype.logLimitsError = function (err) {
if (err) {
this.logger.info({ 'error-message': err.message, 'error-code': err.code }, 'analysis:limits_error');
}
};
AnalysisLogger.prototype.reopenFileStreams () {
this.logger.reopenFileStreams();
};
| 'use strict';
var bunyan = require('bunyan');
var Source = require('../node/nodes/source');
function AnalysisLogger(stream, user) {
this.logger = bunyan.createLogger({
name: 'camshaft',
streams: [{
level: 'info',
stream: stream || process.stdout
}]
});
this.user = user;
}
module.exports = AnalysisLogger;
AnalysisLogger.prototype.log = function (analysis) {
var self = this;
analysis.getSortedNodes()
.forEach(function (node) {
if (node.getType() !== Source.TYPE) {
self.logger.info({
analysis: analysis.id(),
node: node.id(),
type: node.getType(),
queued: node.didQueueWork(),
username: self.user
}, 'analysis:node');
}
});
};
AnalysisLogger.prototype.logLimitsError = function (err) {
if (err) {
this.logger.info({ 'error-message': err.message, 'error-code': err.code }, 'analysis:limits_error');
}
};
|
Make the py2.6 dependency conditional | import sys
from setuptools import setup
from setuptools.command.test import test as TestCommand
import pipin
install_requires = []
if sys.version_info[:2] < (2, 6):
install_requires.append('argparse')
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
import pytest
errcode = pytest.main(self.test_args)
sys.exit(errcode)
setup(
name='pipin',
version=pipin.__version__,
description='',
author='Matt Lenc',
author_email='[email protected]',
url='http://github.com/mattack108/pipin',
license='LICENSE.txt',
packages=['pipin'],
install_requires=install_requires,
tests_require=['pytest'],
cmdclass={'test': PyTest},
test_suite='pipin.tests.test_pipin',
extras_require={
'testing': ['pytest'],
},
entry_points={
'console_scripts': [
'pipin = pipin.pipin:lets_pipin',
]
},
classifiers=[
"Environment :: Console",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.3",
"Topic :: Software Development",
"Topic :: Utilities",
]
)
| import sys
from setuptools import setup
from setuptools.command.test import test as TestCommand
import pipin
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
import pytest
errcode = pytest.main(self.test_args)
sys.exit(errcode)
setup(
name='pipin',
version=pipin.__version__,
description='',
author='Matt Lenc',
author_email='[email protected]',
url='http://github.com/mattack108/pipin',
license='LICENSE.txt',
packages=['pipin'],
install_requires=['argparse'],
tests_require=['pytest'],
cmdclass={'test': PyTest},
test_suite='pipin.tests.test_pipin',
extras_require={
'testing': ['pytest'],
},
entry_points={
'console_scripts': [
'pipin = pipin.pipin:lets_pipin',
]
},
classifiers=[
"Environment :: Console",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.3",
"Topic :: Software Development",
"Topic :: Utilities",
]
)
|
Remove duplicate import. (Thanks to MechanisM) | # -*- coding: utf-8 -*-
from django.views.generic import View
from django.views.decorators.csrf import csrf_exempt
try:
from django.http import StreamingHttpResponse as HttpResponse
except ImportError:
from django.http import HttpResponse
from django.utils.decorators import method_decorator
from sse import Sse
class BaseSseView(View):
"""
This is a base class for sse streaming.
"""
def get_last_id(self):
if "HTTP_LAST_EVENT_ID" in self.request.META:
return self.request.META['HTTP_LAST_EVENT_ID']
return None
def _iterator(self):
for subiterator in self.iterator():
for bufferitem in self.sse:
yield bufferitem
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
self.sse = Sse()
self.request = request
self.args = args
self.kwargs = kwargs
response = HttpResponse(self._iterator(), content_type="text/event-stream")
response['Cache-Control'] = 'no-cache'
response['Software'] = 'django-sse'
return response
def iterator(self):
"""
This is a source of stream.
Must be use sentence ``yield`` for flush
content fon sse object to the client.
Example:
def iterator(self):
counter = 0
while True:
self.sse.add_message('foo', 'bar')
self.sse.add_message('bar', 'foo')
yield
"""
raise NotImplementedError
| # -*- coding: utf-8 -*-
from django.views.generic import View
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
try:
from django.http import StreamingHttpResponse as HttpResponse
except ImportError:
from django.http import HttpResponse
from django.utils.decorators import method_decorator
from sse import Sse
class BaseSseView(View):
"""
This is a base class for sse streaming.
"""
def get_last_id(self):
if "HTTP_LAST_EVENT_ID" in self.request.META:
return self.request.META['HTTP_LAST_EVENT_ID']
return None
def _iterator(self):
for subiterator in self.iterator():
for bufferitem in self.sse:
yield bufferitem
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
self.sse = Sse()
self.request = request
self.args = args
self.kwargs = kwargs
response = HttpResponse(self._iterator(), content_type="text/event-stream")
response['Cache-Control'] = 'no-cache'
response['Software'] = 'django-sse'
return response
def iterator(self):
"""
This is a source of stream.
Must be use sentence ``yield`` for flush
content fon sse object to the client.
Example:
def iterator(self):
counter = 0
while True:
self.sse.add_message('foo', 'bar')
self.sse.add_message('bar', 'foo')
yield
"""
raise NotImplementedError
|
Refactor the app initialization code into its own class. |
( function( mdash, $ )
{
var Dashboard = mdash.Dashboard = function() {},
proto = Dashboard.prototype;
Dashboard.VERSION = '0.5.1';
proto.init = function()
{
this.$fontSizes = $( '#fontctrl > a' );
this.$helpCtrl = $( '#helpctrl' );
this.$getStarted = $( '#getstarted' );
this.$bookmarks = $( '#bookmarks' );
this.$version = $( '#version' );
this.manager = new mdash.Manager(),
this.fontCtrl = new mdash.FontCtrl( ),
this.helpCtrl = new mdash.HelpCtrl( $helpCtrl, $getStarted, $bookmarks );
this.fontCtrl.init();
this.helpCtrl.init();
this.manager.init( this.loadBookmarks.bind( this ) );
this.showVersion();
this.loadBookmarks();
};
proto.loadBookmarks = function()
{
var _this = this;
this.leftColumn = new mdash.Column( $( '#bookmarks > .left' ) );
this.rightColumn = new mdash.Column( $( '#bookmarks > .right' ) );
manager.getSections( 'left', function( sections )
{
_this.leftColumn.sections = sections;
_this.leftColumn.render();
} );
manager.getSections( 'right', function( sections )
{
_this.rightColumn.sections = sections;
_this.rightColumn.render();
} );
};
proto.showVersion = function()
{
this.$version.html( Dashboard.VERSION );
};
} )( window.mdash, Zepto );
|
( function( mdash, $ )
{
$( document ).ready( function()
{
var manager = new mdash.Manager(),
fontCtrl = new mdash.FontCtrl( $( '#fontctrl > a' ) ),
helpCtrl = new mdash.HelpCtrl( $( '#helpctrl' ), $( '#getstarted' ), $( '#bookmarks' ) );
manager.init( function()
{
fontCtrl.init();
helpCtrl.init();
var leftColumn = new mdash.Column( $( '#bookmarks > .left' ) ),
rightColumn = new mdash.Column( $( '#bookmarks > .right' ) );
manager.getSections( 'left', function( sections )
{
leftColumn.sections = sections;
leftColumn.render();
} );
manager.getSections( 'right', function( sections )
{
rightColumn.sections = sections;
rightColumn.render();
} );
} );
} );
} )( window.mdash, Zepto );
|
Add some extra output for create and destroy.
Signed-off-by: mulhern <[email protected]> | """
Miscellaneous pool-level actions.
"""
from __future__ import print_function
from .._errors import StratisCliValueUnimplementedError
def create_pool(dbus_thing, namespace):
"""
Create a stratis pool.
"""
if namespace.force:
raise StratisCliValueUnimplementedError(
namespace.force,
"namespace.force"
)
if namespace.redundancy != 'none':
raise StratisCliValueUnimplementedError(
namespace.redundancy,
"namespace.redundancy"
)
(result, rc, message) = dbus_thing.CreatePool(
namespace.name,
namespace.device,
len(namespace.device)
)
if rc == 0:
print("New pool with object path: %s" % result)
return (rc, message)
def list_pools(dbus_thing, namespace):
"""
List all stratis pools.
:param Interface dbus_thing: the interface to the stratis manager
"""
# pylint: disable=unused-argument
(result, rc, message) = dbus_thing.ListPools()
if rc != 0:
return (rc, message)
for item in result:
print(item)
return (rc, message)
def destroy_pool(dbus_thing, namespace):
"""
Destroy a stratis pool.
"""
if namespace.force:
raise StratisCliValueUnimplementedError(
namespace.force,
"namespace.force"
)
(result, rc, message) = dbus_thing.DestroyPool(
namespace.name
)
if rc == 0:
print("Deleted pool with object path: %s" % result)
return (rc, message)
| """
Miscellaneous pool-level actions.
"""
from __future__ import print_function
from .._errors import StratisCliValueUnimplementedError
def create_pool(dbus_thing, namespace):
"""
Create a stratis pool.
"""
if namespace.force:
raise StratisCliValueUnimplementedError(
namespace.force,
"namespace.force"
)
if namespace.redundancy != 'none':
raise StratisCliValueUnimplementedError(
namespace.redundancy,
"namespace.redundancy"
)
(_, rc, message) = dbus_thing.CreatePool(
namespace.name,
namespace.device,
len(namespace.device)
)
return (rc, message)
def list_pools(dbus_thing, namespace):
"""
List all stratis pools.
:param Interface dbus_thing: the interface to the stratis manager
"""
# pylint: disable=unused-argument
(result, rc, message) = dbus_thing.ListPools()
if rc != 0:
return (rc, message)
for item in result:
print(item)
return (rc, message)
def destroy_pool(dbus_thing, namespace):
"""
Destroy a stratis pool.
"""
if namespace.force:
raise StratisCliValueUnimplementedError(
namespace.force,
"namespace.force"
)
(_, rc, message) = dbus_thing.DestroyPool(
namespace.name
)
return (rc, message)
|
Use LOG_PATH for log path and make failures more descriptive | <?php
class ObserverTest extends Ibuildings_Mage_Test_PHPUnit_ControllerTestCase
{
public function testDispatchTask()
{
$ps = explode(PHP_EOL, `ps ax | grep test_worker`);
$found = false;
foreach ($ps as $line) {
if (preg_match('/test_worker\.php/', $line)) {
$found = true;
break;
}
}
if (!$found) {
$this->fail(
'You need to have started test_worker.php from the ' .
'tests directory'
);
}
$this->assertTrue($found);
$id = uniqid();
$data = 'This is a string!';
$e = array();
$e['queue'] = 'test';
$e['task'] = array(
'id' => $id,
'payload' => $data,
'callback' => 'http://magento.development.local/index.php'
);
Mage::dispatchEvent('gearman_do_async_task', $e);
sleep(1);
$log = explode(
PHP_EOL,
file_get_contents(LOG_PATH . 'gearman_testing.log')
);
$res = preg_match(
'/' . $id . ' \- ' . $data . '/',
$log[count($log) - 2]
);
$this->assertEquals(1, $res);
}
} | <?php
class ObserverTest extends Ibuildings_Mage_Test_PHPUnit_ControllerTestCase
{
public function testDispatchTask()
{
$ps = explode(PHP_EOL, `ps ax | grep test_worker`);
$found = false;
foreach ($ps as $line) {
if (preg_match('/php test_worker\.php/', $line)) {
$found = true;
break;
}
}
$this->assertTrue($found);
$id = uniqid();
$data = 'This is a string!';
$e = array();
$e['queue'] = 'test';
$e['task'] = array(
'id' => $id,
'payload' => $data,
'callback' => 'http://magento.development.local/index.php'
);
Mage::dispatchEvent('gearman_do_async_task', $e);
sleep(1);
$log = explode(PHP_EOL, file_get_contents('./testing.log'));
$res = preg_match(
'/' . $id . ' \- ' . $data . '/',
$log[count($log) - 2]
);
$this->assertEquals(1, $res);
}
} |
Prepare to retrive info for submit to server | /**
* Created by mark on 7/1/16.
*/
/* Counter */
counter = function () {
var value = $('#textArea').val();
if (value.length == 0) {
$('#wordCount').html(0);
$('#caretPos').html(0);
$('#scrollTop').html(0);
return;
}
var regex = /\s+/gi;
var wordCount = value.trim().replace(regex, ' ').split(' ').length;
var caretPos = $('#textArea')[0].selectionStart;
var scrollTop = $('#textArea')[0].scrollTop;
$('#wordCount').html(wordCount);
$('#caretPos').html(caretPos);
$('#scrollTop').html(scrollTop);
};
$(document).ready(function () {
$('#textArea').change(counter);
$('#textArea').keydown(counter);
$('#textArea').keypress(counter);
$('#textArea').keyup(counter);
$('#textArea').blur(counter);
$('#textArea').focus(counter);
$('#textArea').mousedown(counter);
$('#textArea').mouseup(counter);
$('#textArea').scroll(counter);
});
/* GUI functions */
var justify = false;
toggleJustify = function () {
if (!justify) {
$('#textArea').css({"text-align": "justify"});
} else {
$('#textArea').css({"text-align": "left"});
}
justify = !justify;
};
/* Saving to the server */
saveContent = function () {
var caretPos = $('#textArea')[0].selectionStart;
var scrollTop = $('#textArea')[0].scrollTop;
alert("Saves content to server " + caretPos + " " + scrollTop);
return false;
}; | /**
* Created by mark on 7/1/16.
*/
/* Counter */
counter = function () {
var value = $('#textArea').val();
if (value.length == 0) {
$('#wordCount').html(0);
$('#caretPos').html(0);
$('#scrollTop').html(0);
return;
}
var regex = /\s+/gi;
var wordCount = value.trim().replace(regex, ' ').split(' ').length;
var caretPos = $('#textArea')[0].selectionStart;
var scrollTop = $('#textArea')[0].scrollTop;
$('#wordCount').html(wordCount);
$('#caretPos').html(caretPos);
$('#scrollTop').html(scrollTop);
};
$(document).ready(function () {
$('#textArea').change(counter);
$('#textArea').keydown(counter);
$('#textArea').keypress(counter);
$('#textArea').keyup(counter);
$('#textArea').blur(counter);
$('#textArea').focus(counter);
$('#textArea').mousedown(counter);
$('#textArea').mouseup(counter);
$('#textArea').scroll(counter);
});
/* GUI functions */
var justify = false;
toggleJustify = function () {
if (!justify) {
$('#textArea').css({"text-align": "justify"});
} else {
$('#textArea').css({"text-align": "left"});
}
justify = !justify;
};
/* Saving to the server */
saveContent = function () {
alert("Saves content to server");
return false;
}; |
Allow uploading directly to a file | import os
import asyncio
from tornado.web import HTTPError
class CreateMixin:
def validate_put(self):
self.kind = self.get_query_argument('kind', default='file')
if self.kind not in ('file', 'folder'):
raise HTTPError(400)
if self.path.endswith('/'):
name = self.get_query_argument('name') # TODO What does this do?
self.path = os.path.join(self.path, name)
if self.kind == 'folder':
self.path += '/'
elif self.kind == 'folder':
raise HTTPError(400)
length = self.request.headers.get('Content-Length')
if length is None and self.kind == 'file':
raise HTTPError(400)
try:
if int(length) > 0 and self.kind == 'folder':
raise HTTPError(400)
except ValueError:
raise HTTPError(400)
@asyncio.coroutine
def create_folder(self):
metadata = yield from self.provider.create_folder(self.path)
self.set_status(201)
self.write(metadata.serialized())
@asyncio.coroutine
def upload_file(self):
self.writer.write_eof()
metadata, created = yield from self.uploader
self.writer.close()
self.wsock.close()
if created:
self.set_status(201)
self.write(metadata.serialized())
| import os
import asyncio
from tornado.web import HTTPError
class CreateMixin:
def validate_put(self):
self.name = self.get_query_argument('name') # TODO What does this do?
self.kind = self.get_query_argument('kind', default='file')
if self.kind not in ('file', 'folder'):
raise HTTPError(400)
length = self.request.headers.get('Content-Length')
if length is None and self.kind == 'file':
raise HTTPError(400)
try:
if int(length) > 0 and self.kind == 'folder':
raise HTTPError(400)
except ValueError:
raise HTTPError(400)
self.path = os.path.join(self.path, self.name)
if self.kind == 'folder':
self.path += '/'
@asyncio.coroutine
def create_folder(self):
metadata = yield from self.provider.create_folder(self.path)
self.set_status(201)
self.write(metadata.serialized())
@asyncio.coroutine
def upload_file(self):
self.writer.write_eof()
metadata, created = yield from self.uploader
self.writer.close()
self.wsock.close()
if created:
self.set_status(201)
self.write(metadata.serialized())
|
Replace 'substring' with 'trimStart' from the OpenAPI utils | package de.espend.idea.laravel.config;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ConfigFileUtil
{
private static final Pattern configFilePattern = Pattern.compile(".*/config/([\\w-/]+).php$");
public static ConfigFileMatchResult matchConfigFile(Project project, VirtualFile virtualFile) {
String projectPath = project.getBaseDir().getPath();
String path = StringUtil.trimStart(virtualFile.getPath(), projectPath);
Matcher m = configFilePattern.matcher(path);
// config/app.php
// config/testing/app.php
if(m.matches()) {
return new ConfigFileMatchResult(true, m.group(1).replace('/', '.'));
} else {
return new ConfigFileMatchResult(false, "");
}
}
public static class ConfigFileMatchResult
{
private boolean matches;
private String keyPrefix;
ConfigFileMatchResult(boolean matches, @NotNull String keyPrefix) {
this.matches = matches;
this.keyPrefix = keyPrefix;
}
public boolean matches() {
return matches;
}
@NotNull
public String getKeyPrefix() {
return keyPrefix;
}
}
}
| package de.espend.idea.laravel.config;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ConfigFileUtil
{
private static final Pattern configFilePattern = Pattern.compile(".*/config/([\\w-/]+).php$");
public static ConfigFileMatchResult matchConfigFile(Project project, VirtualFile virtualFile) {
String path = virtualFile.getPath();
String projectPath = project.getBaseDir().getPath();
if(path.startsWith(projectPath)) {
path = path.substring(projectPath.length());
}
Matcher m = configFilePattern.matcher(path);
// config/app.php
// config/testing/app.php
if(m.matches()) {
return new ConfigFileMatchResult(true, m.group(1).replace('/', '.'));
} else {
return new ConfigFileMatchResult(false, "");
}
}
public static class ConfigFileMatchResult
{
private boolean matches;
private String keyPrefix;
ConfigFileMatchResult(boolean matches, @NotNull String keyPrefix) {
this.matches = matches;
this.keyPrefix = keyPrefix;
}
public boolean matches() {
return matches;
}
@NotNull
public String getKeyPrefix() {
return keyPrefix;
}
}
}
|
Check recursion in str() and repr() | from unittest import TestCase
import lazydict
class TestLazyDictionary(TestCase):
def test_circular_reference_error(self):
d = lazydict.LazyDictionary()
d['foo'] = lambda s: s['foo']
self.assertRaises(lazydict.CircularReferenceError, d.__getitem__, 'foo')
def test_constant_redefinition_error(self):
d = lazydict.LazyDictionary()
d['a'] = 1
d['b'] = 2
d['sum'] = lambda s: s['a'] + s['b']
x = d['sum']
self.assertRaises(lazydict.ConstantRedefinitionError, d.__setitem__, 'a', 'hotdog')
self.assertRaises(lazydict.ConstantRedefinitionError, d.__delitem__, 'a')
def test_lazy_evaluation(self):
d = lazydict.LazyDictionary()
d['sum'] = lambda s: s['a'] + s['b']
d['a'] = 1
d['b'] = 2
self.assertEqual(d['sum'], 3)
def test_str(self):
d = lazydict.LazyDictionary({'a': {'b': 1}})
self.assertEqual(str(d), "{'a': {'b': 1}}")
def test_repr(self):
d = lazydict.LazyDictionary({'a': {'b': 1}})
self.assertEqual(repr(d), "LazyDictionary({'a': {'b': 1}})")
| from unittest import TestCase
import lazydict
class TestLazyDictionary(TestCase):
def test_circular_reference_error(self):
d = lazydict.LazyDictionary()
d['foo'] = lambda s: s['foo']
self.assertRaises(lazydict.CircularReferenceError, d.__getitem__, 'foo')
def test_constant_redefinition_error(self):
d = lazydict.LazyDictionary()
d['a'] = 1
d['b'] = 2
d['sum'] = lambda s: s['a'] + s['b']
x = d['sum']
self.assertRaises(lazydict.ConstantRedefinitionError, d.__setitem__, 'a', 'hotdog')
self.assertRaises(lazydict.ConstantRedefinitionError, d.__delitem__, 'a')
def test_lazy_evaluation(self):
d = lazydict.LazyDictionary()
d['sum'] = lambda s: s['a'] + s['b']
d['a'] = 1
d['b'] = 2
self.assertEqual(d['sum'], 3)
def test_str(self):
d = lazydict.LazyDictionary({'a': 1})
self.assertEqual(str(d), "{'a': 1}")
def test_repr(self):
d = lazydict.LazyDictionary({'a': 1})
self.assertEqual(repr(d), "LazyDictionary({'a': 1})")
|
Make use of the events provided by chosen.
Make it work when using the search field. | /*
* Chosen jQuery plugin to add an image to the dropdown items.
*/
(function($) {
$.fn.chosenImage = function(options) {
return this.each(function() {
var $select = $(this);
var imgMap = {};
// 1. Retrieve img-src from data attribute and build object of image sources for each list item.
$select.find('option').filter(function(){
return $(this).text();
}).each(function(i) {
imgMap[i] = $(this).attr('data-img-src');
});
// 2. Execute chosen plugin and get the newly created chosen container.
$select.chosen(options);
var $chosen = $select.next('.chosen-container').addClass('chosenImage-container');
// 3. Style lis with image sources.
$chosen.on('mousedown.chosen, keyup.chosen', function(event){
$chosen.find('.chosen-results li').each(function() {
var imgIndex = $(this).attr('data-option-array-index');
$(this).css(cssObj(imgMap[imgIndex]));
});
});
// 4. Change image on chosen selected element when form changes.
$select.change(function() {
var imgSrc = $select.find('option:selected').attr('data-img-src') || '';
$chosen.find('.chosen-single span').css(cssObj(imgSrc));
});
$select.trigger('change');
// Utilties
function cssObj(imgSrc) {
var bgImg = (imgSrc) ? 'url(' + imgSrc + ')' : 'none';
return { 'background-image' : bgImg };
}
});
};
})(jQuery);
| /*
* Chosen jQuery plugin to add an image to the dropdown items.
*/
(function($) {
$.fn.chosenImage = function(options) {
return this.each(function() {
var $select = $(this);
var imgMap = {};
// 1. Retrieve img-src from data attribute and build object of image sources for each list item.
$select.find('option').filter(function(){
return $(this).text();
}).each(function(i) {
imgMap[i] = $(this).attr('data-img-src');
});
// 2. Execute chosen plugin and get the newly created chosen container.
$select.chosen(options);
var $chosen = $select.next('.chosen-container').addClass('chosenImage-container');
// 3. Style lis with image sources.
$chosen.mousedown(function(event) {
$chosen.find('.chosen-results li').each(function(i) {
$(this).css(cssObj(imgMap[i]));
});
});
// 4. Change image on chosen selected element when form changes.
$select.change(function() {
var imgSrc = $select.find('option:selected').attr('data-img-src') || '';
$chosen.find('.chosen-single span').css(cssObj(imgSrc));
});
$select.trigger('change');
// Utilties
function cssObj(imgSrc) {
var bgImg = (imgSrc) ? 'url(' + imgSrc + ')' : 'none';
return { 'background-image' : bgImg };
}
});
};
})(jQuery);
|
Include custom templatetags in package build. | import os
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='pybbm-private-messages',
version='0.2.2',
packages=find_packages(),
include_package_data=True,
install_requires=[
'pybbm',
],
test_suite='runtests.runtests',
license='MIT License',
description='A private messaging plugin for the pybbm forum.',
long_description=README,
url='https://github.com/skolsuper/pybbm_private_messages',
author='James Keys',
author_email='[email protected]',
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',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
| import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='pybbm-private-messages',
version='0.2.1',
packages=['private_messages', 'private_messages.migrations'],
include_package_data=True,
install_requires=[
'pybbm',
],
test_suite='runtests.runtests',
license='MIT License',
description='A private messaging plugin for the pybbm forum.',
long_description=README,
url='https://github.com/skolsuper/pybbm_private_messages',
author='James Keys',
author_email='[email protected]',
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',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
|
Remove date formatting from archive list urls | <?php
$years = $this->em($this->ck->module->name('article'))->publishYears();
?>
<ul>
<?php foreach ($years as $year) { ?>
<li>
<a href="<?= $this->ck->url->route([
'year' => $year['year'],
], $this->ck->module->name('main_archive'), true) ?>">
<?= $year['date']->format('Y') ?>
(<?= $year['contentCount'] ?>)
</a>
<ul>
<?php foreach ($year['months'] as $month) { ?>
<li><a href="<?= $this->ck->url->route([
'year' => $month['year'],
'month' => $month['month'],
], $this->ck->module->name('main_archive'), true) ?>">
<?= $month['date']->format('F') ?>
(<?= $month['contentCount'] ?>)
</a></li>
<?php } ?>
</ul>
</li>
<?php } ?>
</ul> | <?php
$years = $this->em($this->ck->module->name('article'))->publishYears();
?>
<ul>
<?php foreach ($years as $year) { ?>
<li>
<a href="<?= $this->ck->url->route([
'year' => $year['date']->format('Y'),
], $this->ck->module->name('main_archive'), true) ?>">
<?= $year['date']->format('Y') ?>
(<?= $year['contentCount'] ?>)
</a>
<ul>
<?php foreach ($year['months'] as $month) { ?>
<li><a href="<?= $this->ck->url->route([
'year' => $month['date']->format('Y'),
'month' => $month['date']->format('m'),
], $this->ck->module->name('main_archive'), true) ?>">
<?= $month['date']->format('F') ?>
(<?= $month['contentCount'] ?>)
</a></li>
<?php } ?>
</ul>
</li>
<?php } ?>
</ul> |
Adjust coverage values to current coverage level | 'use strict';
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
allFiles: ['Gruntfile.js', 'lib/**/*.js', 'test/**/*.js', 'index.js'],
options: {
jshintrc: '.jshintrc',
}
},
mochacli: {
all: ['test/**/*.js'],
options: {
reporter: 'spec',
ui: 'tdd'
}
},
'mocha_istanbul': {
coveralls: {
src: [ 'test/lib', 'test/lib/utils' ],
options: {
coverage: true,
legend: true,
check: {
lines: 95,
statements: 96
},
root: './lib',
reportFormats: ['lcov']
}
}
}
})
grunt.event.on('coverage', function(lcov, done){
require('coveralls').handleInput(lcov, function(error) {
if (error) {
console.log(error)
return done(error)
}
done()
})
})
// Load the plugins
grunt.loadNpmTasks('grunt-contrib-jshint')
grunt.loadNpmTasks('grunt-mocha-cli')
grunt.loadNpmTasks('grunt-mocha-istanbul')
// Configure tasks
grunt.registerTask('coveralls', ['mocha_istanbul:coveralls'])
grunt.registerTask('default', ['test'])
grunt.registerTask('test', ['mochacli', 'jshint', 'coveralls'])
}
| 'use strict';
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
allFiles: ['Gruntfile.js', 'lib/**/*.js', 'test/**/*.js', 'index.js'],
options: {
jshintrc: '.jshintrc',
}
},
mochacli: {
all: ['test/**/*.js'],
options: {
reporter: 'spec',
ui: 'tdd'
}
},
'mocha_istanbul': {
coveralls: {
src: [ 'test/lib', 'test/lib/utils' ],
options: {
coverage: true,
legend: true,
check: {
lines: 100,
statements: 99
},
root: './lib',
reportFormats: ['lcov']
}
}
}
})
grunt.event.on('coverage', function(lcov, done){
require('coveralls').handleInput(lcov, function(error) {
if (error) {
console.log(error)
return done(error)
}
done()
})
})
// Load the plugins
grunt.loadNpmTasks('grunt-contrib-jshint')
grunt.loadNpmTasks('grunt-mocha-cli')
grunt.loadNpmTasks('grunt-mocha-istanbul')
// Configure tasks
grunt.registerTask('coveralls', ['mocha_istanbul:coveralls'])
grunt.registerTask('default', ['test'])
grunt.registerTask('test', ['mochacli', 'jshint', 'coveralls'])
}
|
Add is_staff to user serializer | #from phonenumber_field.serializerfields import PhoneNumberField
from rest_framework import serializers
from drf_extra_fields.geo_fields import PointField
from .models import User
class UserSerializer(serializers.ModelSerializer):
""" Usage:
from rest_framework.renderers import JSONRenderer
from semillas_backend.users.serializers import UserSerializer
JSONRenderer().render(UserSerializer(user_instance).data)
"""
location = PointField()
class Meta:
model = User
fields = ('uuid', 'name', 'picture', 'location', 'username', 'last_login',
'email', 'phone', 'faircoin_address', 'telegram_id',
'is_staff')
class UpdateUserSerializer(serializers.ModelSerializer):
name = serializers.CharField(required=False)
#phone = PhoneNumberField(required=False)
email = serializers.CharField(required=False)
picture = serializers.ImageField(required=False)
uuid = serializers.CharField(read_only=True)
location = PointField(required=False)
class Meta:
model = User
fields = ('name', 'picture', 'phone', 'email', 'uuid',
'faircoin_address', 'telegram_id', 'location',
'location_manually_set')
from wallet.serializers import WalletSerializer
class FullUserSerializer(UserSerializer):
wallet = WalletSerializer()
class Meta:
model = User
fields = ('uuid', 'name', 'picture', 'location', 'username', 'last_login', 'wallet', 'email', 'phone')
| #from phonenumber_field.serializerfields import PhoneNumberField
from rest_framework import serializers
from drf_extra_fields.geo_fields import PointField
from .models import User
class UserSerializer(serializers.ModelSerializer):
""" Usage:
from rest_framework.renderers import JSONRenderer
from semillas_backend.users.serializers import UserSerializer
JSONRenderer().render(UserSerializer(user_instance).data)
"""
location = PointField()
class Meta:
model = User
fields = ('uuid', 'name', 'picture', 'location', 'username', 'last_login',
'email', 'phone', 'faircoin_address', 'telegram_id')
class UpdateUserSerializer(serializers.ModelSerializer):
name = serializers.CharField(required=False)
#phone = PhoneNumberField(required=False)
email = serializers.CharField(required=False)
picture = serializers.ImageField(required=False)
uuid = serializers.CharField(read_only=True)
location = PointField(required=False)
class Meta:
model = User
fields = ('name', 'picture', 'phone', 'email', 'uuid',
'faircoin_address', 'telegram_id', 'location',
'location_manually_set')
from wallet.serializers import WalletSerializer
class FullUserSerializer(UserSerializer):
wallet = WalletSerializer()
class Meta:
model = User
fields = ('uuid', 'name', 'picture', 'location', 'username', 'last_login', 'wallet', 'email', 'phone')
|
Refactor method definitions on prototype to be more DRY | "use strict";
var _ = require("lodash");
var HTTP_STATUS_CODES = require("http").STATUS_CODES;
var request = require("request");
var url = require("url");
function LamernewsAPI(root) {
this.root = root;
return this;
}
LamernewsAPI.prototype = {
getNews: function getNews(options, callback) {
var defaults = {
count: 30,
start: 0,
type: "latest"
};
var signature;
if (!callback && typeof options === "function") {
callback = options;
options = {};
}
options = _.defaults(options || {}, defaults);
signature = ["getnews", options.type, options.start, options.count];
this.query(signature.join("/"), callback);
return this;
},
query: function query(signature, callback) {
if (!this.root) {
throw new Error("No API root specified");
}
request(url.resolve(this.root, signature), function(err, res, body) {
var status;
if (err) {
return callback(err);
}
status = res.statusCode;
if (status !== 200) {
err = new Error(HTTP_STATUS_CODES[status]);
err.code = status;
return callback(err);
}
try {
body = JSON.parse(body);
} catch (err) {
callback(err);
}
callback(null, body);
});
}
};
module.exports = LamernewsAPI;
| "use strict";
var _ = require("lodash");
var HTTP_STATUS_CODES = require("http").STATUS_CODES;
var request = require("request");
var url = require("url");
function LamernewsAPI(root) {
this.root = root;
return this;
}
LamernewsAPI.prototype.getNews = function getNews(options, callback) {
var defaults = {
count: 30,
start: 0,
type: "latest"
};
var signature;
if (!callback && typeof options === "function") {
callback = options;
options = {};
}
options = _.defaults(options || {}, defaults);
signature = ["getnews", options.type, options.start, options.count];
this.query(signature.join("/"), callback);
return this;
};
LamernewsAPI.prototype.query = function query(signature, callback) {
if (!this.root) {
throw new Error("No API root specified");
}
request(url.resolve(this.root, signature), function(err, res, body) {
var status;
if (err) {
return callback(err);
}
status = res.statusCode;
if (status !== 200) {
err = new Error(HTTP_STATUS_CODES[status]);
err.code = status;
return callback(err);
}
try {
body = JSON.parse(body);
} catch (err) {
callback(err);
}
callback(null, body);
});
};
module.exports = LamernewsAPI;
|
Rename client to httpClient for more clarity | package fr.insee.pogues.transforms;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;
import java.util.Map;
@Service
public class StromaeServiceImpl implements StromaeService {
@Autowired
Environment env;
private String serviceUri;
@PostConstruct
public void setUp(){
serviceUri = env.getProperty("fr.insee.pogues.api.remote.stromae.vis.url");
}
@Override
public String transform(String input, Map<String, Object> params) throws Exception {
try {
String uri = String.format("%s/%s", serviceUri,
params.get("name"));
HttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(uri);
post.setEntity(new StringEntity(input, StandardCharsets.UTF_8));
post.setHeader("Content-type", "application/xml");
HttpResponse response = httpClient.execute(post);
return EntityUtils.toString(response.getEntity());
} catch(Exception e) {
throw e;
}
}
}
| package fr.insee.pogues.transforms;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;
import java.util.Map;
@Service
public class StromaeServiceImpl implements StromaeService {
@Autowired
Environment env;
private String serviceUri;
@PostConstruct
public void setUp(){
serviceUri = env.getProperty("fr.insee.pogues.api.remote.stromae.vis.url");
}
@Override
public String transform(String input, Map<String, Object> params) throws Exception {
try {
String uri = String.format("%s/%s", serviceUri,
params.get("name"));
HttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(uri);
post.setEntity(new StringEntity(input, StandardCharsets.UTF_8));
post.setHeader("Content-type", "application/xml");
HttpResponse response = client.execute(post);
return EntityUtils.toString(response.getEntity());
} catch(Exception e) {
throw e;
}
}
}
|
Make sure the subscribe form is available before running the script | /*
* Mailchimp AJAX form submit VanillaJS
* Vanilla JS
* Author: Michiel Vandewalle
* Github author: https://github.com/michiel-vandewalle
* Github project: https://github.com/michiel-vandewalle/Mailchimp-AJAX-form-submit-vanillaJS
*/
(function () {
if (document.getElementsByTagName('form').length > 0) {
document.getElementsByTagName('form')[0].addEventListener('submit', function (e) {
e.preventDefault();
// Check for spam
if(document.getElementById('js-validate-robot').value !== '') { return false }
// Get url for mailchimp
var url = this.action.replace('/post?', '/post-json?');
// Add form data to object
var data = '';
var inputs = this.querySelectorAll('#js-form-inputs input');
for (var i = 0; i < inputs.length; i++) {
data += '&' + inputs[i].name + '=' + encodeURIComponent(inputs[i].value);
}
// Create & add post script to the DOM
var script = document.createElement('script');
script.src = url + data;
document.body.appendChild(script);
// Callback function
var callback = 'callback';
window[callback] = function(data) {
// Remove post script from the DOM
delete window[callback];
document.body.removeChild(script);
// Display response message
document.getElementById('js-subscribe-response').innerHTML = data.msg
};
});
}
})();
| /*
* Mailchimp AJAX form submit VanillaJS
* Vanilla JS
* Author: Michiel Vandewalle
* Github author: https://github.com/michiel-vandewalle
* Github project: https://github.com/michiel-vandewalle/Mailchimp-AJAX-form-submit-vanillaJS
*/
(function () {
document.getElementsByTagName('form')[0].addEventListener('submit', function (e) {
e.preventDefault();
// Check for spam
if(document.getElementById('js-validate-robot').value !== '') { return false }
// Get url for mailchimp
var url = this.action.replace('/post?', '/post-json?');
// Add form data to object
var data = '';
var inputs = this.querySelectorAll('#js-form-inputs input');
for (var i = 0; i < inputs.length; i++) {
data += '&' + inputs[i].name + '=' + encodeURIComponent(inputs[i].value);
}
// Create & add post script to the DOM
var script = document.createElement('script');
script.src = url + data;
document.body.appendChild(script);
// Callback function
var callback = 'callback';
window[callback] = function(data) {
// Remove post script from the DOM
delete window[callback];
document.body.removeChild(script);
// Display response message
document.getElementById('js-subscribe-response').innerHTML = data.msg
};
});
})(); |
Revert "Added comment and used more generic code in xpath validator" | from __future__ import absolute_import
from __future__ import unicode_literals
from collections import namedtuple
from corehq.apps.app_manager.xpath_validator.config import get_xpath_validator_path
from corehq.apps.app_manager.xpath_validator.exceptions import XpathValidationError
from dimagi.utils.subprocess_manager import subprocess_context
XpathValidationResponse = namedtuple('XpathValidationResponse', ['is_valid', 'message'])
def validate_xpath(xpath, allow_case_hashtags=False):
with subprocess_context() as subprocess:
path = get_xpath_validator_path()
if allow_case_hashtags:
cmd = ['node', path, '--allow-case-hashtags']
else:
cmd = ['node', path]
p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = p.communicate(xpath.replace('\r', ' ').encode('utf-8'))
exit_code = p.wait()
if exit_code == 0:
return XpathValidationResponse(is_valid=True, message=None)
elif exit_code == 1:
return XpathValidationResponse(is_valid=False, message=stdout)
else:
raise XpathValidationError(
"{path} failed with exit code {exit_code}:\n{stderr}"
.format(path=path, exit_code=exit_code, stderr=stderr))
| from __future__ import absolute_import
from __future__ import unicode_literals
from collections import namedtuple
from corehq.apps.app_manager.xpath_validator.config import get_xpath_validator_path
from corehq.apps.app_manager.xpath_validator.exceptions import XpathValidationError
from dimagi.utils.subprocess_manager import subprocess_context
XpathValidationResponse = namedtuple('XpathValidationResponse', ['is_valid', 'message'])
def validate_xpath(xpath, allow_case_hashtags=False):
with subprocess_context() as subprocess:
path = get_xpath_validator_path()
if allow_case_hashtags:
cmd = ['node', path, '--allow-case-hashtags']
else:
cmd = ['node', path]
p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
# Collapse whitespace. '\r' mysteriously causes the process to hang in python 3.
stdout, stderr = p.communicate(xpath.replace('\s+', ' ').encode('utf-8'))
exit_code = p.wait()
if exit_code == 0:
return XpathValidationResponse(is_valid=True, message=None)
elif exit_code == 1:
return XpathValidationResponse(is_valid=False, message=stdout)
else:
raise XpathValidationError(
"{path} failed with exit code {exit_code}:\n{stderr}"
.format(path=path, exit_code=exit_code, stderr=stderr))
|
Make sure to end upstart script with .conf |
import os
from kokki import *
def setup(name, **kwargs):
env = Environment.get_instance()
config = env.config.mongodb.copy()
config.update(kwargs)
config['configpath'] = "/etc/mongodb/%s.conf" % name
if 'dbpath' not in kwargs:
config['dbpath'] = os.path.join(config.dbpath, name)
if 'logfilename' not in kwargs:
config['logfilename'] = "%s.log" % name
Directory("/etc/mongodb",
owner = "root",
group = "root",
mode = 0755)
Directory(config.dbpath,
owner = "mongodb",
group = "mongodb",
mode = 0755,
recursive = True)
Service("mongodb-%s" % name)
File("/etc/init/mongodb-%s.conf" % name,
owner = "root",
group = "root",
mode = 0644,
content = Template("mongodb/upstart.conf.j2", variables=dict(mongodb=config)),
notifies = [
("reload", env.resources["Service"]["mongodb-%s" % name], True),
])
File(config.configpath,
owner = "root",
group = "root",
mode = 0644,
content = Template("mongodb/mongodb.conf.j2", variables=dict(mongodb=config)),
notifies = [("restart", env.resources["Service"]["mongodb-%s" % name])])
|
import os
from kokki import *
def setup(name, **kwargs):
env = Environment.get_instance()
config = env.config.mongodb.copy()
config.update(kwargs)
config['configpath'] = "/etc/mongodb/%s.conf" % name
if 'dbpath' not in kwargs:
config['dbpath'] = os.path.join(config.dbpath, name)
if 'logfilename' not in kwargs:
config['logfilename'] = "%s.log" % name
Directory("/etc/mongodb",
owner = "root",
group = "root",
mode = 0755)
Directory(config.dbpath,
owner = "mongodb",
group = "mongodb",
mode = 0755,
recursive = True)
Service("mongodb-%s" % name)
File("/etc/init/mongodb-%s" % name,
owner = "root",
group = "root",
mode = 0644,
content = Template("mongodb/upstart.conf.j2", variables=dict(mongodb=config)),
notifies = [
("reload", env.resources["Service"]["mongodb-%s" % name], True),
])
File(config.configpath,
owner = "root",
group = "root",
mode = 0644,
content = Template("mongodb/mongodb.conf.j2", variables=dict(mongodb=config)),
notifies = [("restart", env.resources["Service"]["mongodb-%s" % name])])
|
Allow calls to 'weigh' to run forever when 'max_attempts' is set to 'inf'. | # -*- coding: utf-8 -*-
import openerp
from ..helpers.usbscale.scale import Scale
from ..helpers.usbscale.scale_manager import ScaleManager
from ..helpers.usbscale.tests import mocks
class ScaleController(openerp.addons.web.http.Controller):
_cp_path = '/scale_proxy'
def __init__(self, *args, **kwargs):
self.scale = Scale()
self.mock_manager = ScaleManager(
lookup=mocks.usb_ids.USB_IDS,
usb_lib=mocks.usb_lib.MockUSBLib()
)
self.mock_endpoint = mocks.usb_lib.MockEndpoint(0, 0)
super(ScaleController, self).__init__(*args, **kwargs)
@openerp.addons.web.http.jsonrequest
def weigh(self, request, max_attempts=10, test_weight=None):
'''Get a reading from the attached USB scale.'''
# Are we running an integration test...
if test_weight:
scale = Scale(device_manager=self.mock_manager)
scale.device.set_weight(test_weight)
weighing = scale.weigh(
endpoint=self.mock_endpoint, max_attempts=float(max_attempts)
)
# ...or are we doing an actual weighing?
if not test_weight:
weighing = self.scale.weigh(max_attempts=float(max_attempts))
if weighing:
return {'success': True, 'weight': weighing.weight, 'unit': weighing.unit}
return {'success': False, 'error': "Could not read scale"} | # -*- coding: utf-8 -*-
import openerp
from ..helpers.usbscale.scale import Scale
from ..helpers.usbscale.scale_manager import ScaleManager
from ..helpers.usbscale.tests import mocks
class ScaleController(openerp.addons.web.http.Controller):
_cp_path = '/scale_proxy'
def __init__(self, *args, **kwargs):
self.scale = Scale()
self.mock_manager = ScaleManager(
lookup=mocks.usb_ids.USB_IDS,
usb_lib=mocks.usb_lib.MockUSBLib()
)
self.mock_endpoint = mocks.usb_lib.MockEndpoint(0, 0)
super(ScaleController, self).__init__(*args, **kwargs)
@openerp.addons.web.http.jsonrequest
def weigh(self, request, max_attempts=10, test_weight=None):
'''Get a reading from the attached USB scale.'''
# Are we running an integration test...
if test_weight:
scale = Scale(device_manager=self.mock_manager)
scale.device.set_weight(test_weight)
weighing = scale.weigh(
endpoint=self.mock_endpoint, max_attempts=max_attempts
)
# ...or are we doing an actual weighing?
if not test_weight:
weighing = self.scale.weigh(max_attempts=max_attempts)
if weighing:
return {'success': True, 'weight': weighing.weight, 'unit': weighing.unit}
return {'success': False, 'error': "Could not read scale"} |
Convert explain to yield function | const _ = require('lodash');
const {gen: tcg} = require('testcheck');
const {invalidString} = require('./conform');
const explainData = require('./explainData');
const {gen} = require('./gen');
const describe = require('./util/describe');
function or(...predicates) {
const pairs = _.chunk(predicates, 2);
return {
conform: value => {
const found = _.find(pairs, ([, predicate]) => predicate(value));
return _.isUndefined(found) ? invalidString : [found[0], value];
},
unform: ([key, value]) => {
const found = _.find(pairs, ([k]) => k === key);
if (_.isUndefined(found)) {
throw new Error(`Key ${key} does not exist in spec`);
}
return value;
},
gen: () => tcg.null.then(() => gen(_.sample(pairs)[1])),
describe: () => [or.name, ...describe(predicates)],
explain: function*(value, {via}) {
const problems = _.map(pairs, ([k, predicate]) => explainData(predicate, value, {path: [k], via}));
if (!_.some(problems, _.isNull)) {
for (let p of problems) {
yield p.problems[0];
}
}
}
};
}
module.exports = or;
| const _ = require('lodash');
const {gen: tcg} = require('testcheck');
const {invalidString} = require('./conform');
const explainData = require('./explainData');
const {gen} = require('./gen');
const describe = require('./util/describe');
function or(...predicates) {
const pairs = _.chunk(predicates, 2);
return {
conform: value => {
const found = _.find(pairs, ([, predicate]) => predicate(value));
return _.isUndefined(found) ? invalidString : [found[0], value];
},
unform: ([key, value]) => {
const found = _.find(pairs, ([k]) => k === key);
if (_.isUndefined(found)) {
throw new Error(`Key ${key} does not exist in spec`);
}
return value;
},
gen: () => tcg.null.then(() => gen(_.sample(pairs)[1])),
describe: () => [or.name, ...describe(predicates)],
explain: function*(value, {via}) {
const problems = _.map(pairs, ([k, predicate]) => explainData(predicate, value, {path: [k], via}));
if (!_.some(problems, _.isNull)) {
for (let i = 0; i < problems.length; i++) {
yield problems[i].problems[0];
}
}
}
};
}
module.exports = or;
|
Fix injection in show dialog button directive | function dialogClose() {
return {
restrict: 'EA',
require: '^dialog',
scope: {
returnValue: '=?return'
},
link(scope, element, attrs, dialog) {
element.on('click', function() {
scope.$apply(() => {
dialog.close(scope.returnValue);
});
});
}
};
}
function showDialogButton(dialogRegistry) {
return {
restrict: 'EA',
scope: {
dialogName: '@for',
modal: '=?',
anchorSelector: '@?anchor'
},
link(scope, element) {
scope.modal = scope.modal !== undefined ? scope.modal : true;
element.on('click', function() {
let dialog = dialogRegistry.getDialog(scope.dialogName);
if (dialog) {
dialog.show(scope.modal, document.querySelector(scope.anchorSelector));
}
});
}
};
}
export {dialogClose, showDialogButton}; | function dialogClose() {
return {
restrict: 'EA',
require: '^dialog',
scope: {
returnValue: '=?return'
},
link(scope, element, attrs, dialog) {
element.on('click', function() {
scope.$apply(() => {
dialog.close(scope.returnValue);
});
});
}
};
}
function showDialogButton() {
return {
restrict: 'EA',
scope: {
dialogName: '@for',
modal: '=?',
anchorSelector: '@?anchor'
},
link(scope, element) {
scope.modal = scope.modal !== undefined ? scope.modal : true;
element.on('click', function() {
let dialog = dialogRegistry.getDialog(scope.dialogName);
if (dialog) {
dialog.show(scope.modal, document.querySelector(scope.anchorSelector));
}
});
}
};
}
export {dialogClose, showDialogButton}; |
[TASK] Add documentation for entry point | <?php
namespace TYPO3\SingleSignOn\Client\Security\EntryPoint;
/* *
* This script belongs to the TYPO3 Flow package "TYPO3.SingleSignOn.Client".*
* *
* */
use TYPO3\Flow\Annotations as Flow;
/**
* An entry point that redirects to the SSO server endpoint
*/
class SingleSignOnRedirect extends \TYPO3\Flow\Security\Authentication\EntryPoint\AbstractEntryPoint {
/**
* @Flow\Inject
* @var \TYPO3\SingleSignOn\Client\Domain\Service\UrlService
*/
protected $urlService;
/**
* Starts the authentication by redirecting to the SSO endpoint
*
* The redirect includes the callback URI (the original URI from the given request)
* the client identifier and a signature of the arguments with the client private key.
*
* @param \TYPO3\Flow\Http\Request $request The current request
* @param \TYPO3\Flow\Http\Response $response The current response
* @return void
*/
public function startAuthentication(\TYPO3\Flow\Http\Request $request, \TYPO3\Flow\Http\Response $response) {
$callbackUrl = $request->getUri();
$redirectUrl = $this->urlService->buildLoginRedirectUrl($callbackUrl);
$response->setStatus(303);
$response->setHeader('Location', $redirectUrl);
}
}
?> | <?php
namespace TYPO3\SingleSignOn\Client\Security\EntryPoint;
/* *
* This script belongs to the TYPO3 Flow package "TYPO3.SingleSignOn.Client".*
* *
* */
use TYPO3\Flow\Annotations as Flow;
/**
* An entry point that redirects to the SSO server endpoint
*/
class SingleSignOnRedirect extends \TYPO3\Flow\Security\Authentication\EntryPoint\AbstractEntryPoint {
/**
* @Flow\Inject
* @var \TYPO3\SingleSignOn\Client\Domain\Service\UrlService
*/
protected $urlService;
/**
* Starts the authentication. (e.g. redirect to login page or send 401 HTTP header)
*
* @param \TYPO3\Flow\Http\Request $request The current request
* @param \TYPO3\Flow\Http\Response $response The current response
* @return void
*/
public function startAuthentication(\TYPO3\Flow\Http\Request $request, \TYPO3\Flow\Http\Response $response) {
$callbackUrl = $request->getUri();
$redirectUrl = $this->urlService->buildLoginRedirectUrl($callbackUrl);
$response->setStatus(303);
$response->setHeader('Location', $redirectUrl);
}
}
?> |
Set Meta class model default on ContainerAdminForm | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django import forms
from django.conf import settings
from opps.db.models.fields.jsonf import JSONFormField
from opps.fields.widgets import JSONField
from opps.fields.models import Field, FieldOption
from .models import Container
class ContainerAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ContainerAdminForm, self).__init__(*args, **kwargs)
if not settings.OPPS_MIRROR_CHANNEL:
self.fields['mirror_channel'].widget = forms.HiddenInput()
self.fields['json'] = JSONFormField(
widget=JSONField(
attrs={'_model': self._meta.model.__name__}),
required=False)
for field in Field.objects.filter(application__contains=
self._meta.model.__name__):
if field.type == 'checkbox':
for fo in FieldOption.objects.filter(field=field):
self.fields[
'json_{}_{}'.format(
field.slug, fo.option.slug
)] = forms.CharField(required=False)
else:
self.fields[
'json_{}'.format(field.slug)
] = forms.CharField(required=False)
class Meta:
model = Container
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django import forms
from django.conf import settings
from opps.db.models.fields.jsonf import JSONFormField
from opps.fields.widgets import JSONField
from opps.fields.models import Field, FieldOption
class ContainerAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ContainerAdminForm, self).__init__(*args, **kwargs)
if not settings.OPPS_MIRROR_CHANNEL:
self.fields['mirror_channel'].widget = forms.HiddenInput()
self.fields['json'] = JSONFormField(
widget=JSONField(
attrs={'_model': self._meta.model.__name__}),
required=False)
for field in Field.objects.filter(application__contains=
self._meta.model.__name__):
if field.type == 'checkbox':
for fo in FieldOption.objects.filter(field=field):
self.fields[
'json_{}_{}'.format(
field.slug, fo.option.slug
)] = forms.CharField(required=False)
else:
self.fields[
'json_{}'.format(field.slug)
] = forms.CharField(required=False)
|
Create argument to select month to import | import numpy
def import_climate_data():
ncols = 720
nrows = 360
digits = 5
monthnr = 3
with open('./data/cloud/ccld6190.dat', 'r') as filein:
lines = filein.readlines()
line_n = 0
grid_size = 0.50
xmin = 0.25
xmax = 360.25
ymin = -89.75
ymax = 90.25
lonrange = numpy.arange(xmin, xmax, grid_size)
latrange = numpy.arange(ymin, ymax, grid_size)
Z = numpy.zeros((int(latrange.shape[0]), int(lonrange.shape[0])))
print(len(lonrange))
print(len(latrange))
i = 0
rown = 0
for line in lines:
line_n += 1
if line_n < 3: # skip header
continue
if rown < (monthnr-1)*nrows or rown >= monthnr*nrows: # read one month
rown += 1
continue
value = ''
counter = 1
j = 0
for char in line:
value += char
if counter % digits == 0:
value = float(value)
if value < 0:
value = numpy.nan
Z[i][j] = value
value = ''
j += 1
counter += 1
i += 1
rown += 1
return latrange, lonrange, Z | import numpy
def import_climate_data():
ncols = 720
nrows = 360
digits = 5
with open('./data/cloud/ccld6190.dat') as filein:
lines = filein.readlines()
line_n = 0
grid_size = 0.50
xmin = 0.25
xmax = 360.25
ymin = -89.75
ymax = 90.25
lonrange = numpy.arange(xmin, xmax, grid_size)
latrange = numpy.arange(ymin, ymax, grid_size)
Z = numpy.zeros((int(latrange.shape[0]), int(lonrange.shape[0])))
print(len(lonrange))
print(len(latrange))
i = 0
for line in lines:
line_n += 1
if line_n < 3: # skip header
continue
if i >= nrows: # read one month
break
value = ''
values = []
counter = 1
j = 0
for char in line:
value += char
if counter % digits == 0:
Z[i][j] = float(value)
values.append(value)
value = ''
j += 1
counter += 1
i += 1
return latrange, lonrange, Z |
Add market tree built from active symbols | import { Map } from 'immutable';
import { FILTER_MARKETS, UPDATE_MARKETS, SERVER_DATA_ACTIVE_SYMBOLS } from '../_constants/ActionTypes';
const initialState = new Map({
active: [],
tree: {},
query: '',
shownMarkets: [],
});
const generateTree = (symbols) => {
const tree = {};
symbols.forEach((sym) => {
if (!tree[sym.market_display_name]) tree[sym.market_display_name] = {};
if (!tree[sym.market_display_name][sym.submarket_display_name]) tree[sym.market_display_name][sym.submarket_display_name] = {};
tree[sym.market_display_name][sym.submarket_display_name][sym] = sym.display_name;
});
return new Map(tree);
};
export default (state = initialState, action) => {
const doFilter = (markets = state.allMarkets, query = state.query) => {
const queryLc = query.toLowerCase();
return markets.filter(m =>
queryLc === '' ||
m.id.toLowerCase().includes(queryLc) ||
m.name.toLowerCase().includes(queryLc)
);
};
switch (action.type) {
case SERVER_DATA_ACTIVE_SYMBOLS: {
const activeSymbols = action.serverResponse.data;
return state
.set('active', activeSymbols)
.set('tree', generateTree(activeSymbols));
}
case FILTER_MARKETS:
return {
...state,
shownMarkets: doFilter(state.markets, action.query),
query: action.query,
};
case UPDATE_MARKETS:
return {
...state,
shownMarkets: doFilter(state.markets, action.query),
query: action.query,
};
default:
return state;
}
};
| import { Map } from 'immutable';
import { FILTER_MARKETS, UPDATE_MARKETS, SERVER_DATA_ACTIVE_SYMBOLS } from '../_constants/ActionTypes';
const initialState = new Map({
active: [],
query: '',
shownMarkets: [],
});
export default (state = initialState, action) => {
const doFilter = (markets = state.allMarkets, query = state.query) => {
const queryLc = query.toLowerCase();
return markets.filter(m =>
queryLc === '' ||
m.id.toLowerCase().includes(queryLc) ||
m.name.toLowerCase().includes(queryLc)
);
};
switch (action.type) {
case SERVER_DATA_ACTIVE_SYMBOLS: {
const data = action.serverResponse.data;
return state.set('active', data);
}
case FILTER_MARKETS:
return {
...state,
shownMarkets: doFilter(state.markets, action.query),
query: action.query,
};
case UPDATE_MARKETS:
return {
...state,
shownMarkets: doFilter(state.markets, action.query),
query: action.query,
};
default:
return state;
}
};
|
Fix - missing comma :/ | 'use strict';
module.exports = function (sequelize, DataTypes) {
var Event = sequelize.define('event', {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
date: {
type: DataTypes.DATEONLY
},
day: {
type: DataTypes.INTEGER(1)
},
from: {
type: DataTypes.STRING(5)
},
to: {
type: DataTypes.STRING(5)
},
activity: {
type: DataTypes.STRING
},
type: {
type: DataTypes.STRING
},
tutorId: {
type: DataTypes.INTEGER
},
placeId: {
type: DataTypes.INTEGER
},
groupId: {
type: DataTypes.INTEGER
},
note: {
type: DataTypes.STRING
},
blocks: {
type: DataTypes.INTEGER
},
deleted: {
type: DataTypes.BOOLEAN,
defaultValue: false
}
}, {
indexes: [{
name: 'unique',
unique: true,
fields: ['date',
'from',
'to',
'activity',
'type',
'tutorId',
'placeId',
'groupId',
'blocks']
}],
timestamps: true
});
return Event;
}; | 'use strict';
module.exports = function (sequelize, DataTypes) {
var Event = sequelize.define('event', {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
date: {
type: DataTypes.DATEONLY
},
day: {
type: DataTypes.INTEGER(1)
},
from: {
type: DataTypes.STRING(5)
},
to: {
type: DataTypes.STRING(5)
},
activity: {
type: DataTypes.STRING
},
type: {
type: DataTypes.STRING
},
tutorId: {
type: DataTypes.INTEGER
},
placeId: {
type: DataTypes.INTEGER
},
groupId: {
type: DataTypes.INTEGER
},
note: {
type: DataTypes.STRING
},
blocks: {
type: DataTypes.INTEGER
},
deleted: {
type: DataTypes.BOOLEAN
defaultValue: false
}
}, {
indexes: [{
name: 'unique',
unique: true,
fields: ['date',
'from',
'to',
'activity',
'type',
'tutorId',
'placeId',
'groupId',
'blocks']
}],
timestamps: true
});
return Event;
}; |
Add support for apcu cache | <?php
namespace OpenClassrooms\Bundle\DoctrineCacheExtensionBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
/**
* @author Romain Kuzniak <[email protected]>
*/
class ServiceCompilerPass implements CompilerPassInterface
{
/**
* @var string[]
*/
public static $types =
[
'apc',
'apcu',
'array',
'couchbase',
'file_system',
'memcache',
'memcached',
'mongodb',
'php_file',
'redis',
'riak',
'wincache',
'xcache',
'zenddata',
];
/**
* {@inheritdoc}
*/
public function process(ContainerBuilder $container)
{
$factoryService = $this->getFactoryService();
foreach (self::$types as $type) {
$definition = $container->findDefinition('doctrine_cache.abstract.'.$type);
$definition->setFactory([new Reference($factoryService), 'create']);
$definition->addArgument($type);
}
}
/**
* @return string
*/
protected function getFactoryService()
{
return 'oc.doctrine_cache_extensions.cache_provider_decorator_factory';
}
}
| <?php
namespace OpenClassrooms\Bundle\DoctrineCacheExtensionBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
/**
* @author Romain Kuzniak <[email protected]>
*/
class ServiceCompilerPass implements CompilerPassInterface
{
/**
* @var string[]
*/
public static $types =
[
'apc',
'array',
'couchbase',
'file_system',
'memcache',
'memcached',
'mongodb',
'php_file',
'redis',
'riak',
'wincache',
'xcache',
'zenddata',
];
/**
* {@inheritdoc}
*/
public function process(ContainerBuilder $container)
{
$factoryService = $this->getFactoryService();
foreach (self::$types as $type) {
$definition = $container->findDefinition('doctrine_cache.abstract.'.$type);
$definition->setFactory([new Reference($factoryService), 'create']);
$definition->addArgument($type);
}
}
/**
* @return string
*/
protected function getFactoryService()
{
return 'oc.doctrine_cache_extensions.cache_provider_decorator_factory';
}
}
|
Add information message for 'widget list remove' | (function () {
'use strict';
var program = require('./../src/customcommander');
var registrycontroller = require('./../src/registrycontroller');
var rmdir = require('rmdir');
var widgetName, widgetsList;
var removeRegistryRecord = function (name) {
console.log('WARNING: widget package might remain at appsngen.com' +
(widgetsList[name].phonegapId ? ' and build.phonegap.com.': '.'));
widgetsList[name] = undefined;
registrycontroller.updateWidgetsList(widgetsList);
};
program
.arguments('<name>')
.usage('<name> [option]')
.option('--hard', 'delete widget folder')
.action(function (name) {
widgetName = name;
})
.parse(process.argv);
if (typeof widgetName === 'undefined') {
program.help();
}
widgetsList = registrycontroller.getWidgetsList();
if (widgetsList[widgetName]) {
if (program.hard) {
rmdir(widgetsList[widgetName].path, function (error) {
if(error) {
console.error(error.toString());
process.exit(1);
}
removeRegistryRecord(widgetName);
});
} else {
removeRegistryRecord(widgetName);
}
} else {
console.log('Widget with provided name doesn\'t exist.');
process.exit(1);
}
})(); | (function () {
'use strict';
var program = require('./../src/customcommander');
var registrycontroller = require('./../src/registrycontroller');
var rmdir = require('rmdir');
var widgetName, widgetsList;
var removeRegistryRecord = function (name) {
widgetsList[name] = undefined;
registrycontroller.updateWidgetsList(widgetsList);
};
program
.arguments('<name>')
.usage('<name> [option]')
.option('--hard', 'delete widget folder')
.action(function (name) {
widgetName = name;
})
.parse(process.argv);
if (typeof widgetName === 'undefined') {
program.help();
}
widgetsList = registrycontroller.getWidgetsList();
if (widgetsList[widgetName]) {
if (program.hard) {
rmdir(widgetsList[widgetName].path, function (error) {
if(error) {
console.error(error.toString());
process.exit(1);
}
removeRegistryRecord(widgetName);
});
} else {
removeRegistryRecord(widgetName);
}
} else {
console.log('Widget with provided name doesn\'t exist.');
process.exit(1);
}
})(); |
Fix payment processor test failures | package appstore;
import static org.junit.Assert.*;
import org.junit.Ignore;
import org.junit.Test;
public class TestThisWillFailAbunch {
@Test
public void aFailingTest() {
assertTrue("I expected this to pass!", true);
}
@Ignore
@Test
public void aFailingTest2() {
assertTrue("I expected this to pass!", true);
}
@Ignore
@Test
public void aFailingTest3() {
assertTrue("I expected this to pass!", false);
}
//@Ignore
@Test
public void aFailingTest4() {
assertTrue("I expected this to pass!", true);
}
@Ignore
@Test
public void aNewFailingTest31() {
assertTrue("I expected this to pass!", true);
}
@Test
public void aNotherNewFailingTest4() {
assertTrue("I expected this to pass!", true);
}
@Test
public void aFailingTest5() {
assertTrue("I expected this to pass!", true);
}
@Test
public void aFailingTest6() {
assertTrue("I expected this to pass!", false);
}
@Test
public void aPassingTest3() {
assertTrue("Success!", true);
}
@Test
public void aPassingTest4() {
assertTrue("Success!", true);
}
private void doSomething() {
interesting();
}
private void interesting() {
RubeGoldburgMachine machine = new RubeGoldburgMachine();
machine.processPayment();
}
private class RubeGoldburgMachine {
void processPayment() {
throw new IllegalStateException("bad payment code");
}
}
}
| package appstore;
import static org.junit.Assert.*;
import org.junit.Ignore;
import org.junit.Test;
public class TestThisWillFailAbunch {
@Test
public void aFailingTest() {
assertTrue("I expected this to pass!", true);
}
@Ignore
@Test
public void aFailingTest2() {
assertTrue("I expected this to pass!", true);
}
@Ignore
@Test
public void aFailingTest3() {
assertTrue("I expected this to pass!", false);
}
//@Ignore
@Test
public void aFailingTest4() {
doSomething();
}
@Ignore
@Test
public void aNewFailingTest31() {
assertTrue("I expected this to pass!", true);
}
@Test
public void aNotherNewFailingTest4() {
assertTrue("I expected this to pass!", true);
}
@Test
public void aFailingTest5() {
doSomething();
}
@Test
public void aFailingTest6() {
assertTrue("I expected this to pass!", false);
}
@Test
public void aPassingTest3() {
assertTrue("Success!", true);
}
@Test
public void aPassingTest4() {
assertTrue("Success!", true);
}
private void doSomething() {
interesting();
}
private void interesting() {
RubeGoldburgMachine machine = new RubeGoldburgMachine();
machine.processPayment();
}
private class RubeGoldburgMachine {
void processPayment() {
throw new IllegalStateException("bad payment code");
}
}
}
|
Fix issues with schema service provider. | <?php
namespace DevelMe;
use Illuminate\Support\ServiceProvider;
class SchemaServiceProvider extends ServiceProvider
{
/**
* Schema Wireframe Commands
*
* @type Array
*/
private $commands = [
'ControllerMake',
'ModelMake',
'SchemaAppMake',
'ViewMake'
];
/**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->registerCommands();
}
/**
* Register all of the schema-wireframe commands.
*
* @return void
*/
private function registerCommands()
{
$commands = $this->commands;
$bind_names = [];
foreach ($commands as $command) {
$this->registerCommand($command);
$bind_name = strtolower($command);
$bind_names[] = "command.schema.$bind_name";
}
call_user_func_array([$this, 'commands'], $bind_names);
}
/**
* Register ControllerMake Command
*
* @author Verron Knowles <[email protected]>
* @return void
*/
private function registerCommand($name)
{
$bind_name = strtolower($name);
$this->app->singleton("command.schema.$bind_name", function ($app) use ($name) {
return $app->make('DevelMe\Console\\'.$name.'Command');
});
}
}
| <?php
namespace DevelMe;
use Illuminate\Support\ServiceProvider;
class SchemaServiceProvider extends ServiceProvider
{
/**
* Schema Wireframe Commands
*
* @type Array
*/
private $commands = [
'ControllerMake',
'ModelMake',
'SchemaAppMake',
'ViewMake'
];
/**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->registerCommands();
}
/**
* Register all of the schema-wireframe commands.
*
* @return void
*/
private function registerCommands()
{
$commands = $this->commands;
foreach ($commands as $command) {
$this->registerCommand($command);
}
$this->commands(
'command.schema.app',
'command.schema.controller',
'command.schema.model',
'command.schema.view'
);
}
/**
* Register ControllerMake Command
*
* @author Verron Knowles <[email protected]>
* @return void
*/
private function registerCommand($name)
{
$bind_name = strtolower($name);
$this->app->singleton("command.schema.$bind_name", function ($app) use ($name) {
return $app->make('DevelMe\Console\\'.$name.'Command');
});
}
}
|
Add the missing halt() call in trigger method to clear previous styles. | package com.strohwitwer.awesomevalidation.validators;
import android.graphics.Color;
import android.widget.EditText;
import com.strohwitwer.awesomevalidation.ValidationHolder;
import com.strohwitwer.awesomevalidation.helper.RangeHelper;
import com.strohwitwer.awesomevalidation.helper.SpanHelper;
import com.strohwitwer.awesomevalidation.utility.ValidationCallback;
import java.util.ArrayList;
import java.util.regex.Matcher;
public class ColorationValidator extends Validator {
private int mColor = Color.RED;
public void setColor(int color) {
mColor = color;
}
@Override
public boolean trigger() {
halt();
return checkFields(new ValidationCallback() {
@Override
public void execute(ValidationHolder validationHolder, Matcher matcher) {
ArrayList<int[]> listOfMatching = new ArrayList<int[]>();
while (matcher.find()) {
listOfMatching.add(new int[]{matcher.start(), matcher.end() - 1});
}
EditText editText = validationHolder.getEditText();
ArrayList<int[]> listOfNotMatching = RangeHelper.inverse(listOfMatching, validationHolder.getText().length());
SpanHelper.setColor(editText, mColor, listOfNotMatching);
editText.setError(validationHolder.getErrMsg());
}
});
}
@Override
public void halt() {
for (ValidationHolder validationHolder : mValidationHolderList) {
EditText editText = validationHolder.getEditText();
editText.setError(null);
SpanHelper.reset(editText);
}
}
} | package com.strohwitwer.awesomevalidation.validators;
import android.graphics.Color;
import android.widget.EditText;
import com.strohwitwer.awesomevalidation.ValidationHolder;
import com.strohwitwer.awesomevalidation.helper.RangeHelper;
import com.strohwitwer.awesomevalidation.helper.SpanHelper;
import com.strohwitwer.awesomevalidation.utility.ValidationCallback;
import java.util.ArrayList;
import java.util.regex.Matcher;
public class ColorationValidator extends Validator {
private int mColor = Color.RED;
public void setColor(int color) {
mColor = color;
}
@Override
public boolean trigger() {
return checkFields(new ValidationCallback() {
@Override
public void execute(ValidationHolder validationHolder, Matcher matcher) {
ArrayList<int[]> listOfMatching = new ArrayList<int[]>();
while (matcher.find()) {
listOfMatching.add(new int[]{matcher.start(), matcher.end() - 1});
}
EditText editText = validationHolder.getEditText();
ArrayList<int[]> listOfNotMatching = RangeHelper.inverse(listOfMatching, validationHolder.getText().length());
SpanHelper.setColor(editText, mColor, listOfNotMatching);
editText.setError(validationHolder.getErrMsg());
}
});
}
@Override
public void halt() {
for (ValidationHolder validationHolder : mValidationHolderList) {
EditText editText = validationHolder.getEditText();
editText.setError(null);
SpanHelper.reset(editText);
}
}
} |
Remove version from minified js name | module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
// define the files to lint
files: ['gruntfile.js', 'src/**/*.js', 'test/**/*.js'],
// configure JSHint (documented at http://www.jshint.com/docs/)
options: {
// more options here if you want to override JSHint defaults
globals: {
jQuery: true,
console: true,
module: true
}
}
},
uglify: {
options: {
banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
},
build: {
src: 'src/<%= pkg.name %>.js',
dest: 'build/<%= pkg.name %>.min.js'
}
}
});
// Load the plugin that provides the "uglify" task.
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.registerTask('test', ['jshint']);
// Default task(s).
grunt.registerTask('default', ['jshint', 'uglify']);
}; | module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
// define the files to lint
files: ['gruntfile.js', 'src/**/*.js', 'test/**/*.js'],
// configure JSHint (documented at http://www.jshint.com/docs/)
options: {
// more options here if you want to override JSHint defaults
globals: {
jQuery: true,
console: true,
module: true
}
}
},
uglify: {
options: {
banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
},
build: {
src: 'src/<%= pkg.name %>.js',
dest: 'build/<%= pkg.name %>v<%= pkg.version %>.min.js'
}
}
});
// Load the plugin that provides the "uglify" task.
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.registerTask('test', ['jshint']);
// Default task(s).
grunt.registerTask('default', ['jshint', 'uglify']);
}; |
Add src in path for dev javascript | module.exports = {
all: {
files: [
{ expand: true, src: ['config.json'], dest: 'dist' },
{ expand: true, src: ['javascript.json'], dest: 'dist' },
{ expand: true, cwd: 'src/config/locales/', src: ['**'], dest: 'dist/config/locales/' },
{ expand: true, cwd: 'src/images/', src: ['**'], dest: 'dist/images/', },
{ expand: true, cwd: 'src/downloads/', src: ['**'], dest: 'dist/downloads/' },
{ expand: true, cwd: 'src/flash/', src: ['**'], dest: 'dist/flash/' },
{ expand: true, cwd: 'src/templates/', src: ['**'], dest: 'dist/templates/' },
{ expand: true, cwd: 'src/css/external/jquery-ui-custom-theme/images/', src: ['**'], dest: 'dist/css/images' },
{ expand: true, cwd: 'src/css/external/jquery-ui-custom-theme/', src: ['*.css'], dest: 'dist/css/' },
{ expand: true, cwd: 'src/css/fonts/', src: ['**'], dest: 'dist/css/fonts' },
{ expand: true, cwd: 'src/javascript/', src: ['**'], dest: 'dist/dev/src/javascript/' }
]
}
};
| module.exports = {
all: {
files: [
{ expand: true, src: ['config.json'], dest: 'dist' },
{ expand: true, src: ['javascript.json'], dest: 'dist' },
{ expand: true, cwd: 'src/config/locales/', src: ['**'], dest: 'dist/config/locales/' },
{ expand: true, cwd: 'src/images/', src: ['**'], dest: 'dist/images/', },
{ expand: true, cwd: 'src/downloads/', src: ['**'], dest: 'dist/downloads/' },
{ expand: true, cwd: 'src/flash/', src: ['**'], dest: 'dist/flash/' },
{ expand: true, cwd: 'src/templates/', src: ['**'], dest: 'dist/templates/' },
{ expand: true, cwd: 'src/css/external/jquery-ui-custom-theme/images/', src: ['**'], dest: 'dist/css/images' },
{ expand: true, cwd: 'src/css/external/jquery-ui-custom-theme/', src: ['*.css'], dest: 'dist/css/' },
{ expand: true, cwd: 'src/css/fonts/', src: ['**'], dest: 'dist/css/fonts' },
{ expand: true, cwd: 'src/javascript/', src: ['**'], dest: 'dist/dev/javascript/' }
]
}
};
|
Use SystemRandom instead of insecure RNG | """
In here we shall keep track of all variables and objects that should be
instantiated only once and be common to pieces of GLBackend code.
"""
__version__ = '1.0.0'
__all__ = ['Storage', 'randomStr']
import string
from random import SystemRandom
random = SystemRandom()
class Storage(dict):
"""
A Storage object is like a dictionary except `obj.foo` can be used
in addition to `obj['foo']`.
>>> o = Storage(a=1)
>>> o.a
1
>>> o['a']
1
>>> o.a = 2
>>> o['a']
2
>>> del o.a
>>> o.a
"""
def __getattr__(self, key):
return self.get(key)
def __setattr__(self, key, value):
self[key] = value
def __delattr__(self, key):
try:
del self[key]
except KeyError, k:
raise AttributeError(k)
def __repr__(self):
return '<Storage ' + dict.__repr__(self) + '>'
def __getstate__(self):
return dict(self)
def __setstate__(self, value):
self.update(value.items())
def randomStr(length, num=True):
"""
Returns a random a mixed lowercase, uppercase, alfanumerical (if num True)
string long length
"""
chars = string.ascii_lowercase + string.ascii_uppercase
if num:
chars += string.digits
return ''.join(random.choice(chars) for x in range(length))
| """
In here we shall keep track of all variables and objects that should be
instantiated only once and be common to pieces of GLBackend code.
"""
__version__ = '1.0.0'
__all__ = ['Storage', 'randomStr']
import string
import random
class Storage(dict):
"""
A Storage object is like a dictionary except `obj.foo` can be used
in addition to `obj['foo']`.
>>> o = Storage(a=1)
>>> o.a
1
>>> o['a']
1
>>> o.a = 2
>>> o['a']
2
>>> del o.a
>>> o.a
"""
def __getattr__(self, key):
return self.get(key)
def __setattr__(self, key, value):
self[key] = value
def __delattr__(self, key):
try:
del self[key]
except KeyError, k:
raise AttributeError(k)
def __repr__(self):
return '<Storage ' + dict.__repr__(self) + '>'
def __getstate__(self):
return dict(self)
def __setstate__(self, value):
self.update(value.items())
def randomStr(length, num=True):
"""
Returns a random a mixed lowercase, uppercase, alfanumerical (if num True)
string long length
"""
chars = string.ascii_lowercase + string.ascii_uppercase
if num:
chars += string.digits
return ''.join(random.choice(chars) for x in range(length))
|
Add test for unimplemented get_response_statements function | from unittest import TestCase
from chatterbot.storage import StorageAdapter
class StorageAdapterTestCase(TestCase):
"""
This test case is for the StorageAdapter base class.
Although this class is not intended for direct use,
this test case ensures that exceptions requiring
basic functionality are triggered when needed.
"""
def setUp(self):
super(StorageAdapterTestCase, self).setUp()
self.adapter = StorageAdapter()
def test_count(self):
with self.assertRaises(StorageAdapter.AdapterMethodNotImplementedError):
self.adapter.count()
def test_filter(self):
with self.assertRaises(StorageAdapter.AdapterMethodNotImplementedError):
self.adapter.filter()
def test_remove(self):
with self.assertRaises(StorageAdapter.AdapterMethodNotImplementedError):
self.adapter.remove('')
def test_create(self):
with self.assertRaises(StorageAdapter.AdapterMethodNotImplementedError):
self.adapter.create()
def test_update(self):
with self.assertRaises(StorageAdapter.AdapterMethodNotImplementedError):
self.adapter.update('')
def test_get_random(self):
with self.assertRaises(StorageAdapter.AdapterMethodNotImplementedError):
self.adapter.get_random()
def test_drop(self):
with self.assertRaises(StorageAdapter.AdapterMethodNotImplementedError):
self.adapter.drop()
def test_get_response_statements(self):
with self.assertRaises(StorageAdapter.AdapterMethodNotImplementedError):
self.adapter.get_response_statements()
| from unittest import TestCase
from chatterbot.storage import StorageAdapter
class StorageAdapterTestCase(TestCase):
"""
This test case is for the StorageAdapter base class.
Although this class is not intended for direct use,
this test case ensures that exceptions requiring
basic functionality are triggered when needed.
"""
def setUp(self):
super(StorageAdapterTestCase, self).setUp()
self.adapter = StorageAdapter()
def test_count(self):
with self.assertRaises(StorageAdapter.AdapterMethodNotImplementedError):
self.adapter.count()
def test_filter(self):
with self.assertRaises(StorageAdapter.AdapterMethodNotImplementedError):
self.adapter.filter()
def test_remove(self):
with self.assertRaises(StorageAdapter.AdapterMethodNotImplementedError):
self.adapter.remove('')
def test_create(self):
with self.assertRaises(StorageAdapter.AdapterMethodNotImplementedError):
self.adapter.create()
def test_update(self):
with self.assertRaises(StorageAdapter.AdapterMethodNotImplementedError):
self.adapter.update('')
def test_get_random(self):
with self.assertRaises(StorageAdapter.AdapterMethodNotImplementedError):
self.adapter.get_random()
def test_drop(self):
with self.assertRaises(StorageAdapter.AdapterMethodNotImplementedError):
self.adapter.drop()
|
Clean up the lab10 code a bit. | /**
* Created by curtis on 3/28/16.
*/
angular.module('clusterApp', [])
.controller('MainCtrl', [
'$scope',
'$http',
function($scope, $http) {
var completed = 0,
timesToQuery = 100;
$scope.cluster = [];
$scope.busy = false;
$scope.getMyPIDs = function() {
$scope.busy = true;
for (var i = 0; i < timesToQuery; i++) {
$http.get('/pid').success(function(data) {
//console.log("getAll", data);
completed++;
$scope.cluster.push(data);
if (completed % timesToQuery == 0) {
$scope.busy = false;
}
});
}
};
$scope.clearPIDs = function() {
completed = 0;
$scope.cluster = [];
};
}
]); | /**
* Created by curtis on 3/28/16.
*/
angular.module('clusterApp', [])
.controller('MainCtrl', [
'$scope',
'$http',
function($scope, $http) {
var completed = 0,
timesToQuery = 100,
pids = [];
$scope.cluster = [];
$scope.busy = false;
$scope.getMyPIDs = function() {
$scope.busy = true;
for (var i = 0; i < timesToQuery; i++) {
$http.get('/pid').success(function(data) {
//console.log("getAll", data);
pids.push(data);
completed++;
if (completed % timesToQuery == 0) {
$scope.cluster = angular.copy(pids);
$scope.busy = false;
}
});
}
};
$scope.clearPIDs = function() {
completed = 0;
pids = [];
$scope.cluster = [];
};
}
]); |
Add explicit version check for Django 1.7 or above | from django.db import models
from south.db import DEFAULT_DB_ALIAS
# If we detect Django 1.7 or higher, then exit
# Placed here so it's guaranteed to be imported on Django start
import django
if django.VERSION[0] > 1 or (django.VERSION[0] == 1 and django.VERSION[1] > 6):
raise RuntimeError("South does not support Django 1.7 or higher. Please use native Django migrations.")
class MigrationHistory(models.Model):
app_name = models.CharField(max_length=255)
migration = models.CharField(max_length=255)
applied = models.DateTimeField(blank=True)
@classmethod
def for_migration(cls, migration, database):
try:
# Switch on multi-db-ness
if database != DEFAULT_DB_ALIAS:
# Django 1.2
objects = cls.objects.using(database)
else:
# Django <= 1.1
objects = cls.objects
return objects.get(
app_name=migration.app_label(),
migration=migration.name(),
)
except cls.DoesNotExist:
return cls(
app_name=migration.app_label(),
migration=migration.name(),
)
def get_migrations(self):
from south.migration.base import Migrations
return Migrations(self.app_name)
def get_migration(self):
return self.get_migrations().migration(self.migration)
def __str__(self):
return "<%s: %s>" % (self.app_name, self.migration)
| from django.db import models
from south.db import DEFAULT_DB_ALIAS
class MigrationHistory(models.Model):
app_name = models.CharField(max_length=255)
migration = models.CharField(max_length=255)
applied = models.DateTimeField(blank=True)
@classmethod
def for_migration(cls, migration, database):
try:
# Switch on multi-db-ness
if database != DEFAULT_DB_ALIAS:
# Django 1.2
objects = cls.objects.using(database)
else:
# Django <= 1.1
objects = cls.objects
return objects.get(
app_name=migration.app_label(),
migration=migration.name(),
)
except cls.DoesNotExist:
return cls(
app_name=migration.app_label(),
migration=migration.name(),
)
def get_migrations(self):
from south.migration.base import Migrations
return Migrations(self.app_name)
def get_migration(self):
return self.get_migrations().migration(self.migration)
def __str__(self):
return "<%s: %s>" % (self.app_name, self.migration)
|
Revert "Re-search for listPanelCell in addAndRemoveLabelTest"
This reverts commit f1e2b41afb4623ff35771d028fbd79810e80dece. | package guitests;
import javafx.scene.input.KeyCode;
import org.junit.Test;
import ui.listpanel.ListPanelCell;
import static org.junit.Assert.assertEquals;
import static org.loadui.testfx.Assertions.assertNodeExists;
import static org.loadui.testfx.controls.Commons.hasText;
public class LabelPickerTests extends UITest {
public static final int EVENT_DELAY = 500;
@Test
public void showLabelPickerTest() {
click("#dummy/dummy_col0_9");
push(KeyCode.L);
sleep(EVENT_DELAY);
assertNodeExists(hasText("Issue #9: Issue 9"));
push(KeyCode.ENTER);
}
@Test
public void addAndRemoveLabelTest() {
ListPanelCell listPanelCell = find("#dummy/dummy_col0_9");
click(listPanelCell);
assertEquals(1, listPanelCell.getIssueLabels().size());
push(KeyCode.L);
sleep(EVENT_DELAY);
type("3 ");
push(KeyCode.ENTER);
sleep(EVENT_DELAY);
assertEquals(2, listPanelCell.getIssueLabels().size());
push(KeyCode.L);
sleep(EVENT_DELAY);
type("3 ");
push(KeyCode.ENTER);
sleep(EVENT_DELAY);
assertEquals(1, listPanelCell.getIssueLabels().size());
}
}
| package guitests;
import javafx.scene.input.KeyCode;
import org.junit.Test;
import ui.listpanel.ListPanelCell;
import static org.junit.Assert.assertEquals;
import static org.loadui.testfx.Assertions.assertNodeExists;
import static org.loadui.testfx.controls.Commons.hasText;
public class LabelPickerTests extends UITest {
public static final int EVENT_DELAY = 500;
@Test
public void showLabelPickerTest() {
click("#dummy/dummy_col0_9");
push(KeyCode.L);
sleep(EVENT_DELAY);
assertNodeExists(hasText("Issue #9: Issue 9"));
push(KeyCode.ENTER);
}
@Test
public void addAndRemoveLabelTest() {
ListPanelCell listPanelCell = find("#dummy/dummy_col0_9");
click(listPanelCell);
assertEquals(1, listPanelCell.getIssueLabels().size());
push(KeyCode.L);
sleep(EVENT_DELAY);
type("3 ");
push(KeyCode.ENTER);
listPanelCell = find("#dummy/dummy_col0_9");
sleep(EVENT_DELAY);
assertEquals(2, listPanelCell.getIssueLabels().size());
push(KeyCode.L);
sleep(EVENT_DELAY);
type("3 ");
push(KeyCode.ENTER);
listPanelCell = find("#dummy/dummy_col0_9");
sleep(EVENT_DELAY);
assertEquals(1, listPanelCell.getIssueLabels().size());
}
}
|
Comment out a console log | angular
.module('app')
.directive('modal', ['$compile', '$templateCache', 'pageService',
function($compile, $templateCache, pageAPI) {
return {
scope: true,
compile: function(element, cAtts) {
return function(scope, element, lAtts) {
var $element, template;
var bindClick = function() {
element.on('click', function(e) {
// e.preventDefault();
$element.modal('show');
angular.element(document.getElementById('wrap')).addClass('openModal');
scope.$parent.closeModal = function() {
$element.modal('hide');
angular.element(document.getElementById('wrap')).removeClass('openModal');
};
});
};
// if this is a template modal
if(cAtts.template) {
$element = template = $templateCache.get(cAtts.template);
$element = $($compile(template)(scope));
bindClick();
}
// else this is a page modal
else if(cAtts.page) {
$element = template = $templateCache.get("app/templates/partials/pageModal.html");
pageAPI.getByURL(cAtts.page, function(err, res) {
if (!err) {
scope.modalView = res;
$element = $($compile(template)(scope));
bindClick();
}
});
}
};
}
};
}
]);
| angular
.module('app')
.directive('modal', ['$compile', '$templateCache', 'pageService',
function($compile, $templateCache, pageAPI) {
return {
scope: true,
compile: function(element, cAtts) {
return function(scope, element, lAtts) {
console.log(scope);
var $element, template;
var bindClick = function() {
element.on('click', function(e) {
// e.preventDefault();
$element.modal('show');
angular.element(document.getElementById('wrap')).addClass('openModal');
scope.$parent.closeModal = function() {
$element.modal('hide');
angular.element(document.getElementById('wrap')).removeClass('openModal');
};
});
};
// if this is a template modal
if(cAtts.template) {
$element = template = $templateCache.get(cAtts.template);
$element = $($compile(template)(scope));
bindClick();
}
// else this is a page modal
else if(cAtts.page) {
$element = template = $templateCache.get("app/templates/partials/pageModal.html");
pageAPI.getByURL(cAtts.page, function(err, res) {
if (!err) {
scope.modalView = res;
$element = $($compile(template)(scope));
bindClick();
}
});
}
};
}
};
}
]);
|
Test against SimpleAdminConfig on Django>=1.7.
In test cases, use the same admin setup we recommend to users. | # python setup.py test
# or
# python runtests.py
import sys
from django import VERSION as django_version
from django.conf import settings
APP = 'djrill'
ADMIN = 'django.contrib.admin'
if django_version >= (1, 7):
ADMIN = 'django.contrib.admin.apps.SimpleAdminConfig'
settings.configure(
DEBUG=True,
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
},
ROOT_URLCONF=APP+'.urls',
INSTALLED_APPS=(
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
ADMIN,
APP,
),
MIDDLEWARE_CLASSES=(
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
)
try:
# Django 1.7+ initialize app registry
from django import setup
setup()
except ImportError:
pass
try:
from django.test.runner import DiscoverRunner as TestRunner # Django 1.6+
except ImportError:
from django.test.simple import DjangoTestSuiteRunner as TestRunner # Django -1.5
def runtests():
test_runner = TestRunner(verbosity=1)
failures = test_runner.run_tests([APP])
sys.exit(failures)
if __name__ == '__main__':
runtests()
| # python setup.py test
# or
# python runtests.py
import sys
from django.conf import settings
APP = 'djrill'
settings.configure(
DEBUG=True,
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
},
ROOT_URLCONF=APP+'.urls',
INSTALLED_APPS=(
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.admin',
APP,
),
MIDDLEWARE_CLASSES=(
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
)
try:
# Django 1.7+ initialize app registry
from django import setup
setup()
except ImportError:
pass
try:
from django.test.runner import DiscoverRunner as TestRunner # Django 1.6+
except ImportError:
from django.test.simple import DjangoTestSuiteRunner as TestRunner # Django -1.5
def runtests():
test_runner = TestRunner(verbosity=1)
failures = test_runner.run_tests([APP])
sys.exit(failures)
if __name__ == '__main__':
runtests()
|
Fix shop invoice index notice | <?php
/*
* This file is part of the fnacApi.
* (c) 2011 Fnac
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace FnacApiClient\Service\Response;
use Symfony\Component\Serializer\SerializerInterface;
use FnacApiClient\Entity\ShopInvoice;
/**
* BatchQueryResponse service base definition for batch query response
*
* @author Fnac
* @version 1.0.0
*/
class ShopInvoiceQueryResponse extends QueryResponse
{
private $shop_invoices = array();
/**
* {@inheritdoc}
*/
public function denormalize(SerializerInterface $serializer, $data, $format = null)
{
parent::denormalize($serializer, $data, $format);
$this->shop_invoices = new \ArrayObject();
if(!empty($data['shop_invoice'])) {
foreach ($data['shop_invoice'] as $shop_invoice) {
$shopInvoiceObj = new ShopInvoice();
$shopInvoiceObj->denormalize($serializer, $shop_invoice, $format);
$this->shop_invoices[] = $shopInvoiceObj;
}
}
}
/**
* List of shops' invoices
*
* @see FnacApiClient\Entity\ShopInvoice
*
* @return ArrayObject<ShopInvoice>
*/
public function getShopInvoices()
{
return $this->shop_invoices;
}
}
| <?php
/*
* This file is part of the fnacApi.
* (c) 2011 Fnac
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace FnacApiClient\Service\Response;
use Symfony\Component\Serializer\SerializerInterface;
use FnacApiClient\Entity\ShopInvoice;
/**
* BatchQueryResponse service base definition for batch query response
*
* @author Fnac
* @version 1.0.0
*/
class ShopInvoiceQueryResponse extends QueryResponse
{
private $shop_invoices = array();
/**
* {@inheritdoc}
*/
public function denormalize(SerializerInterface $serializer, $data, $format = null)
{
parent::denormalize($serializer, $data, $format);
$this->shop_invoices = new \ArrayObject();
foreach ($data['shop_invoice'] as $shop_invoice) {
$shopInvoiceObj = new ShopInvoice();
$shopInvoiceObj->denormalize($serializer, $shop_invoice, $format);
$this->shop_invoices[] = $shopInvoiceObj;
}
}
/**
* List of shops' invoices
*
* @see FnacApiClient\Entity\ShopInvoice
*
* @return ArrayObject<ShopInvoice>
*/
public function getShopInvoices()
{
return $this->shop_invoices;
}
}
|
Change multi line string to be regular comment. | from ed2d.physics import rectangle
from ed2d.physics import quadtree
class PhysEngine(object):
def __init__(self):
# I would love to have width and height as global constants
self.quadTree = quadtree.QuadTree(0, rectangle.Rectangle(0.0, 0.0, width=800, height=600, flag='QT'))
self.quadTree.clear()
self.pObjects = []
self.returnObjects = []
def simulate(self, delta):
'''Update all the objects'''
# Update the quad tree
self.quadTree.clear()
for item in self.pObjects:
self.quadTree.insert(item)
# Pass this for a while, this basically add velocity to objects
# But is kinda of a stupid way to do
# for i in range(len(self.pObjects)):
# self.pObjects[i].update(delta)
# Run collision check
self.collisions()
def collisions(self):
objects = []
self.quadTree.retriveAll(objects)
for x in range(len(objects)):
obj = []
self.quadTree.findObjects(obj, objects[x])
for y in range(len(obj)):
objects[x].getCollisionModel().intersect(obj[y].getCollisionModel())
del obj[:]
del objects[:]
def addObject(self, p_object):
self.quadTree.insert(p_object)
self.pObjects.append(p_object)
def getObject(self, index):
return self.pObjects[index]
def getLength(self):
return len(self.pObjects)
| from ed2d.physics import rectangle
from ed2d.physics import quadtree
class PhysEngine(object):
def __init__(self):
# I would love to have width and height as global constants
self.quadTree = quadtree.QuadTree(0, rectangle.Rectangle(0.0, 0.0, width=800, height=600, flag='QT'))
self.quadTree.clear()
self.pObjects = []
self.returnObjects = []
def simulate(self, delta):
'''Update all the objects'''
# Update the quad tree
self.quadTree.clear()
for item in self.pObjects:
self.quadTree.insert(item)
# Pass this for a while, this basically add velocity to objects
# But is kinda of a stupid way to do
'''
for i in range(len(self.pObjects)):
self.pObjects[i].update(delta)
'''
# Run collision check
self.collisions()
def collisions(self):
objects = []
self.quadTree.retriveAll(objects)
for x in range(len(objects)):
obj = []
self.quadTree.findObjects(obj, objects[x])
for y in range(len(obj)):
objects[x].getCollisionModel().intersect(obj[y].getCollisionModel())
del obj[:]
del objects[:]
def addObject(self, p_object):
self.quadTree.insert(p_object)
self.pObjects.append(p_object)
def getObject(self, index):
return self.pObjects[index]
def getLength(self):
return len(self.pObjects) |
Fix incompatibility between FrontendBridge/jsonAction with the inclusion of the RequestHandlerComponent. Make sure the "json" View subfolder is not used in this case. | <?php
namespace FrontendBridge\Lib;
trait FrontendBridgeTrait
{
/**
* jsonActionResponse
*
* @param \Cake\Network\Response $response the response
* @return \FrontendBridge\Lib\ServiceResponse
*/
protected function jsonActionResponse(\Cake\Network\Response $response)
{
// get the frontendData set by the Frontend plugin and remove unnecessary data
$frontendData = $this->viewVars['frontendData'];
unset($frontendData['Types']);
$response = array(
'code' => 'success',
'data' => array(
'frontendData' => $frontendData,
'html' => $response->body()
)
);
return new \FrontendBridge\Lib\ServiceResponse($response);
}
/**
* renderJsonAction
*
* @param string $view the view to render
* @param string $layout the layout to render
* @return \FrontendBridge\Lib\ServiceResponse
*/
public function renderJsonAction($view, $layout)
{
if ($layout === null) {
$layout = 'FrontendBridge.json_action';
}
if ($this->RequestHandler) {
$this->RequestHandler->renderAs($this, 'ajax');
}
$response = parent::render($view, $layout);
return $this->jsonActionResponse($response);
}
/**
* Detect if the current request should be rendered as a JSON Action
*
* @return bool
*/
protected function _isJsonActionRequest()
{
return
(isset($this->request->params['jsonAction']) && $this->request->params['jsonAction'] === true)
|| $this->request->query('json_action') == 1;
}
}
| <?php
namespace FrontendBridge\Lib;
trait FrontendBridgeTrait {
/**
* jsonActionResponse
*
* @param \Cake\Network\Response $response the response
* @return \FrontendBridge\Lib\ServiceResponse
*/
protected function jsonActionResponse(\Cake\Network\Response $response) {
// get the frontendData set by the Frontend plugin and remove unnecessary data
$frontendData = $this->viewVars['frontendData'];
unset($frontendData['Types']);
$response = array(
'code' => 'success',
'data' => array(
'frontendData' => $frontendData,
'html' => $response->body()
)
);
return new \FrontendBridge\Lib\ServiceResponse($response);
}
/**
* renderJsonAction
*
* @param string $view the view to render
* @param string $layout the layout to render
* @return \FrontendBridge\Lib\ServiceResponse
*/
public function renderJsonAction($view, $layout) {
if ($layout === null) {
$layout = 'FrontendBridge.json_action';
}
$response = parent::render($view, $layout);
$this->getView()->subDir = null;
return $this->jsonActionResponse($response);
}
/**
* Detect if the current request should be rendered as a JSON Action
*
* @return bool
*/
protected function _isJsonActionRequest() {
return
(isset($this->request->params['jsonAction']) && $this->request->params['jsonAction'] === true)
|| $this->request->query('json_action') == 1;
}
}
|
Fix react outside of guilds, add checks for custom emojis. | const { Command } = require('discord-akairo');
function exec(message, args){
let emojiSet;
if (!message.guild || !message.guild.emojis.size){
emojiSet = this.client.user.premium ? this.client.emojis : this.client.emojis.filter(e => e.managed);
} else {
emojiSet = message.guild.emojis;
}
if (emojiSet.size === 0){
this.framework.logger.log(3, 'No custom emojis to react with.');
return message.delete();
}
let emojis = emojiSet.array();
let currentIndex = emojis.length;
let temporaryValue;
let randomIndex;
while (currentIndex !== 0) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
temporaryValue = emojis[currentIndex];
emojis[currentIndex] = emojis[randomIndex];
emojis[randomIndex] = temporaryValue;
}
emojis = emojis.slice(0, Math.min(args.amount, 20));
return message.delete().then(() => message.channel.fetchMessages({ limit: 2 }).then(messages => {
const reactee = messages.first();
if (!reactee) return;
const react = i => {
if (!emojis[i]) return;
setTimeout(() => reactee.react(emojis[i]).then(() => react(i + 1)));
};
react(0);
}));
}
module.exports = new Command('superreact', exec, {
aliases: ['superreact'],
args: [
{
id: 'amount',
type: 'integer',
defaultValue: 1
}
]
});
| const { Command } = require('discord-akairo');
function exec(message, args){
let emojiSet;
if (!message.guild || !message.guild.emojis.size){
emojiSet = this.client.emojis;
} else {
emojiSet = message.guild.emojis;
}
let emojis = emojiSet.array();
let currentIndex = emojis.length;
let temporaryValue;
let randomIndex;
while (currentIndex !== 0) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
temporaryValue = emojis[currentIndex];
emojis[currentIndex] = emojis[randomIndex];
emojis[randomIndex] = temporaryValue;
}
emojis = emojis.slice(0, Math.min(args.amount, 20));
return message.delete().then(() => message.channel.fetchMessages({ limit: 2 }).then(messages => {
const reactee = messages.first();
if (!reactee) return;
const react = i => {
if (!emojis[i]) return;
setTimeout(() => reactee.react(emojis[i]).then(() => react(i + 1)));
};
react(0);
}));
}
module.exports = new Command('superreact', exec, {
aliases: ['superreact'],
args: [
{
id: 'amount',
type: 'integer',
defaultValue: 1
}
]
});
|
Update email address and home page. | #
# This file is part of ArgProc. ArgProc is free software that is made
# available under the MIT license. Consult the file "LICENSE" that is
# distributed together with this file for the exact licensing terms.
#
# ArgProc is copyright (c) 2010 by the ArgProc authors. See the file
# "AUTHORS" for a complete overview.
import os
from setuptools import setup, Extension, Command
class gentab(Command):
"""Generate the PLY parse tables."""
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
from argproc.parser import RuleParser
RuleParser._write_tables()
setup(
name = 'argproc',
version = '1.4',
description = 'A rule-based arguments processor',
author = 'Geert Jansen',
author_email = '[email protected]',
url = 'http://github.com/geertj/argproc',
license = 'MIT',
classifiers = [
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules' ],
package_dir = {'': 'lib'},
packages = ['argproc', 'argproc.test'],
test_suite = 'nose.collector',
cmdclass = { 'gentab': gentab },
install_requires = ['ply >= 3.3', 'nose'],
use_2to3 = True
)
| #
# This file is part of ArgProc. ArgProc is free software that is made
# available under the MIT license. Consult the file "LICENSE" that is
# distributed together with this file for the exact licensing terms.
#
# ArgProc is copyright (c) 2010 by the ArgProc authors. See the file
# "AUTHORS" for a complete overview.
import os
from setuptools import setup, Extension, Command
class gentab(Command):
"""Generate the PLY parse tables."""
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
from argproc.parser import RuleParser
RuleParser._write_tables()
setup(
name = 'argproc',
version = '1.4',
description = 'A rule-based arguments processor',
author = 'Geert Jansen',
author_email = '[email protected]',
url = 'http://bitbucket.org/geertj/argproc',
license = 'MIT',
classifiers = [
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules' ],
package_dir = {'': 'lib'},
packages = ['argproc', 'argproc.test'],
test_suite = 'nose.collector',
cmdclass = { 'gentab': gentab },
install_requires = ['ply >= 3.3', 'nose'],
use_2to3 = True
)
|
Move event source to Github site feeds, rather than full (rate-limited) API | define(["lib/reqwest", "lib/lodash", "lib/knockout", "githubEvent"],
function (reqwest, _, ko, GithubEvent) {
var githubApi = {};
var rootUrl = "https://api.github.com";
function getOrganisationMembers(orgName) {
return reqwest({
url: 'https://api.github.com/orgs/' + orgName + '/members',
type: 'json'
});
}
function getUserEvents(username) {
return reqwest({
url: 'https://github.com/' + username + '.json?callback=?',
method: 'get',
crossOrigin: true,
headers: { "Accept": "application/json" },
type: 'jsonp'
}).then(function (response) {
return _.map(response, function (response) {
return new GithubEvent(response);
});
});
}
// Returns a KO array which is then updated as data arrives
githubApi.getOrganisationEvents = function (orgName) {
var events = ko.observableArray([]);
var loading = 1;
getOrganisationMembers(orgName).then(function (members) {
loading = members.length;
_.each(members, function (member) {
getUserEvents(member.login).then(function (userEvents) {
events(events().concat(userEvents));
loading--;
});
});
});
events.loadingComplete = ko.computed(function () {
return loading === 0;
});
return events;
};
return githubApi;
}); | define(["lib/reqwest", "lib/lodash", "lib/knockout", "githubEvent"],
function (reqwest, _, ko, GithubEvent) {
var githubApi = {};
var rootUrl = "https://api.github.com";
function getOrganisationMembers(orgName) {
return reqwest({
url: rootUrl + '/orgs/' + orgName + '/members',
type: 'json'
});
}
function getUserEvents(username) {
return reqwest({
url: rootUrl + '/users/' + username + '/events',
type: 'json'
}).then(function (response) {
return _.map(response, function (response) {
return new GithubEvent(response);
});
});
}
// Returns a KO array which is then updated as data arrives
githubApi.getOrganisationEvents = function (orgName) {
var events = ko.observableArray([]);
var loading = 1;
getOrganisationMembers(orgName).then(function (members) {
loading = members.length;
_.each(members, function (member) {
getUserEvents(member.login).then(function (userEvents) {
events(events().concat(userEvents));
loading--;
});
});
});
events.loadingComplete = ko.computed(function () {
return loading === 0;
});
return events;
};
return githubApi;
}); |
Check for input types in methods | Categories = new Mongo.Collection('categories');
Schema.categories = new SimpleSchema({
name: {
type: String
},
slug: {
type: String,
index: true,
unique: true
},
description: {
type: String
},
position: {
type: Number
},
topicCount: {
type: Number,
defaultValue: 0
},
createdAt: {
type: Date,
defaultValue: new Date(),
denyUpdate: true
}
});
Categories.attachSchema(Schema.categories);
Categories.simpleSchema().messages({
notUnique: 'A duplicate slug exists.'
});
Meteor.methods({
createCategory: function (category) {
check(category, Object);
var maxPosition = Categories.find().count();
_.extend(category, {
slug: getSlug(category.name),
position: maxPosition + 1
});
var categoryId = Categories.insert(category);
return categoryId;
},
updateCategory: function (modifier, categoryId) {
check(modifier, Object);
check(categoryId, String);
var categoryName = modifier.$set.name;
// Generate a new slug
modifier.$set.slug = getSlug(categoryName);
Categories.update(categoryId, modifier);
var category = Categories.findOne(categoryId);
return category;
},
incrementTopicCount: function (categoryId) {
check(categoryId, String);
Categories.update(categoryId, {$inc: {topicCount: 1}});
},
removeCategory: function (categoryId) {
check(categoryId, String);
Categories.remove(categoryId);
//TODO: call removeTopic that removes topic and all its posts
Topics.remove({categoryId: categoryId});
}
});
| Categories = new Mongo.Collection('categories');
Schema.categories = new SimpleSchema({
name: {
type: String
},
slug: {
type: String,
index: true,
unique: true
},
description: {
type: String
},
position: {
type: Number
},
topicCount: {
type: Number,
defaultValue: 0
},
createdAt: {
type: Date,
defaultValue: new Date(),
denyUpdate: true
}
});
Categories.attachSchema(Schema.categories);
Categories.simpleSchema().messages({
notUnique: 'A duplicate slug exists.'
});
Meteor.methods({
createCategory: function (category) {
var maxPosition = Categories.find().count();
_.extend(category, {
slug: getSlug(category.name),
position: maxPosition + 1
});
var categoryId = Categories.insert(category);
return categoryId;
},
updateCategory: function (modifier, categoryId) {
var categoryName = modifier.$set.name;
// Generate a new slug
modifier.$set.slug = getSlug(categoryName);
Categories.update(categoryId, modifier);
var category = Categories.findOne(categoryId);
return category;
},
incrementTopicCount: function (categoryId) {
check(categoryId, String);
Categories.update(categoryId, {$inc: {topicCount: 1}});
},
removeCategory: function (categoryId) {
check(categoryId, String);
Categories.remove(categoryId);
//TODO: call removeTopic that removes topic and all its posts
Topics.remove({categoryId: categoryId});
}
});
|
Add flake8 static code testing | from __future__ import print_function
from setuptools import setup, find_packages
import sys
v = sys.version_info
if v[:2] < (3, 5):
error = "ERROR: jupyterhub-kubespawner requires Python version 3.5 or above."
print(error, file=sys.stderr)
sys.exit(1)
setup(
name='jupyterhub-kubespawner',
version='0.10.2.dev',
install_requires=[
'jupyterhub>=0.8',
'pyYAML',
'kubernetes>=7.0',
'escapism',
'jinja2',
'async_generator>=1.8',
],
python_requires='>=3.5',
extras_require={
'test': [
'flake8',
'pytest>=3.3',
'pytest-cov',
'pytest-asyncio',
]
},
description='JupyterHub Spawner for Kubernetes',
url='http://github.com/jupyterhub/kubespawner',
author='Jupyter Contributors',
author_email='[email protected]',
long_description=open("README.md").read(),
long_description_content_type="text/markdown",
license='BSD',
packages=find_packages(),
project_urls={
'Documentation': 'https://jupyterhub-kubespawner.readthedocs.io',
'Source': 'https://github.com/jupyterhub/kubespawner',
'Tracker': 'https://github.com/jupyterhub/kubespawner/issues',
},
)
| from __future__ import print_function
from setuptools import setup, find_packages
import sys
v = sys.version_info
if v[:2] < (3, 5):
error = "ERROR: jupyterhub-kubespawner requires Python version 3.5 or above."
print(error, file=sys.stderr)
sys.exit(1)
setup(
name='jupyterhub-kubespawner',
version='0.10.2.dev',
install_requires=[
'jupyterhub>=0.8',
'pyYAML',
'kubernetes>=7.0',
'escapism',
'jinja2',
'async_generator>=1.8',
],
python_requires='>=3.5',
extras_require={
'test': [
'pytest>=3.3',
'pytest-cov',
'pytest-asyncio',
]
},
description='JupyterHub Spawner for Kubernetes',
url='http://github.com/jupyterhub/kubespawner',
author='Jupyter Contributors',
author_email='[email protected]',
long_description=open("README.md").read(),
long_description_content_type="text/markdown",
license='BSD',
packages=find_packages(),
project_urls={
'Documentation': 'https://jupyterhub-kubespawner.readthedocs.io',
'Source': 'https://github.com/jupyterhub/kubespawner',
'Tracker': 'https://github.com/jupyterhub/kubespawner/issues',
},
)
|
Use commonprefix to break dep on 3.5 | import http.server
from threading import Thread
import os.path
class HTTPHandler:
def __init__(self, config):
self.config = config
handler = HTTPHandler.make_http_handler(self.config['media_dir'])
self.httpd = http.server.HTTPServer(('', self.config['media']['port']), handler)
self.thread = Thread(target=self.main_loop)
def run(self):
self.thread.start()
return self
def main_loop(self):
self.httpd.serve_forever()
@staticmethod
def make_http_handler(root_path):
class RelayGramHTTPHandler(http.server.BaseHTTPRequestHandler):
def __init__(self, *args, **kwargs):
super(RelayGramHTTPHandler, self).__init__(*args, **kwargs)
def do_GET(self):
file_path = os.path.abspath(root_path + self.path)
if os.path.commonprefix([root_path, file_path]) != os.path.abspath(root_path): # Detect path traversal attempt
self.send_error(501, "Nice try")
else:
if not os.path.exists(file_path) or not os.path.isfile(file_path):
self.send_error(404, 'File Not Found')
else:
self.send_response(200)
self.wfile.write(open(file_path, mode='rb').read())
return RelayGramHTTPHandler
| import http.server
from threading import Thread
import os.path
class HTTPHandler:
def __init__(self, config):
self.config = config
handler = HTTPHandler.make_http_handler(self.config['media_dir'])
self.httpd = http.server.HTTPServer(('', self.config['media']['port']), handler)
self.thread = Thread(target=self.main_loop)
def run(self):
self.thread.start()
return self
def main_loop(self):
self.httpd.serve_forever()
@staticmethod
def make_http_handler(root_path):
class RelayGramHTTPHandler(http.server.BaseHTTPRequestHandler):
def __init__(self, *args, **kwargs):
super(RelayGramHTTPHandler, self).__init__(*args, **kwargs)
def do_GET(self):
file_path = os.path.abspath(root_path + self.path)
if os.path.commonpath([root_path, file_path]) != os.path.abspath(root_path): # Detect path traversal attempt
self.send_error(501, "Nice try")
else:
if not os.path.exists(file_path) or not os.path.isfile(file_path):
self.send_error(404, 'File Not Found')
else:
self.send_response(200)
self.wfile.write(open(file_path, mode='rb').read())
return RelayGramHTTPHandler
|
Test for version strings in abilities. | var assert = require('assert');
require('./support/start')(function(command) {
exports['test abilities endpoint'] = function() {
assert.response(command.servers['Core'],
{ url: '/assets/tilemill/js/abilities.js' },
{ status: 200 },
function(res) {
var body = res.body.replace(/^\s*var\s+abilities\s*=\s*(.+?);?$/, '$1');
var abilities = JSON.parse(body);
assert.ok(/v\d+.\d+.\d+-\d+-[a-z0-9]+/.test(abilities.version[0]));
assert.ok(/\d+.\d+.\d+.\d+/.test(abilities.version[1]));
assert.ok(abilities.fonts.indexOf('Arial Regular') >= 0 ||
abilities.fonts.indexOf('DejaVu Sans Book') >= 0);
assert.deepEqual([0,206,209], abilities.carto.colors.darkturquoise);
assert.deepEqual([
"background-color",
"background-image",
"srs",
"buffer-size",
"base",
"paths-from-xml",
"minimum-version",
"font-directory"
], Object.keys(abilities.carto.symbolizers.map));
assert.deepEqual({
mbtiles: true,
png: true,
pdf: true,
svg: true
}, abilities.exports);
}
);
};
});
| var assert = require('assert');
require('./support/start')(function(command) {
exports['test abilities endpoint'] = function() {
assert.response(command.servers['Core'],
{ url: '/assets/tilemill/js/abilities.js' },
{ status: 200 },
function(res) {
var body = res.body.replace(/^\s*var\s+abilities\s*=\s*(.+?);?$/, '$1');
var abilities = JSON.parse(body);
assert.ok(abilities.fonts.indexOf('Arial Regular') >= 0 ||
abilities.fonts.indexOf('DejaVu Sans Book') >= 0);
assert.deepEqual([0,206,209], abilities.carto.colors.darkturquoise);
assert.deepEqual([
"background-color",
"background-image",
"srs",
"buffer-size",
"base",
"paths-from-xml",
"minimum-version",
"font-directory"
], Object.keys(abilities.carto.symbolizers.map));
assert.deepEqual({
mbtiles: true,
png: true,
pdf: true,
svg: true
}, abilities.exports);
}
);
};
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.