text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Use static methods for options | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package net.kirauks.minigames.engine.utils;
import javafx.scene.input.KeyCode;
/**
*
* @author Karl
*/
public class Options {
public static KeyCode getUpKey(){
return KeyCode.UP;
}
public static KeyCode getDownKey(){
return KeyCode.DOWN;
}
public static KeyCode getLeftKey(){
return KeyCode.LEFT;
}
public static KeyCode getRightKey(){
return KeyCode.RIGHT;
}
public static KeyCode getActionKey(){
return KeyCode.SPACE;
}
public static KeyCode getPauseKey(){
return KeyCode.ESCAPE;
}
}
| /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package net.kirauks.minigames.engine.utils;
import javafx.scene.input.KeyCode;
/**
*
* @author Karl
*/
public class Options {
public Options(){}
public KeyCode getUpKey(){
return KeyCode.UP;
}
public KeyCode getDownKey(){
return KeyCode.DOWN;
}
public KeyCode getLeftKey(){
return KeyCode.LEFT;
}
public KeyCode getRightKey(){
return KeyCode.RIGHT;
}
public KeyCode getActionKey(){
return KeyCode.SPACE;
}
public KeyCode getPauseKey(){
return KeyCode.ESCAPE;
}
}
|
Remove code that's no longer necessary with improved event handling | // ==========================================================================
// Project: Ember Handlebar Views
// Copyright: ©2011 Strobe Inc. and contributors.
// License: Licensed under MIT license (see license.js)
// ==========================================================================
require("ember-handlebars/ext");
require("ember-views/views/view");
var get = Ember.get, set = Ember.set;
/** @class */
Ember.TextSupport = Ember.Mixin.create(
/** @scope Ember.TextSupport.prototype */ {
value: "",
attributeBindings: ['placeholder', 'disabled'],
placeholder: null,
disabled: false,
insertNewline: Ember.K,
cancel: Ember.K,
focusOut: function(event) {
this._elementValueDidChange();
},
change: function(event) {
this._elementValueDidChange();
},
keyUp: function(event) {
this.interpretKeyEvents(event);
},
/**
@private
*/
interpretKeyEvents: function(event) {
var map = Ember.TextSupport.KEY_EVENTS;
var method = map[event.keyCode];
this._elementValueDidChange();
if (method) { return this[method](event); }
},
_elementValueDidChange: function() {
set(this, 'value', this.$().val());
}
});
Ember.TextSupport.KEY_EVENTS = {
13: 'insertNewline',
27: 'cancel'
};
| // ==========================================================================
// Project: Ember Handlebar Views
// Copyright: ©2011 Strobe Inc. and contributors.
// License: Licensed under MIT license (see license.js)
// ==========================================================================
require("ember-handlebars/ext");
require("ember-views/views/view");
var get = Ember.get, set = Ember.set;
/** @class */
Ember.TextSupport = Ember.Mixin.create(
/** @scope Ember.TextSupport.prototype */ {
value: "",
attributeBindings: ['placeholder', 'disabled'],
placeholder: null,
disabled: false,
insertNewline: Ember.K,
cancel: Ember.K,
focusOut: function(event) {
this._elementValueDidChange();
},
change: function(event) {
this._elementValueDidChange();
},
keyUp: function(event) {
this.interpretKeyEvents(event);
},
/**
@private
*/
interpretKeyEvents: function(event) {
var map = Ember.TextSupport.KEY_EVENTS;
var method = map[event.keyCode];
this._elementValueDidChange();
if (method) { return this[method](event); }
},
_elementValueDidChange: function() {
var element = this.$();
if (element.length) {
set(this, 'value', this.$().val());
} else {
// the element is receiving blur because it was
// removed, so don't do anything.
}
}
});
Ember.TextSupport.KEY_EVENTS = {
13: 'insertNewline',
27: 'cancel'
};
|
Add link to classification details from item details | import React from 'react'
import { connectFromRoute } from '../router-mapping'
import { sparqlConnect } from '../sparql/configure-sparql'
import { LOADING, LOADED, FAILED } from 'sparql-connect'
import Loading from './loading'
import { Link } from 'react-router'
import { uriToLink } from '../router-mapping'
import ItemChildren from './item-children'
function ItemDetails({ loaded, item, label, code, text, parent, parentCode,
parentLabel, cl, clCode, clLabel }) {
if (loaded !== LOADED) return <Loading from="Item details" plural={false} />
return (
<div>
<Link to={uriToLink.classificationDetails(cl)}>
{ clCode } - { clLabel }
</Link>
<h1>{code} - {label}</h1>
{ parent &&
<Link to={uriToLink.itemDetails(parent)}>
<span>↑ </span>{ parentCode } - { parentLabel }
</Link>
}
{ text && <div className="note">{text}</div> }
<hr/>
<ItemChildren item={item} />
</div>
)
}
export default connectFromRoute(sparqlConnect.itemDetails(ItemDetails)) | import React from 'react'
import { connectFromRoute } from '../router-mapping'
import { sparqlConnect } from '../sparql/configure-sparql'
import { LOADING, LOADED, FAILED } from 'sparql-connect'
import Loading from './loading'
import { Link } from 'react-router'
import { uriToLink } from '../router-mapping'
import ItemChildren from './item-children'
function ItemDetails({ loaded, item, label, code, text, parent, parentCode, parentLabel }) {
if (loaded !== LOADED) return <Loading from="Item details" plural={false} />
return (
<div>
<h1>{code} - {label}</h1>
{ parent &&
<Link to={uriToLink.itemDetails(parent)}>
{ parentCode } - { parentLabel }
</Link>
}
{ text && <div className="note">{text}</div> }
<hr/>
<ItemChildren item={item} />
</div>
)
}
export default connectFromRoute(sparqlConnect.itemDetails(ItemDetails)) |
Fix bug with http causing test failure | import HomeModule from './home';
describe('HomeModule', function() {
let element, scope;
beforeEach(angular.mock.module('app.home'));
beforeEach(angular.mock.inject(($rootScope, $compile, $httpBackend) => {
$httpBackend.whenGET("/api/plan/").respond([]);
scope = $rootScope.$new();
element = angular.element('<home></home>');
element = $compile(element)(scope);
$rootScope.$digest();
}));
it('should render into a home-container div', () => {
expect(element.find('div.home-container').length).to.exist;
});
it('should have a controller', () => {
expect(element.isolateScope().$ctrl).to.exist;
});
// this is not a meaningful test - it's serving as an example for now
it('should update its name if the name is updated', () => {
element.isolateScope().$ctrl.name = '';
element.isolateScope().$apply();
expect(element.find('h1').text()).to.equal('');
});
});
describe('HomeController', function() {
let HomeController;
beforeEach(angular.mock.module('app.home'));
beforeEach(angular.mock.inject(($componentController) => {
HomeController = $componentController('home', null, {});
}));
it ('should exist', () => {
expect(HomeController).to.exist;
});
});
| import HomeModule from './home';
describe('HomeModule', function() {
let element, scope;
beforeEach(angular.mock.module('app.home'));
beforeEach(angular.mock.inject(($rootScope, $compile) => {
scope = $rootScope.$new();
element = angular.element('<home></home>');
element = $compile(element)(scope);
$rootScope.$digest();
}));
it('should render into a home-container div', () => {
expect(element.find('div.home-container').length).to.equal(1);
});
it('should have a controller with a name property', () => {
expect(element.isolateScope().$ctrl).to.exist;
});
// this is not a meaningful test - it's serving as an example for now
it('should update its name if the name is updated', () => {
element.isolateScope().$ctrl.name = 'Hello world';
element.isolateScope().$apply();
expect(element.find('h1').text()).to.equal('Hello world');
});
});
describe('HomeController', function() {
let HomeController;
beforeEach(angular.mock.module('app.home'));
beforeEach(angular.mock.inject(($componentController) => {
HomeController = $componentController('home', null, {});
}));
it ('should be a component called home with a name property', () => {
expect(HomeController).to.exist;
});
});
|
Update SymPy/IPython version in test script | #!/usr/bin/env python
try:
import sympy
except ImportError:
print("sympy is required")
else:
if sympy.__version__ < '1.0':
print("SymPy version 1.0 or newer is required. You have", sympy.__version__)
if sympy.__version__ != '1.0':
print("The stable SymPy version 1.0 is recommended. You have", sympy.__version__)
try:
import matplotlib
except ImportError:
print("matplotlib is required for the plotting section of the tutorial")
try:
import IPython
except ImportError:
print("IPython notebook is required.")
else:
if IPython.__version__ < '4.1.2':
print("The latest version of IPython is recommended. You have", IPython.__version__)
print("""A fortran and/or C compiler is required for the code generation portion
of the tutorial. However, if you do not have one, you should not worry, as it
will not be a large part of the tutorial.""")
| #!/usr/bin/env python
try:
import sympy
except ImportError:
print("sympy is required")
else:
if sympy.__version__ < '0.7.5':
print("SymPy version 0.7.5 or newer is required. You have", sympy.__version__)
if sympy.__version__ != '0.7.5':
print("The stable SymPy version 0.7.5 is recommended. You have", sympy.__version__)
try:
import matplotlib
except ImportError:
print("matplotlib is required for the plotting section of the tutorial")
try:
import IPython
except ImportError:
print("IPython notebook is required.")
else:
if IPython.__version__ < '2.1.0':
print("The latest version of IPython is recommended. You have", IPython.__version__)
print("""A fortran and/or C compiler is required for the code generation portion
of the tutorial. However, if you do not have one, you should not worry, as it
will not be a large part of the tutorial.""")
|
Add secret key list unit test | package com.emc.ecs.managementClient;
import static org.junit.Assert.*;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.emc.ecs.serviceBroker.EcsManagementClientException;
import com.emc.ecs.serviceBroker.model.UserSecretKey;
public class ObjectUserSecretActionTest extends EcsActionTest {
private String user = "testuser2";
@Before
public void setUp() throws EcsManagementClientException {
connection.login();
ObjectUserAction.create(connection, user, namespace);
}
@After
public void cleanup() throws EcsManagementClientException {
ObjectUserAction.delete(connection, user);
connection.logout();
}
@Test
public void createUserSecretKey() throws EcsManagementClientException {
UserSecretKey secret = ObjectUserSecretAction.create(connection, user);
assertNotNull(secret.getSecretKey());
}
@Test
public void listUserSecretKey() throws EcsManagementClientException {
UserSecretKey secret = ObjectUserSecretAction.create(connection, user);
List<UserSecretKey> secretKeys = ObjectUserSecretAction.list(connection, user);
assertEquals(secret.getSecretKey(), secretKeys.get(0).getSecretKey());
}
}
| package com.emc.ecs.managementClient;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.emc.ecs.serviceBroker.EcsManagementClientException;
import com.emc.ecs.serviceBroker.model.UserSecretKey;
public class ObjectUserSecretActionTest extends EcsActionTest {
private String user = "testuser2";
@Before
public void setUp() throws EcsManagementClientException {
connection.login();
ObjectUserAction.create(connection, user, namespace);
}
@After
public void cleanup() throws EcsManagementClientException {
ObjectUserAction.delete(connection, user);
connection.logout();
}
@Test
public void createUserSecretKey() throws EcsManagementClientException {
UserSecretKey secret = ObjectUserSecretAction.create(connection, user);
assertNotNull(secret.getSecretKey());
}
}
|
Make part task creation explicit | from malcolm.core import Controller, DefaultStateMachine, Hook, \
method_only_in, method_takes
sm = DefaultStateMachine
@sm.insert
@method_takes()
class DefaultController(Controller):
Resetting = Hook()
Disabling = Hook()
@method_takes()
def disable(self):
try:
self.transition(sm.DISABLING, "Disabling")
self.run_hook(self.Disabling, self.create_part_tasks())
self.transition(sm.DISABLED, "Done Disabling")
except Exception as e: # pylint:disable=broad-except
self.log_exception("Fault occurred while Disabling")
self.transition(sm.FAULT, str(e))
raise
@method_only_in(sm.DISABLED, sm.FAULT)
def reset(self):
try:
self.transition(sm.RESETTING, "Resetting")
self.run_hook(self.Resetting, self.create_part_tasks())
self.transition(self.stateMachine.AFTER_RESETTING, "Done Resetting")
except Exception as e: # pylint:disable=broad-except
self.log_exception("Fault occurred while Resetting")
self.transition(sm.FAULT, str(e))
raise
| from malcolm.core import Controller, DefaultStateMachine, Hook, \
method_only_in, method_takes
sm = DefaultStateMachine
@sm.insert
@method_takes()
class DefaultController(Controller):
Resetting = Hook()
Disabling = Hook()
@method_takes()
def disable(self):
try:
self.transition(sm.DISABLING, "Disabling")
self.run_hook(self.Disabling)
self.transition(sm.DISABLED, "Done Disabling")
except Exception as e: # pylint:disable=broad-except
self.log_exception("Fault occurred while Disabling")
self.transition(sm.FAULT, str(e))
raise
@method_only_in(sm.DISABLED, sm.FAULT)
def reset(self):
try:
self.transition(sm.RESETTING, "Resetting")
self.run_hook(self.Resetting)
self.transition(sm.AFTER_RESETTING, "Done Resetting")
except Exception as e: # pylint:disable=broad-except
self.log_exception("Fault occurred while Resetting")
self.transition(sm.FAULT, str(e))
raise |
Update dsub version to 0.4.5
PiperOrigin-RevId: 393155372 | # Copyright 2017 Google Inc. All Rights Reserved.
#
# 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.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.4.5'
| # Copyright 2017 Google Inc. All Rights Reserved.
#
# 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.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.4.5.dev0'
|
Make ticks passable argument to data | # -*- coding: utf-8 -*-
from __future__ import division
import argparse
ansi_ticks = ('▁', '▂', '▃', '▄', '▅', '▆', '▇', '█')
def scale_data(data, ticks):
m = min(data)
n = (max(data) - m) / (len(ticks) - 1)
# if every element is the same height return all lower ticks, else compute
# the tick height
if n == 0:
return [ ticks[0] for t in data]
else:
return [ ticks[int((t - m) / n)] for t in data ]
def print_ansi_spark(d):
print ''.join(d)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Process numbers')
parser.add_argument('numbers', metavar='N', type=float, nargs='+',
help='series of data to plot')
args = parser.parse_args()
print_ansi_spark(scale_data(args.numbers, ansi_ticks))
| # -*- coding: utf-8 -*-
from __future__ import division
import argparse
ticks = ('▁', '▂', '▃', '▄', '▅', '▆', '▇', '█')
def scale_data(data):
m = min(data)
n = (max(data) - m) / (len(ticks) - 1)
# if every element is the same height return all lower ticks, else compute
# the tick height
if n == 0:
return [ ticks[0] for t in data]
else:
return [ ticks[int((t - m) / n)] for t in data ]
def print_ansi_spark(d):
print ''.join(d)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Process numbers')
parser.add_argument('numbers', metavar='N', type=float, nargs='+',
help='series of data to plot')
args = parser.parse_args()
print_ansi_spark(scale_data(args.numbers))
|
Add test task to Gulp default task. | const gulp = require('gulp');
const gutil = require('gulp-util');
const uglify = require('gulp-uglify');
const concat = require('gulp-concat');
const server = require('karma').Server;
gulp.task('concat', function() {
return gulp.src([
'./src/utils/globals.js',
'./src/utils/svg.js',
'./src/charts/classes.js'
])
.pipe(concat('proteus-charts.js'))
.pipe(gulp.dest('./dist/'));
});
gulp.task('minify', function() {
return gulp.src('./dist/es5/proteus-charts.js')
.pipe(uglify().on('error', gutil.log))
.pipe(gulp.dest('./min'));
});
gulp.task('test', function (done) {
new server({
configFile: __dirname + '/karma.conf.js',
singleRun: true
}, done).start();
});
gulp.task('default', ['test', 'concat', 'minify']); | const gulp = require('gulp');
const gutil = require('gulp-util');
const uglify = require('gulp-uglify');
const concat = require('gulp-concat');
const server = require('karma').Server;
gulp.task('concat', function() {
return gulp.src([
'./src/utils/globals.js',
'./src/utils/svg.js',
'./src/charts/classes.js'
])
.pipe(concat('proteus-charts.js'))
.pipe(gulp.dest('./dist/'));
});
gulp.task('minify', function() {
return gulp.src('./dist/es5/proteus-charts.js')
.pipe(uglify().on('error', gutil.log))
.pipe(gulp.dest('./min'));
});
gulp.task('test', function (done) {
new server({
configFile: __dirname + '/karma.conf.js',
singleRun: true
}, done).start();
});
gulp.task('default', ['concat', 'minify']); |
Add an intermediary build step to lib/ | 'use strict'
let gulp = require('gulp')
let connect = require('gulp-connect')
let sourcemaps = require('gulp-sourcemaps')
let browserify = require('browserify')
let babelify = require('babelify')
let babel = require('gulp-babel')
let gutil = require('gulp-util')
let source = require('vinyl-source-stream')
gulp.task('serve', () => {
connect.server({
root: '.',
livereload: true
})
})
gulp.task('es6', () => {
gulp.src(['src/list.jsx', 'src/list-item.jsx', 'src/index.js'])
.pipe(babel())
.pipe(gulp.dest('lib/'))
})
gulp.task('js', () => {
return browserify({
entries: 'src/index.js',
paths: ['src/', 'node_modules/'],
})
.transform(babelify)
.bundle()
.on('error', err => {
gutil.log(gutil.colors.red(err.message))
this.emit('end')
})
.pipe(source('list.js'))
.pipe(gulp.dest('dist/'))
.pipe(connect.reload())
})
gulp.task('watch', () => {
gulp.watch(['src/*'], ['js'])
})
gulp.task('build', ['js'])
gulp.task('default', ['watch', 'js', 'serve'])
| 'use strict'
let gulp = require('gulp')
let connect = require('gulp-connect')
let sourcemaps = require('gulp-sourcemaps')
let browserify = require('browserify')
let babelify = require('babelify')
let gutil = require('gulp-util')
let source = require('vinyl-source-stream')
gulp.task('serve', () => {
connect.server({
root: '.',
livereload: true
})
})
gulp.task('js', () => {
return browserify({
entries: 'src/test.jsx',
paths: ['src/', 'node_modules/'],
})
.transform(babelify)
.bundle()
.on('error', err => {
gutil.log(gutil.colors.red(err.message))
this.emit('end')
})
.pipe(source('list.js'))
.pipe(gulp.dest('dist/'))
.pipe(connect.reload())
})
gulp.task('watch', () => {
gulp.watch(['src/*'], ['js'])
})
gulp.task('build', ['js'])
gulp.task('default', ['watch', 'js', 'serve'])
|
Add counter for server http requests | package collector
import (
"fmt"
"strings"
"github.com/prometheus/client_golang/prometheus"
)
type SquidCounter struct {
Section string
Counter string
Description string
}
var squidCounters = []SquidCounter{
{"client_http", "requests", "The total number of client requests"},
{"client_http", "hits", "The total number of client cache hits"},
{"client_http", "errors", "The total number of client http errors"},
{"client_http", "kbytes_in", "The total number of client kbytes recevied"},
{"client_http", "kbytes_out", "The total number of client kbytes transfered"},
{"client_http", "hit_kbytes_out", "The total number of client kbytes cache hit"},
{"server.http", "requests", "The total number of server http requests"},
{"server.http", "errors", "The total number of server http errors"},
{"server.http", "kbytes_in", "The total number of server kbytes recevied"},
{"server.http", "kbytes_out", "The total number of server kbytes transfered"},
}
func generateSquidCounters() DescMap {
counters := DescMap{}
for i := range squidCounters {
counter := squidCounters[i]
counters[fmt.Sprintf("%s.%s", counter.Section, counter.Counter)] = prometheus.NewDesc(
prometheus.BuildFQName(namespace, strings.Replace(counter.Section, ".", "_", -1), counter.Counter),
counter.Description,
[]string{}, nil,
)
}
return counters
}
| package collector
import (
"fmt"
"github.com/prometheus/client_golang/prometheus"
)
type SquidCounter struct {
Section string
Counter string
Description string
}
var squidCounters = []SquidCounter{
{"client_http", "requests", "The total number of client requests"},
{"client_http", "hits", "The total number of client cache hits"},
{"client_http", "errors", "The total number of client http errors"},
{"client_http", "kbytes_in", "The total number of client kbytes recevied"},
{"client_http", "kbytes_out", "The total number of client kbytes transfered"},
{"client_http", "hit_kbytes_out", "The total number of client kbytes cache hit"},
}
func generateSquidCounters() DescMap {
counters := DescMap{}
for i := range squidCounters {
counter := squidCounters[i]
counters[fmt.Sprintf("%s.%s", counter.Section, counter.Counter)] = prometheus.NewDesc(
prometheus.BuildFQName(namespace, counter.Section, counter.Counter),
counter.Description,
[]string{}, nil,
)
}
return counters
}
|
Add IANA OID to file | #!/usr/bin/python
############################################################
#
# Copyright 2015 Interface Masters Technologies, Inc.
#
# Platform Driver for x86-64-im-n29xx-t40n-r0
#
############################################################
import os
import struct
import time
import subprocess
from onl.platform.base import *
from onl.vendor.imt import *
class OpenNetworkPlatformImplementation(OpenNetworkPlatformIMT):
def model(self):
# different IMT hw is supported by one image.
return 'IM29XX'
def platform(self):
return 'x86-64-im-n29xx-t40n-r0'
def _plat_info_dict(self):
return {
# TODO IMT: check how to improve this
# different IMT hw is supported by one image.
platinfo.LAG_COMPONENT_MAX : -1,
platinfo.PORT_COUNT : -1
}
def _plat_oid_table(self):
return None
def sys_oid_platform(self):
return ".30324.29"
def get_environment(self):
return "Not implemented."
if __name__ == "__main__":
import sys
p = OpenNetworkPlatformImplementation()
if len(sys.argv) == 1 or sys.argv[1] == 'info':
print p
elif sys.argv[1] == 'env':
print p.get_environment()
| #!/usr/bin/python
############################################################
#
# Copyright 2015 Interface Masters Technologies, Inc.
#
# Platform Driver for x86-64-im-n29xx-t40n-r0
#
############################################################
import os
import struct
import time
import subprocess
from onl.platform.base import *
from onl.vendor.imt import *
class OpenNetworkPlatformImplementation(OpenNetworkPlatformIMT):
def model(self):
# different IMT hw is supported by one image.
return 'IM29XX'
def platform(self):
return 'x86-64-im-n29xx-t40n-r0'
def _plat_info_dict(self):
return {
# TODO IMT: check how to improve this
# different IMT hw is supported by one image.
platinfo.LAG_COMPONENT_MAX : -1,
platinfo.PORT_COUNT : -1
}
def _plat_oid_table(self):
return None
def get_environment(self):
return "Not implemented."
if __name__ == "__main__":
import sys
p = OpenNetworkPlatformImplementation()
if len(sys.argv) == 1 or sys.argv[1] == 'info':
print p
elif sys.argv[1] == 'env':
print p.get_environment()
|
Update release link on public site. | <?php
/**
* the home page
*
* @package WordPress
* @subpackage Twenty_Eleven
*/
get_header(); ?>
<div id="primary">
<div id="content" class="home" role="main">
<img src="/public/wp-content/themes/muteswan/i/phone.png" />
<h2>Anonymous friends<br />trusted face-to-face.</h2>
<p>Create secure social networks using shared QR codes. Share them with whomever you trust, face-to-face.</p>
<a href="http://muteswan.org/releases/0.3alpha-release-3.apk" title="Download App">Download App</a><br />
<img src="/public/wp-content/themes/muteswan/i/get_it_on_play_logo_large.png" id="gplaybutton" alt="Available in Google Play" />
</div><!-- #content -->
<div style="clear: both;"> </div>
</div><!-- #primary -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
| <?php
/**
* the home page
*
* @package WordPress
* @subpackage Twenty_Eleven
*/
get_header(); ?>
<div id="primary">
<div id="content" class="home" role="main">
<img src="/public/wp-content/themes/muteswan/i/phone.png" />
<h2>Anonymous friends<br />trusted face-to-face.</h2>
<p>Create secure social networks using shared QR codes. Share them with whomever you trust, face-to-face.</p>
<a href="http://muteswan.org/releases/0.3alpha-release-1.apk" title="Download App">Download App</a><br />
<img src="/public/wp-content/themes/muteswan/i/get_it_on_play_logo_large.png" id="gplaybutton" alt="Available in Google Play" />
</div><!-- #content -->
<div style="clear: both;"> </div>
</div><!-- #primary -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
|
Use (not so) new processor class names | from galleries.models import Gallery, ImageModel
from django.db import models
from imagekit.models import ImageSpec
from imagekit.processors import ResizeToFit
class Photo(ImageModel):
thumbnail = ImageSpec([ResizeToFit(50, 50)])
full = ImageSpec([ResizeToFit(400, 200)])
caption = models.CharField(max_length=100)
class PortfolioImage(ImageModel):
thumbnail = ImageSpec([ResizeToFit(70, 40)])
class Video(models.Model):
title = models.CharField(max_length=50)
video = models.FileField(upload_to='galleries/video/video')
thumbnail = models.ImageField(upload_to='galleries/video/thumbnail', blank=True)
def __unicode__(self):
return self.title
class Meta:
ordering = ['title']
class PhotoAlbum(Gallery):
class GalleryMeta:
member_models = [Photo]
class Meta:
verbose_name = 'Photo Album'
class Portfolio(Gallery):
class GalleryMeta:
member_models = [Video]
membership_class = 'PortfolioMembership'
class PortfolioMembership(Portfolio.BaseMembership):
extra_field = models.CharField(max_length=10)
| from galleries.models import Gallery, ImageModel
from django.db import models
from imagekit.models import ImageSpec
from imagekit.processors.resize import Fit
class Photo(ImageModel):
thumbnail = ImageSpec([Fit(50, 50)])
full = ImageSpec([Fit(400, 200)])
caption = models.CharField(max_length=100)
class PortfolioImage(ImageModel):
thumbnail = ImageSpec([Fit(70, 40)])
class Video(models.Model):
title = models.CharField(max_length=50)
video = models.FileField(upload_to='galleries/video/video')
thumbnail = models.ImageField(upload_to='galleries/video/thumbnail', blank=True)
def __unicode__(self):
return self.title
class Meta:
ordering = ['title']
class PhotoAlbum(Gallery):
class GalleryMeta:
member_models = [Photo]
class Meta:
verbose_name = 'Photo Album'
class Portfolio(Gallery):
class GalleryMeta:
member_models = [Video]
membership_class = 'PortfolioMembership'
class PortfolioMembership(Portfolio.BaseMembership):
extra_field = models.CharField(max_length=10)
|
[Http] Check this commits description for more information
- sendRequest() and postRequest now have better error handling and display the error via console
- No longer toggles error on 403, instead it toggles everything but 200 | #
# http.py
# pyblox
#
# By Sanjay-B(Sanjay Bhadra)
# Copyright © 2017 Sanjay-B(Sanjay Bhadra). All rights reserved.
#
import json
import requests
class Http:
def sendRequest(url):
payload = requests.get(str(url))
statusCode = payload.status_code
header = payload.headers
content = payload.content
if statusCode is not 200:
return print("[Roblox][GET] Something went wrong. Error: "+statusCode)
return content
def postRequest(url,param1,param2):
payload = requests.post(str(url), data = {str(param1):str(param2)})
statusCode = payload.status_code
header = payload.headers
content = payload.content
if statusCode is not 200:
return print("[Roblox][POST] Something went wrong. Error: "+statusCode)
return content
| #
# http.py
# pyblox
#
# By Sanjay-B(Sanjay Bhadra)
# Copyright © 2017 Sanjay-B(Sanjay Bhadra). All rights reserved.
#
import json
import requests
class Http:
def sendRequest(url):
payload = requests.get(str(url))
statusCode = payload.status_code
header = payload.headers
content = payload.content
if statusCode == 403:
return print("[Roblox][GET] Something went wrong. Error: 403")
return content
def postRequest(url,param1,param2):
payload = requests.post(str(url), data = {str(param1):str(param2)})
statusCode = payload.status_code
header = payload.headers
content = payload.content
if statusCode == 403:
return print("[Roblox][POST] Something went wrong. Error: 403")
return content |
Update comment for importing deps | import $ from 'jquery';
import Router from './util/router';
import common from './routes/Common';
import home from './routes/Home';
import about_us from './routes/About';
// Import npm dependencies
import 'bootstrap/dist/js/umd/util.js';
import 'bootstrap/dist/js/umd/alert.js';
import 'bootstrap/dist/js/umd/button.js';
import 'bootstrap/dist/js/umd/carousel.js';
import 'bootstrap/dist/js/umd/collapse.js';
import 'bootstrap/dist/js/umd/dropdown.js';
import 'bootstrap/dist/js/umd/modal.js';
import 'bootstrap/dist/js/umd/scrollspy.js';
import 'bootstrap/dist/js/umd/tab.js';
import 'bootstrap/dist/js/umd/tooltip.js';
import 'bootstrap/dist/js/umd/popover.js';
// Use this variable to set up the common and page specific functions. If you
// rename this variable, you will also need to rename the namespace below.
const routes = {
// All pages
common,
// Home page
home,
// About us page, note the change from about-us to about_us.
about_us
};
// Load Events
$(document).ready(() => new Router(routes).loadEvents());
| import $ from 'jquery';
import Router from './util/router';
import common from './routes/Common';
import home from './routes/Home';
import about_us from './routes/About';
// Import Bootstrap
import 'bootstrap/dist/js/umd/util.js';
import 'bootstrap/dist/js/umd/alert.js';
import 'bootstrap/dist/js/umd/button.js';
import 'bootstrap/dist/js/umd/carousel.js';
import 'bootstrap/dist/js/umd/collapse.js';
import 'bootstrap/dist/js/umd/dropdown.js';
import 'bootstrap/dist/js/umd/modal.js';
import 'bootstrap/dist/js/umd/scrollspy.js';
import 'bootstrap/dist/js/umd/tab.js';
import 'bootstrap/dist/js/umd/tooltip.js';
import 'bootstrap/dist/js/umd/popover.js';
// Use this variable to set up the common and page specific functions. If you
// rename this variable, you will also need to rename the namespace below.
const routes = {
// All pages
common,
// Home page
home,
// About us page, note the change from about-us to about_us.
about_us
};
// Load Events
$(document).ready(() => new Router(routes).loadEvents());
|
Build script: Support specifying the output file | /**
* @license
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.
*/
var flags = {};
if ( process.argv.length > 2 ) {
process.argv[2].split(',').forEach(function(f) {
flags[f] = true;
});
}
var outfile = __dirname + '/../foam-bin.js';
if ( process.argv.length > 3 ) {
outfile = process.argv[3];
}
var env = {
FOAM_FILES: function(files) {
var payload = '';
files.filter(function(f) {
return f.flags ? flags[f.flags] : true;
}).map(function(f) {
return f.name;
}).forEach(function(f) {
var data = require('fs').readFileSync(__dirname + '/../src/' + f + '.js').toString();
payload += data;
});
require('fs').writeFileSync(outfile, payload);
}
};
var data = require('fs').readFileSync(__dirname + '/../src/files.js');
with (env) { eval(data.toString()); }
| /**
* @license
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.
*/
var flags = {};
if ( process.argv.length > 2 ) {
process.argv[2].split(',').forEach(function(f) {
flags[f] = true;
});
}
var env = {
FOAM_FILES: function(files) {
var payload = '';
files.filter(function(f) {
return f.flags ? flags[f.flags] : true;
}).map(function(f) {
return f.name;
}).forEach(function(f) {
var data = require('fs').readFileSync(__dirname + '/../src/' + f + '.js').toString();
payload += data;
});
require('fs').writeFileSync(__dirname + '/../foam-bin.js', payload);
}
};
var data = require('fs').readFileSync(__dirname + '/../src/files.js');
with (env) { eval(data.toString()); }
|
Apply Tonya's suggestion for pointer styling.
Fix issue where pointer didn't appear alongside the AMP menu item.
Uses the show function, as Tonya suggested. | /**
* Adds an admin pointer that describes new features in 1.0.
*/
/* exported ampAdminPointer */
/* global ajaxurl, jQuery */
var ampAdminPointer = ( function( $ ) { // eslint-disable-line no-unused-vars
'use strict';
return {
/**
* Loads the pointer.
*
* @param {Object} data - Module data.
* @return {void}
*/
load: function load( data ) {
var options = $.extend(
data.pointer.options,
{
/**
* Makes a POST request to store the pointer ID as dismissed for this user.
*/
close: function() {
$.post( ajaxurl, {
pointer: data.pointer.pointer_id,
action: 'dismiss-wp-pointer'
} );
},
/**
* Adds styling to the pointer, to ensure it appears alongside the AMP menu.
*
* @param {Object} event The pointer event.
* @param {Object} t Pointer element and state.
*/
show: function( event, t ) {
t.pointer.css( 'position', 'fixed' );
}
}
);
$( data.pointer.target ).pointer( options ).pointer( 'open' );
}
};
}( jQuery ) );
| /**
* Adds an admin pointer that describes new features in 1.0.
*/
/* exported ampAdminPointer */
/* global ajaxurl, jQuery */
var ampAdminPointer = ( function( $ ) { // eslint-disable-line no-unused-vars
'use strict';
return {
/**
* Loads the pointer.
*
* @param {Object} data - Module data.
* @return {void}
*/
load: function load( data ) {
var options = $.extend(
data.pointer.options,
{
/**
* Makes a POST request to store the pointer ID as dismissed for this user.
*/
close: function() {
$.post( ajaxurl, {
pointer: data.pointer.pointer_id,
action: 'dismiss-wp-pointer'
} );
}
}
);
$( data.pointer.target ).pointer( options ).pointer( 'open' );
}
};
}( jQuery ) );
|
Test Affine init calls hooks correctly, and sets descriptors | # encoding: utf8
from __future__ import unicode_literals
import pytest
from mock import Mock, patch
from hypothesis import given, strategies
import abc
from ...._classes.affine import Affine
from ....ops import NumpyOps
@pytest.fixture
def model():
orig_desc = dict(Affine.descriptions)
orig_on_init = list(Affine.on_init_hooks)
Affine.descriptions = {
name: Mock(desc) for (name, desc) in Affine.descriptions.items()
}
Affine.on_init_hooks = [Mock(hook) for hook in Affine.on_init_hooks]
model = Affine()
for attr in model.descriptions:
setattr(model, attr, None)
Affine.descriptions = dict(orig_desc)
Affine.on_init_hooks = orig_on_init
return model
def test_Affine_default_name(model):
assert model.name == 'affine'
def test_Affine_calls_default_descriptions(model):
assert len(model.descriptions) == 5
for name, desc in model.descriptions.items():
desc.assert_called()
assert 'nB' in model.descriptions
assert 'nI' in model.descriptions
assert 'nO' in model.descriptions
assert 'W' in model.descriptions
assert 'b' in model.descriptions
def test_Affine_calls_init_hooks(model):
for hook in model.on_init_hooks:
hook.assert_called()
| # encoding: utf8
from __future__ import unicode_literals
import pytest
from flexmock import flexmock
from hypothesis import given, strategies
import abc
from .... import vec2vec
from ....ops import NumpyOps
@pytest.fixture
def model_with_no_args():
model = vec2vec.Affine(ops=NumpyOps())
return model
def test_Affine_default_name(model_with_no_args):
assert model_with_no_args.name == 'affine'
def test_Affine_defaults_to_cpu(model_with_no_args):
assert isinstance(model_with_no_args.ops, NumpyOps)
def test_Affine_defaults_to_no_layers(model_with_no_args):
assert model_with_no_args.layers == []
def test_Affine_defaults_to_param_descriptions(model_with_no_args):
W_desc, b_desc = model_with_no_args.describe_params
xavier_init = model_with_no_args.ops.xavier_uniform_init
assert W_desc == ('W-affine', (None, None), xavier_init)
assert b_desc == ('b-affine', (None,), None)
def test_Model_defaults_to_no_output_shape(model_with_no_args):
assert model_with_no_args.output_shape == None
def test_Model_defaults_to_no_input_shape(model_with_no_args):
assert model_with_no_args.input_shape == None
def test_Model_defaults_to_0_size(model_with_no_args):
assert model_with_no_args.size == None
|
Add names to Parameters/Variables to surpress DepricationWarnings | from __future__ import division
import sympy
from symfit import Variable, Parameter
from symfit.distributions import Gaussian, Exp
def test_gaussian():
"""
Make sure that symfit.distributions.Gaussians produces the expected
sympy expression.
"""
x0 = Parameter('x0')
sig = Parameter('sig', positive=True)
x = Variable('x')
new = sympy.exp(-(x - x0)**2/(2*sig**2))/sympy.sqrt((2*sympy.pi*sig**2))
assert isinstance(new, sympy.Expr)
g = Gaussian(x, x0, sig)
assert issubclass(g.__class__, sympy.Expr)
assert new == g
# A pdf should always integrate to 1 on its domain
assert sympy.integrate(g, (x, -sympy.oo, sympy.oo)) == 1
def test_exp():
"""
Make sure that symfit.distributions.Exp produces the expected
sympy expression.
"""
l = Parameter('l', positive=True)
x = Variable('x')
new = l * sympy.exp(- l * x)
assert isinstance(new, sympy.Expr)
e = Exp(x, l)
assert issubclass(e.__class__, sympy.Expr)
assert new == e
# A pdf should always integrate to 1 on its domain
assert sympy.integrate(e, (x, 0, sympy.oo)) == 1
| from __future__ import division
import sympy
from symfit import Variable, Parameter
from symfit.distributions import Gaussian, Exp
def test_gaussian():
"""
Make sure that symfit.distributions.Gaussians produces the expected
sympy expression.
"""
x0 = Parameter()
sig = Parameter(positive=True)
x = Variable()
new = sympy.exp(-(x - x0)**2/(2*sig**2))/sympy.sqrt((2*sympy.pi*sig**2))
assert isinstance(new, sympy.Expr)
g = Gaussian(x, x0, sig)
assert issubclass(g.__class__, sympy.Expr)
assert new == g
# A pdf should always integrate to 1 on its domain
assert sympy.integrate(g, (x, -sympy.oo, sympy.oo)) == 1
def test_exp():
"""
Make sure that symfit.distributions.Exp produces the expected
sympy expression.
"""
l = Parameter(positive=True)
x = Variable()
new = l * sympy.exp(- l * x)
assert isinstance(new, sympy.Expr)
e = Exp(x, l)
assert issubclass(e.__class__, sympy.Expr)
assert new == e
# A pdf should always integrate to 1 on its domain
assert sympy.integrate(e, (x, 0, sympy.oo)) == 1
|
Use Guido's trick for always extracting the version number from a
CVS Revision string correctly, even under -kv. | """Core XML support for Python.
This package contains three sub-packages:
dom -- The W3C Document Object Model. This supports DOM Level 1 +
Namespaces.
parsers -- Python wrappers for XML parsers (currently only supports Expat).
sax -- The Simple API for XML, developed by XML-Dev, led by David
Megginson and ported to Python by Lars Marius Garshol. This
supports the SAX 2 API.
"""
__all__ = ["dom", "parsers", "sax"]
# When being checked-out without options, this has the form
# "<dollar>Revision: x.y </dollar>"
# When exported using -kv, it is "x.y".
__version__ = "$Revision$".split()[-2][0]
_MINIMUM_XMLPLUS_VERSION = (0, 6, 1)
try:
import _xmlplus
except ImportError:
pass
else:
try:
v = _xmlplus.version_info
except AttributeError:
# _xmlplue is too old; ignore it
pass
else:
if v >= _MINIMUM_XMLPLUS_VERSION:
import sys
sys.modules[__name__] = _xmlplus
else:
del v
| """Core XML support for Python.
This package contains three sub-packages:
dom -- The W3C Document Object Model. This supports DOM Level 1 +
Namespaces.
parsers -- Python wrappers for XML parsers (currently only supports Expat).
sax -- The Simple API for XML, developed by XML-Dev, led by David
Megginson and ported to Python by Lars Marius Garshol. This
supports the SAX 2 API.
"""
__all__ = ["dom", "parsers", "sax"]
__version__ = "$Revision$".split()[1]
_MINIMUM_XMLPLUS_VERSION = (0, 6, 1)
try:
import _xmlplus
except ImportError:
pass
else:
try:
v = _xmlplus.version_info
except AttributeError:
# _xmlplue is too old; ignore it
pass
else:
if v >= _MINIMUM_XMLPLUS_VERSION:
import sys
sys.modules[__name__] = _xmlplus
else:
del v
|
Add sourceMap in node-sass-middleware for dev | 'use strict';
const express = require('express'),
sassMiddleware = require('node-sass-middleware'),
webpack = require('webpack'),
webpackMiddleware = require('webpack-dev-middleware'),
path = require('path'),
app = express(),
default_port = (process.env.PORT || 3000);
app.use(sassMiddleware({
src: path.join(__dirname, 'sass'),
dest: path.join(__dirname, 'dist'),
debug: true,
outputStyle: 'nested',
sourceMap: path.join(__dirname, 'dist', 'bundle.css.map')
}));
app.use(webpackMiddleware(webpack(require('./webpack.config')), {
noInfo: false,
quiet: false,
lazy: true,
publicPath: "/",
stats: {
colors: true
}
}));
app.use(express.static(path.join(__dirname, 'dist')));
app.use(require('connect-livereload')()); // runs livereload server and serves livereload.js
require('express-livereload')(app, { watchDir: path.join(__dirname) }); // inserts <script> reference to livereload.js
app.use('/', express.static(path.join(__dirname, 'views')));
let server = app.listen(default_port, function () {
let port = server.address().port;
console.log('Listening on port ' + port);
});
| 'use strict';
const express = require('express'),
sassMiddleware = require('node-sass-middleware'),
webpack = require('webpack'),
webpackMiddleware = require('webpack-dev-middleware'),
path = require('path'),
app = express(),
default_port = (process.env.PORT || 3000);
app.use(sassMiddleware({
src: path.join(__dirname, 'sass'),
dest: path.join(__dirname, 'dist'),
debug: true,
outputStyle: 'nested'
}));
app.use(webpackMiddleware(webpack(require('./webpack.config')), {
noInfo: false,
quiet: false,
lazy: true,
publicPath: "/",
stats: {
colors: true
}
}));
app.use(express.static(path.join(__dirname, 'dist')));
app.use(require('connect-livereload')()); // runs livereload server and serves livereload.js
require('express-livereload')(app, { watchDir: path.join(__dirname) }); // inserts <script> reference to livereload.js
app.use('/', express.static(path.join(__dirname, 'views')));
let server = app.listen(default_port, function () {
let port = server.address().port;
console.log('Listening on port ' + port);
});
|
Fix typo and cleanup formatting. | <?php
return array(
/*
|--------------------------------------------------------------------------
| Laravel CORS Defaults
|--------------------------------------------------------------------------
|
| The defaults are the default values applied to all the paths that match,
| unless overridden in a specific URL configuration.
| If you want them to apply to everything, you must define a path with ^/.
|
| allow_origin and allow_headers can be set to * to accept any value,
| the allowed methods however have to be explicitly listed.
|
*/
'defaults' => array(
'allow_credentials' => false,
'allow_origin' => array(),
'allow_headers' => array(),
'allow_methods' => array(),
'expose_headers' => array(),
'max_age' => 0,
),
'paths' => array(
'^/api/' => array(
'allow_origin' => array('*'),
'allow_headers' => array('Content-Type'),
'allow_methods' => array('POST', 'PUT', 'GET', 'DELETE'),
'max_age' => 3600,
),
),
);
| <?php
return array(
/*
|--------------------------------------------------------------------------
| Laravel CORS Defaults
|--------------------------------------------------------------------------
|
| The defaults are the default values applied to all the paths that match,
| unless overriden in a specific URL configuration.
| If you want them to apply to everything, you must define a path with ^/.
|
| allow_origin and allow_headers can be set to * to accept any value,
| the allowed methods however have to be explicitly listed.
|
*/
'defaults' => array(
'allow_credentials' => false,
'allow_origin'=> array(),
'allow_headers'=> array(),
'allow_methods'=> array(),
'expose_headers'=> array(),
'max_age' => 0
),
'paths' => array(
'^/api/' => array(
'allow_origin'=> array('*'),
'allow_headers'=> array('Content-Type'),
'allow_methods'=> array('POST', 'PUT', 'GET', 'DELETE'),
'max_age' => 3600
)
),
);
|
Fix odometer spacing on smaller screen sizes | import React from 'react'
import { PropTypes } from 'prop-types'
import Odometer from 'react-odometerjs'
import Col from 'react-bootstrap/lib/Col'
export default class Stat extends React.PureComponent {
static propTypes = {
title: PropTypes.string.isRequired,
value: PropTypes.any.isRequired,
emoji: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
prefix: PropTypes.string,
format: PropTypes.string
}
static defaultProps = {
prefix: ''
}
render () {
return (
<Col lg={4} md={6} xs={12} className='stat'>
<span className='current_header'>{this.props.title}:</span>
<div className='odometer-group'>
<div style={{minWidth: 60, textAlign: 'right'}}>
{this.props.prefix}
{this.props.value === 0
? <span style={{paddingRight: 5}}>0</span>
: (<Odometer value={this.props.value} options={{format: this.props.format}} />)}
</div>
<div className='emoji'>{this.props.emoji}</div>
</div>
</Col>
)
}
}
| import React from 'react'
import { PropTypes } from 'prop-types'
import Odometer from 'react-odometerjs'
import Col from 'react-bootstrap/lib/Col'
export default class Stat extends React.PureComponent {
static propTypes = {
title: PropTypes.string.isRequired,
value: PropTypes.any.isRequired,
emoji: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
prefix: PropTypes.string,
format: PropTypes.string
}
static defaultProps = {
prefix: ''
}
render () {
return (
<Col lg={4} md={6} xs={12} className='stat'>
<span className='current_header'>{this.props.title}:</span>
<div className='odometer-group'>
{this.props.prefix}
{this.props.value === 0
? <span style={{paddingRight: 5}}>0</span>
: <Odometer value={this.props.value} options={{format: this.props.format}} />}
<div className='emoji'>{this.props.emoji}</div>
</div>
</Col>
)
}
}
|
Add functions for NICK and USER sending. Override sendMessage for debugging. | from twisted.words.protocols import irc
class HeufyBotConnection(irc.IRC):
def __init__(self, protocol):
self.protocol = protocol
self.nickname = "PyHeufyBot" #TODO This will be set by a configuration at some point
self.ident = "PyHeufyBot" #TODO This will be set by a configuration at some point
self.gecos = "PyHeufyBot IRC Bot" #TODO This will be set by a configuration at some point
def connectionMade(self):
self.cmdNICK(self.nickname)
self.cmdUSER(self.ident, self.gecos)
def connectionLost(self, reason=""):
print reason
def dataReceived(self, data):
print data
def sendMessage(self, command, *parameter_list, **prefix):
print command, " ".join(parameter_list)
irc.IRC.sendMessage(self, command, *parameter_list, **prefix)
def cmdNICK(self, nickname):
self.sendMessage("NICK", nickname)
def cmdUSER(self, ident, gecos):
# RFC2812 allows usermodes to be set, but this isn't implemented much in IRCds at all.
# Pass 0 for usermodes instead.
self.sendMessage("USER", ident, "0", "*", ":{}".format(gecos)) | from twisted.words.protocols import irc
class HeufyBotConnection(irc.IRC):
def __init__(self, protocol):
self.protocol = protocol
self.nickname = "PyHeufyBot" #TODO This will be set by a configuration at some point
self.ident = "PyHeufyBot" #TODO This will be set by a configuration at some point
self.gecos = "PyHeufyBot IRC Bot" #TODO This will be set by a configuration at some point
def connectionMade(self):
self.sendMessage("NICK", "PyHeufyBot")
self.sendMessage("USER", "PyHeufyBot", "0", "0", ":PyHeufyBot Bot")
print "OK"
def connectionLost(self, reason=""):
print reason
def dataReceived(self, data):
print data |
Add given / when / them | var http = require('http');
var q = require('q');
var request = require('request');
describe('HTTP', function() {
var encode = function(command) {
var host = 'http://localhost:13000/testSelector';
return host + '?popupInput=' + encodeURIComponent(command);
};
var callElementor = function(command) {
var deferred = q.defer();
var url = encode(command);
request(url, function(error, response, body) {
if (error) {
console.log("Got error: " + error);
return deferred.reject(error);
}
deferred.resolve(JSON.parse(body));
});
return deferred.promise;
};
it('should navigate to protractor website', function(done) {
var url = 'browser.get(\'http://angular.github.io/protractor/#/api\')';
// Given that you navigate to the protractor website.
callElementor(url).then(function(response) {
// When you get the current URL.
return callElementor('browser.getCurrentUrl()');
}).then(function(response) {
// Then ensure the URL has changed.
expect(response).toEqual({
results: {
'browser.getCurrentUrl()': 'http://angular.github.io/protractor/#/api'
}
});
done();
});
});
})
;
| var http = require('http');
var q = require('q');
var request = require('request');
describe('HTTP', function() {
var encode = function(command) {
var host = 'http://localhost:13000/testSelector';
return host + '?popupInput=' + encodeURIComponent(command);
};
var callElementor = function(command) {
var deferred = q.defer();
var url = encode(command);
request(url, function(error, response, body) {
if (error) {
console.log("Got error: " + error);
return deferred.reject(error);
}
deferred.resolve(JSON.parse(body));
});
return deferred.promise;
};
it('should navigate to protractor website', function(done) {
var url = 'browser.get(\'http://angular.github.io/protractor/#/api\')';
callElementor(url).then(function(response) {
expect(response).toEqual({
results: {
'browser.get(\'http://angular.github.io/protractor/#/api\')': null
}
});
return callElementor('browser.getCurrentUrl()');
}).then(function(response) {
expect(response).toEqual({
results: {
'browser.getCurrentUrl()': 'http://angular.github.io/protractor/#/api'
}
});
done();
});
});
})
;
|
Add link to gnu coreutils | #!/usr/bin/env python
from genes.posix.traits import only_posix
from genes.process.commands import run
@only_posix()
def chgrp(path, group):
run(['chgrp', group, path])
@only_posix()
def chown(path, user):
run(['chown', user, path])
@only_posix()
def groupadd(*args):
run(['groupadd'] + list(*args))
@only_posix()
def ln(*args):
run(['ln'] + list(*args))
@only_posix()
def mkdir(path, mode=None):
if mode:
run(['mkdir', '-m', mode, path])
else:
run(['mkdir', path])
@only_posix()
def useradd(*args):
# FIXME: this is a bad way to do things
# FIXME: sigh. this is going to be a pain to make it idempotent
run(['useradd'] + list(*args))
@only_posix()
def usermod(*args):
# FIXME: this is a bad way to do things
run(['usermod'] + list(*args))
| #!/usr/bin/env python
from genes.posix.traits import only_posix
from genes.process.commands import run
@only_posix()
def chgrp(path, group):
run(['chgrp', group, path])
@only_posix()
def chown(path, user):
run(['chown', user, path])
@only_posix()
def groupadd(*args):
run(['groupadd'] + list(*args))
@only_posix()
def mkdir(path, mode=None):
if mode:
run(['mkdir', '-m', mode, path])
else:
run(['mkdir', path])
@only_posix()
def useradd(*args):
# FIXME: this is a bad way to do things
# FIXME: sigh. this is going to be a pain to make it idempotent
run(['useradd'] + list(*args))
@only_posix()
def usermod(*args):
# FIXME: this is a bad way to do things
run(['usermod'] + list(*args))
|
Use UUID with cookie checker | package middleware
import (
"github.com/labstack/echo"
"strings"
"net/http"
"log"
)
func ServerInfo(pipe echo.HandlerFunc) echo.HandlerFunc{
return func (c echo.Context) error{
c.Response().Header().Set(echo.HeaderServer, "GoChat/1.0")
c.Response().Header().Set("Author", "Ethan Garnier")
return pipe(c)
}
}
func checkCookies (pipe echo.HandlerFunc) echo.HandlerFunc{
return func (c echo.Context) error{
cookie, err := c.Cookie("session_id")
if err != nil{
if strings.Contains(err.Error(), "named cookie not present"){
return c.String(http.StatusUnauthorized, "Seems like the cookie monster was here..\n You do not have any cookies")
}
log.Printf("Error: %v \n", err)
return err
}
//Need to add the ability to read a users cookie value
if cookie.Value == "cookie_value"{
return pipe(c)
}
return c.String(http.StatusUnauthorized, "You do not have the correct cookie")
}
} | package middleware
import (
"github.com/labstack/echo"
"strings"
"net/http"
"log"
)
func ServerInfo(pipe echo.HandlerFunc) echo.HandlerFunc{
return func (c echo.Context) error{
c.Response().Header().Set(echo.HeaderServer, "GoChat/1.0")
c.Response().Header().Set("Author", "Ethan Garnier")
return pipe(c)
}
}
func checkCookies (pipe echo.HandlerFunc) echo.HandlerFunc{
return func (c echo.Context) error{
cookie, err := c.Cookie("session_id")
if err != nil{
if strings.Contains(err.Error(), "named cookie not present"){
return c.String(http.StatusUnauthorized, "Seems like the cookie monster was here..\n You do not have any cookies")
}
log.Printf("Error: %v \n", err)
return err
}
if cookie.Value == "cookie_value"{
return pipe(c)
}
return c.String(http.StatusUnauthorized, "You do not have the correct cookie")
}
} |
Change port number to 9001 | 'use strict';
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var memos = require('./routes/memos');
var http = require('http');
var path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 9001);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
// app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' === app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/memos/*', memos.list);
app.get('/memos', memos.list);
app.get('/files/*', memos.get);
var server = http.createServer(app);
server.listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
var io = require('socket.io').listen(server, {'log level': 0});
memos.start(io);
| 'use strict';
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var memos = require('./routes/memos');
var http = require('http');
var path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 8000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
// app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' === app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/memos/*', memos.list);
app.get('/memos', memos.list);
app.get('/files/*', memos.get);
var server = http.createServer(app);
server.listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
var io = require('socket.io').listen(server, {'log level': 0});
memos.start(io);
|
Allow the USB index to be modified | import logging
# import picamera
# import picamera.array
from abc import ABCMeta, abstractmethod
import cv2
LOG = logging.getLogger(__name__)
class Camera(metaclass=ABCMeta):
@abstractmethod
def frame_generator(self):
raise NotImplementedError('Not yet implemented')
class USBCam(Camera):
def __init__(self, index=-1):
self.index = index
def frame_generator(self):
video = cv2.VideoCapture(self.index)
if not video.isOpened():
raise Exception('Unable to open camera')
while True:
success, image = video.read()
yield image
video.release()
class PiCamera(Camera):
def frame_generator(self):
with picamera.PiCamera() as camera:
with picamera.array.PiRGBArray(camera) as output:
camera.resolution = (640, 480)
camera.framerate = 32
while True:
camera.capture(output, 'rgb', use_video_port=True)
yield output.array
output.truncate(0)
| import logging
# import picamera
# import picamera.array
from abc import ABCMeta, abstractmethod
import cv2
LOG = logging.getLogger(__name__)
class Camera(metaclass=ABCMeta):
@abstractmethod
def frame_generator(self):
raise NotImplementedError('Not yet implemented')
class USBCam(Camera):
def frame_generator(self):
video = cv2.VideoCapture(1)
if not video.isOpened():
raise Exception('Unable to open camera')
while True:
success, image = video.read()
yield image
video.release()
class PiCamera(Camera):
def frame_generator(self):
with picamera.PiCamera() as camera:
with picamera.array.PiRGBArray(camera) as output:
camera.resolution = (640, 480)
camera.framerate = 32
while True:
camera.capture(output, 'rgb', use_video_port=True)
yield output.array
output.truncate(0)
|
Change the name to be a unique index.
- this is bad practice, I should have migrated it properly.
- Also, the reason I'm doing this is to make sure we don't duplicate X&Y.
- This is just a bad way of doing this all around, but it's cheap.
- right now cheap is good (given the time constraint) | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCityTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('cities', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->integer('X');
$table->integer('Y');
$table->string('name')->unique();
$table->index('X');
$table->index('Y');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('cities');
}
}
| <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCityTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('cities', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->integer('X');
$table->integer('Y');
$table->string('name')->nullable();
$table->index('X');
$table->index('Y');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('cities');
}
}
|
Refactor code to fix coverage | <?php
namespace Cs278\BankModulus;
use Cs278\BankModulus\BankAccountNormalizer\CoOperativeBankNormalizer;
use Cs278\BankModulus\BankAccountNormalizer\NatWestNormalizer;
use Cs278\BankModulus\BankAccountNormalizer\SantanderNormalizer;
use Cs278\BankModulus\BankAccountNormalizer\SevenDigitNormalizer;
use Cs278\BankModulus\BankAccountNormalizer\SixDigitNormalizer;
final class BankAccountNormalizer
{
private $normalizers = [];
public function __construct(array $normalizers = null)
{
if (null === $normalizers) {
$normalizers = [
new SixDigitNormalizer(),
new SevenDigitNormalizer(),
new SantanderNormalizer(),
new NatWestNormalizer(),
new CoOperativeBankNormalizer(),
];
}
$this->normalizers = $normalizers;
}
public function apply(BankAccountInterface $bankAccount)
{
foreach ($this->normalizers as $normalizer) {
if ($normalizer->supports($bankAccount)) {
return $normalizer->normalize($bankAccount);
}
}
return BankAccountNormalized::createFromBankAccount($bankAccount);
}
}
| <?php
namespace Cs278\BankModulus;
use Cs278\BankModulus\BankAccountNormalizer\CoOperativeBankNormalizer;
use Cs278\BankModulus\BankAccountNormalizer\NatWestNormalizer;
use Cs278\BankModulus\BankAccountNormalizer\SantanderNormalizer;
use Cs278\BankModulus\BankAccountNormalizer\SevenDigitNormalizer;
use Cs278\BankModulus\BankAccountNormalizer\SixDigitNormalizer;
final class BankAccountNormalizer
{
private $normalizers;
public function __construct(array $normalizers = null)
{
$this->normalizers = null !== $normalizers
? $normalizers
: [
new SixDigitNormalizer(),
new SevenDigitNormalizer(),
new SantanderNormalizer(),
new NatWestNormalizer(),
new CoOperativeBankNormalizer(),
];
}
public function apply(BankAccountInterface $bankAccount)
{
foreach ($this->normalizers as $normalizer) {
if ($normalizer->supports($bankAccount)) {
return $normalizer->normalize($bankAccount);
}
}
return BankAccountNormalized::createFromBankAccount($bankAccount);
}
}
|
Maintain laravel database path for sqlite. | <?php namespace Mitch\LaravelDoctrine\Configuration;
class SqliteMapper implements Mapper
{
/**
* Map the L4 configuration array to a sqlite-friendly doctrine configuration.
*
* @param array $configuration
* @return array
*/
public function map(array $configuration)
{
$sqliteConfig = [
'driver' => 'pdo_sqlite',
'user' => @$configuration['username'],
'password' => @$configuration['password']
];
$this->databaseLocation($configuration, $sqliteConfig);
return $sqliteConfig;
}
/**
* Is only suitable for sqlite configuration mapping.
*
* @param array $configuration
* @return bool
*/
public function isAppropriateFor(array $configuration)
{
return $configuration['driver'] == 'sqlite';
}
/**
* Determines the location of the database and appends this to the sqlite configuration.
*
* @param $configuration
* @param $sqliteConfig
*/
private function databaseLocation($configuration, &$sqliteConfig)
{
if ($configuration['database'] == ':memory:')
$sqliteConfig['memory'] = true;
else
$sqliteConfig['path'] = $configuration['database'];
}
}
| <?php namespace Mitch\LaravelDoctrine\Configuration;
class SqliteMapper implements Mapper
{
/**
* Map the L4 configuration array to a sqlite-friendly doctrine configuration.
*
* @param array $configuration
* @return array
*/
public function map(array $configuration)
{
$sqliteConfig = [
'driver' => 'pdo_sqlite',
'user' => @$configuration['username'],
'password' => @$configuration['password']
];
$this->databaseLocation($configuration, $sqliteConfig);
return $sqliteConfig;
}
/**
* Is only suitable for sqlite configuration mapping.
*
* @param array $configuration
* @return bool
*/
public function isAppropriateFor(array $configuration)
{
return $configuration['driver'] == 'sqlite';
}
/**
* Determines the location of the database and appends this to the sqlite configuration.
*
* @param $configuration
* @param $sqliteConfig
*/
private function databaseLocation($configuration, &$sqliteConfig)
{
if ($configuration['database'] == ':memory:')
$sqliteConfig['memory'] = true;
else
$sqliteConfig['path'] = app_path('database').'/'.$configuration['database'].'.sqlite';
}
} |
Add a test to make sure HTTPS URLs aren't failing for Quick Copy | describe("Zotero.QuickCopy", function() {
var quickCopyPref = Zotero.Prefs.get("export.quickCopy.setting");
quickCopyPref = JSON.stringify(Zotero.QuickCopy.unserializeSetting(quickCopyPref));
// TODO: These should set site-specific prefs and test the actual response against it,
// but that will need to wait for 5.0. For now, just make sure they don't fail.
describe("#getFormatFromURL()", function () {
it("should handle an HTTP URL", function () {
assert.deepEqual(Zotero.QuickCopy.getFormatFromURL('http://foo.com/'), quickCopyPref);
})
it("should handle an HTTPS URL", function () {
assert.deepEqual(Zotero.QuickCopy.getFormatFromURL('https://foo.com/'), quickCopyPref);
})
it("should handle a domain and path", function () {
assert.deepEqual(Zotero.QuickCopy.getFormatFromURL('http://foo.com/bar'), quickCopyPref);
})
it("should handle a local host", function () {
assert.deepEqual(Zotero.QuickCopy.getFormatFromURL('http://foo/'), quickCopyPref);
})
it("should handle an about: URL", function () {
assert.deepEqual(Zotero.QuickCopy.getFormatFromURL('about:blank'), quickCopyPref);
})
it("should handle a chrome URL", function () {
assert.deepEqual(Zotero.QuickCopy.getFormatFromURL('chrome://zotero/content/tab.xul'), quickCopyPref);
})
})
})
| describe("Zotero.QuickCopy", function() {
var quickCopyPref = Zotero.Prefs.get("export.quickCopy.setting");
quickCopyPref = JSON.stringify(Zotero.QuickCopy.unserializeSetting(quickCopyPref));
// TODO: These should set site-specific prefs and test the actual response against it,
// but that will need to wait for 5.0. For now, just make sure they don't fail.
describe("#getFormatFromURL()", function () {
it("should handle a domain", function () {
assert.deepEqual(Zotero.QuickCopy.getFormatFromURL('http://foo.com/'), quickCopyPref);
})
it("should handle a domain and path", function () {
assert.deepEqual(Zotero.QuickCopy.getFormatFromURL('http://foo.com/bar'), quickCopyPref);
})
it("should handle a local host", function () {
assert.deepEqual(Zotero.QuickCopy.getFormatFromURL('http://foo/'), quickCopyPref);
})
it("should handle an about: URL", function () {
assert.deepEqual(Zotero.QuickCopy.getFormatFromURL('about:blank'), quickCopyPref);
})
it("should handle a chrome URL", function () {
assert.deepEqual(Zotero.QuickCopy.getFormatFromURL('chrome://zotero/content/tab.xul'), quickCopyPref);
})
})
})
|
Remove notice re practice trials (to avoid confusion) | /**
* Instructions view block for jsSART
*/
var
instructions = [],
participant_id = getParticipantId();
var instructions_block = {
type: "instructions",
pages: [
"<p>Welcome!</p> " +
"<p>In this study you will be presented with a single digit (<code>1-9</code>) in varying sizes in the middle of the screen for a short duration. The digit is then followed by a crossed circle.</p>",
"<p>Your task is to either:</p> " +
"<ol>" +
"<li>Press the " + spacebar_html + " when you see any digit other than <code>3</code>.</li>" +
"<li>Don’t do anything (press no key) when you see the digit <code>3</code>, and just wait for the next digit to be shown.</li>" +
"<ol>",
"<p>It’s important to be accurate and fast in this study.</p>" +
"<p>Use the index finger of your dominant hand when responding (e.g. if you are left-handed, use your left index finger to press the " + spacebar_html + ").</p>"
],
show_clickable_nav: true
};
instructions.push(instructions_block);
jsPsych.init({
display_element: $('#jspsych-target'),
timeline: instructions,
on_finish: function() {
var redirect_url = 'practice?pid=' + participant_id;
window.location = redirect_url;
}
});
| /**
* Instructions view block for jsSART
*/
var
instructions = [],
participant_id = getParticipantId();
var instructions_block = {
type: "instructions",
pages: [
"<p>Welcome!</p> " +
"<p>In this study you will be presented with a single digit (<code>1-9</code>) in varying sizes in the middle of the screen for a short duration. The digit is then followed by a crossed circle.</p>",
"<p>Your task is to either:</p> " +
"<ol>" +
"<li>Press the " + spacebar_html + " when you see any digit other than <code>3</code>.</li>" +
"<li>Don’t do anything (press no key) when you see the digit <code>3</code>, and just wait for the next digit to be shown.</li>" +
"<ol>",
"<p>It’s important to be accurate and fast in this study.</p>" +
"<p>Use the index finger of your dominant hand when responding (e.g. if you are left-handed, use your left index finger to press the " + spacebar_html + ").</p>",
"<p>We will now continue to some practice trials.</p>"
],
show_clickable_nav: true
};
instructions.push(instructions_block);
jsPsych.init({
display_element: $('#jspsych-target'),
timeline: instructions,
on_finish: function() {
var redirect_url = 'practice?pid=' + participant_id;
window.location = redirect_url;
}
});
|
Use @example.com for the admin seed RFC 2606 | <?php
use {{App\}}Models\User;
use {{App\}}Services\UserService;
use Illuminate\Database\Seeder;
class UserTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$service = app(UserService::class);
if (!User::where('name', 'admin')->first()) {
$user = User::create([
'name' => 'Admin',
'email' => 'admin@example.com',
'password' => bcrypt('admin'),
]);
$service->create($user, 'admin', 'admin', false);
}
}
}
| <?php
use {{App\}}Models\User;
use {{App\}}Services\UserService;
use Illuminate\Database\Seeder;
class UserTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$service = app(UserService::class);
if (!User::where('name', 'admin')->first()) {
$user = User::create([
'name' => 'Admin',
'email' => 'admin@admin.com',
'password' => bcrypt('admin'),
]);
$service->create($user, 'admin', 'admin', false);
}
}
}
|
Modify the view to use the selected company | <?php
namespace frontend\controllers\costbenefitcalculation;
use yii\base\Action;
use common\models\CostbenefitItem;
use common\models\CostbenefitCalculation;
use yii\data\ActiveDataProvider;
use common\commands\CompanyAccess;
class ViewAction extends Action{
public function run(){
$companyAccess = new CompanyAccess();
$company_id = \Yii::$app->session['selected_company_id'];
$id = CostbenefitCalculation::findOne(['company_id' => $company_id])->id;
$provider = New ActiveDataProvider([
'query' => CostbenefitItem::find()
->joinWith('costbenefitCalculation')
->joinWith('costbenefitCalculation.company')
->where(['costbenefit_calculation.id' => $id])
->andWhere( $companyAccess->getQueryConditions() ),
]);
$model = CostbenefitCalculation::findOne($id);
return $this->controller->render('view', [
'model' => $model,
'provider' => $provider
]);
}
}
| <?php
namespace frontend\controllers\costbenefitcalculation;
use yii\base\Action;
use common\models\CostbenefitItem;
use common\models\CostbenefitCalculation;
use yii\data\ActiveDataProvider;
use common\commands\CompanyAccess;
class ViewAction extends Action{
public function run($id){
$companyAccess = new CompanyAccess();
$provider = New ActiveDataProvider([
'query' => CostbenefitItem::find()
->joinWith('costbenefitCalculation')
->joinWith('costbenefitCalculation.company')
->where(['costbenefit_calculation.id' => $id])
->andWhere( $companyAccess->getQueryConditions() ),
]);
$model = CostbenefitCalculation::findOne($id);
return $this->controller->render('view', [
'model' => $model,
'provider' => $provider
]);
}
}
|
Enhance flush plugin to support load dependencies and require.async modules | /**
* The Sea.js plugin for collecting HTTP requests and sending all at once
*/
(function(seajs) {
var Module = seajs.Module
var load = Module.prototype.load
var data = seajs.data
var cid = 0
var stack = []
Module.prototype.load = function() {
stack.push(this)
}
seajs.flush = function() {
var currentStack = stack.splice(0)
var deps = []
// Collect dependencies
for (var i = 0, len = currentStack.length; i < len; i++) {
deps = deps.concat(currentStack[i].resolve())
}
// Create an anonymous module for flushing
var mod = Module.get(
data.cwd + "_flush_" + cid++,
deps
)
mod.load = load
mod.callback = function() {
for (var i = 0, len = currentStack.length; i < len; i++) {
currentStack[i].onload()
}
}
// Load it
mod.load()
}
// Flush to load dependencies
seajs.on("requested", function() {
seajs.flush()
})
// Flush to load `require.async` when module.factory is executed
seajs.on("exec", function() {
seajs.flush()
})
// Register as module
define("seajs-flush", [], {})
})(seajs);
| /**
* The Sea.js plugin for collecting HTTP requests and sending all at once
*/
(function(seajs) {
var Module = seajs.Module
var _load = Module.prototype._load
var data = seajs.data
var cid = 0
var stack = []
Module.prototype._load = function() {
stack.push(this)
}
seajs.flush = function() {
var deps = []
// Collect dependencies
for (var i = 0, len = stack.length; i < len; i++) {
deps = deps.concat(stack[i].dependencies)
}
// Create an anonymous module for flushing
var mod = Module.get(
uri || data.cwd + "_flush_" + cid++,
deps
)
mod._load = _load
mod._callback = function() {
for (var i = 0, len = stack.length; i < len; i++) {
stack[i]._onload()
}
// Empty stack
stack.length = 0
}
// Load it
mod._load()
}
// Flush on loaded
seajs.on("requested", function() {
seajs.flush()
})
// Register as module
define("seajs-flush", [], {})
})(seajs);
|
Add extra checking of TV status | module.exports = function (RED) {
function LgtvRequest2Node(n) {
RED.nodes.createNode(this, n);
var node = this;
this.tv = n.tv;
this.tvConn = RED.nodes.getNode(this.tv);
if (this.tvConn) {
this.tvConn.register(node);
this.on('close', function (done) {
node.tvConn.deregister(node, done);
});
node.on('input', function (msg) {
if (!node.tvConn.connected) {
node.send({payload: false});
}
node.tvConn.request(msg.topic, msg.payload, function (err, res) {
if (!err) {
node.send({payload: res});
} else {
node.send({payload: false});
}
});
});
} else {
this.error('No TV Configuration');
}
}
RED.nodes.registerType('lgtv-request2', LgtvRequest2Node);
};
| module.exports = function (RED) {
function LgtvRequest2Node(n) {
RED.nodes.createNode(this, n);
var node = this;
this.tv = n.tv;
this.tvConn = RED.nodes.getNode(this.tv);
if (this.tvConn) {
this.tvConn.register(node);
this.on('close', function (done) {
node.tvConn.deregister(node, done);
});
node.on('input', function (msg) {
node.tvConn.request(msg.topic, msg.payload, function (err, res) {
if (!err) {
node.send({payload: res});
} else {
node.send({payload: false});
}
});
});
} else {
this.error('No TV Configuration');
}
}
RED.nodes.registerType('lgtv-request2', LgtvRequest2Node);
};
|
Set zip_safe to False as the stub may be called by a process that does not
have a writable egg cache. | #
# This file is part of WinPexpect. WinPexpect 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.
#
# WinPexpect is copyright (c) 2008-2010 by the WinPexpect authors. See the
# file "AUTHORS" for a complete overview.
from setuptools import setup
setup(
name = 'winpexpect',
version = '1.2',
description = 'A version of pexpect that works under Windows.',
author = 'Geert Jansen',
author_email = 'geert@boskant.nl',
url = 'http://bitbucket.org/geertj/winpexpect',
license = 'MIT',
classifiers = ['Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Operating System :: Microsoft :: Windows'],
package_dir = {'': 'lib'},
py_modules = ['pexpect', 'winpexpect'],
test_suite = 'nose.collector',
zip_safe = False
)
| #
# This file is part of WinPexpect. WinPexpect 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.
#
# WinPexpect is copyright (c) 2008-2010 by the WinPexpect authors. See the
# file "AUTHORS" for a complete overview.
from setuptools import setup
setup(
name = 'winpexpect',
version = '1.2',
description = 'A version of pexpect that works under Windows.',
author = 'Geert Jansen',
author_email = 'geert@boskant.nl',
url = 'http://bitbucket.org/geertj/winpexpect',
license = 'MIT',
classifiers = ['Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Operating System :: Microsoft :: Windows'],
package_dir = {'': 'lib'},
py_modules = ['pexpect', 'winpexpect'],
test_suite = 'nose.collector'
)
|
Use float so test passes on Python 2.6 | # from jaraco.util.itertools
def always_iterable(item):
"""
Given an object, always return an iterable. If the item is not
already iterable, return a tuple containing only the item.
>>> always_iterable([1,2,3])
[1, 2, 3]
>>> always_iterable('foo')
('foo',)
>>> always_iterable(None)
(None,)
>>> always_iterable(xrange(10))
xrange(10)
"""
if isinstance(item, basestring) or not hasattr(item, '__iter__'):
item = item,
return item
def total_seconds(td):
"""
Python 2.7 adds a total_seconds method to timedelta objects.
See http://docs.python.org/library/datetime.html#datetime.timedelta.total_seconds
>>> import datetime
>>> total_seconds(datetime.timedelta(hours=24))
86400.0
"""
try:
result = td.total_seconds()
except AttributeError:
seconds = td.seconds + td.days * 24 * 3600
result = float((td.microseconds + seconds * 10**6) / 10**6)
return result
| # from jaraco.util.itertools
def always_iterable(item):
"""
Given an object, always return an iterable. If the item is not
already iterable, return a tuple containing only the item.
>>> always_iterable([1,2,3])
[1, 2, 3]
>>> always_iterable('foo')
('foo',)
>>> always_iterable(None)
(None,)
>>> always_iterable(xrange(10))
xrange(10)
"""
if isinstance(item, basestring) or not hasattr(item, '__iter__'):
item = item,
return item
def total_seconds(td):
"""
Python 2.7 adds a total_seconds method to timedelta objects.
See http://docs.python.org/library/datetime.html#datetime.timedelta.total_seconds
>>> import datetime
>>> total_seconds(datetime.timedelta(hours=24))
86400.0
"""
try:
result = td.total_seconds()
except AttributeError:
seconds = td.seconds + td.days * 24 * 3600
result = (td.microseconds + seconds * 10**6) / 10**6
return result
|
Update couchdb-python dependency version to 0.5 in anticipation of its release.
git-svn-id: fdb8975c015a424b33c0997a6b0d758f3a24819f@9 bfab2ddc-a81c-11dd-9a07-0f3041a8e97c | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2008 Jason Davies
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name = 'CouchDB-FUSE',
version = '0.1',
description = 'CouchDB FUSE module',
long_description = \
"""This is a Python FUSE module for CouchDB. It allows CouchDB document
attachments to be mounted on a virtual filesystem and edited directly.""",
author = 'Jason Davies',
author_email = 'jason@jasondavies.com',
license = 'BSD',
url = 'http://code.google.com/p/couchdb-fuse/',
zip_safe = True,
classifiers = [
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Database :: Front-Ends',
],
packages = ['couchdbfuse'],
entry_points = {
'console_scripts': [
'couchmount = couchdbfuse:main',
],
},
install_requires = ['CouchDB >= 0.5'],
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2008 Jason Davies
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name = 'CouchDB-FUSE',
version = '0.1',
description = 'CouchDB FUSE module',
long_description = \
"""This is a Python FUSE module for CouchDB. It allows CouchDB document
attachments to be mounted on a virtual filesystem and edited directly.""",
author = 'Jason Davies',
author_email = 'jason@jasondavies.com',
license = 'BSD',
url = 'http://code.google.com/p/couchdb-fuse/',
zip_safe = True,
classifiers = [
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Database :: Front-Ends',
],
packages = ['couchdbfuse'],
entry_points = {
'console_scripts': [
'couchmount = couchdbfuse:main',
],
},
install_requires = ['CouchDB>=0.5dev_r125'],
)
|
Save the value of the message. | package arbreader
import (
"encoding/json"
"io"
"strings"
"github.com/juju/errgo"
)
type Message struct {
Key string
Type string
Extended map[string]string
Description string
Value string
}
func Read(reader io.Reader) ([]*Message, error) {
data := map[string]interface{}{}
if err := json.NewDecoder(reader).Decode(&data); err != nil {
return nil, errgo.Mask(err)
}
messages := []*Message{}
for key, value := range data {
if key[0] == '@' {
continue
}
vv := data["@" + key].(map[string]interface{})
extended := map[string]string{}
for ekey, evalue := range vv {
if !strings.HasPrefix(ekey, "x-") {
continue
}
extended[ekey] = evalue.(string)
}
messages = append(messages, &Message{
Key: key,
Type: vv["type"].(string),
Description: vv["description"].(string),
Extended: extended,
Value: value,
})
}
return messages, nil
}
| package arbreader
import (
"encoding/json"
"io"
"strings"
"github.com/juju/errgo"
)
type Message struct {
Key string
Type string
Extended map[string]string
Description string
}
func Read(reader io.Reader) ([]*Message, error) {
data := map[string]interface{}{}
if err := json.NewDecoder(reader).Decode(&data); err != nil {
return nil, errgo.Mask(err)
}
messages := []*Message{}
for key := range data {
if key[0] == '@' {
continue
}
vv := data["@" + key].(map[string]interface{})
extended := map[string]string{}
for ekey, evalue := range vv {
if !strings.HasPrefix(ekey, "x-") {
continue
}
extended[ekey] = evalue.(string)
}
messages = append(messages, &Message{
Key: key,
Type: vv["type"].(string),
Description: vv["description"].(string),
Extended: extended,
})
}
return messages, nil
}
|
Handle non-enum inputs (if they are enum names) | """
Custom types.
"""
from enum import Enum
from six import text_type
from sqlalchemy.types import TypeDecorator, Unicode
class EnumType(TypeDecorator):
"""
SQLAlchemy enum type that persists the enum name (not value).
Note that this type is very similar to the `ChoiceType` from `sqlalchemy_utils`,
with the key difference being persisting by name (and not value).
"""
impl = Unicode(255)
def __init__(self, enum_class):
self.enum_class = enum_class
@property
def python_type(self):
return self.impl.python_type
def process_bind_param(self, value, dialect):
if value is None:
return None
if isinstance(value, Enum):
return text_type(self.enum_class(value).name)
return text_type(self.enum_class[value].name)
def process_result_value(self, value, dialect):
if value is None:
return None
return self.enum_class[value]
| """
Custom types.
"""
from six import text_type
from sqlalchemy.types import TypeDecorator, Unicode
class EnumType(TypeDecorator):
"""
SQLAlchemy enum type that persists the enum name (not value).
Note that this type is very similar to the `ChoiceType` from `sqlalchemy_utils`,
with the key difference being persisting by name (and not value).
"""
impl = Unicode(255)
def __init__(self, enum_class):
self.enum_class = enum_class
@property
def python_type(self):
return self.impl.python_type
def process_bind_param(self, value, dialect):
if value is None:
return None
return text_type(self.enum_class(value).name)
def process_result_value(self, value, dialect):
if value is None:
return None
return self.enum_class[value]
|
Update package
pip install hackr | from setuptools import setup, find_packages
with open('requirements.txt') as f:
required = f.read().splitlines()
setup(name='hackr',
version='0.1.2',
url='https://github.com/pytorn/hackr',
license='Apache 2.0',
author='Ashwini Purohit',
author_email='geek.ashwini@gmail.com',
description='A unicorn for Hackathons',
packages=find_packages(exclude=['tests']),
long_description=open('README.rst').read(),
zip_safe=False,
classifiers=[
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.6',
],
install_requires=required,
setup_requires=[])
| from setuptools import setup, find_packages
with open('requirements.txt') as f:
required = f.read().splitlines()
setup(name='hackr',
version='0.1.1',
url='https://github.com/pytorn/hackr',
license='Apache 2.0',
author='Ashwini Purohit',
author_email='geek.ashwini@gmail.com',
description='A unicorn for Hackathons',
packages=find_packages(exclude=['tests']),
long_description=open('README.rst').read(),
zip_safe=False,
classifiers=[
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.6',
],
install_requires=required,
setup_requires=[])
|
Revert "Add support for server side authentication."
This reverts commit 10ae930f6f14c2840d0b87cbec17054b4cc318d2.
Change-Id: Ied52c31f6f28ad635a6e5dae2171df22dc91e42c
Reviewed-on: http://review.pozytywnie.pl:8080/5153
Reviewed-by: Tomasz Wysocki <f17c2dc043305c950a029074ababd304e0373387@gmail.com>
Tested-by: Tomasz Wysocki <f17c2dc043305c950a029074ababd304e0373387@gmail.com> | from django.contrib.auth import models as auth_models
from django.db import models
import facepy
import simplejson
from facebook_auth import utils
class FacebookUser(auth_models.User):
user_id = models.BigIntegerField(unique=True)
access_token = models.TextField(blank=True, null=True)
app_friends = models.ManyToManyField('self')
@property
def graph(self):
return facepy.GraphAPI(self.access_token)
@property
def js_session(self):
return simplejson.dumps({
'access_token': self.access_token,
'uid': self.user_id
})
@property
def friends(self):
return utils.get_from_graph_api(self.graph, "me/friends")['data']
def update_app_friends(self):
friends = self.friends
friends_ids = [f['id'] for f in friends]
self.app_friends.clear()
self.app_friends.add(*FacebookUser.objects.filter(user_id__in=friends_ids))
| from uuid import uuid1
from django.conf import settings
from django.contrib.auth import models as auth_models
from django.db import models
import facepy
import simplejson
from facebook_auth import utils
class FacebookUser(auth_models.User):
user_id = models.BigIntegerField(unique=True)
access_token = models.TextField(blank=True, null=True)
app_friends = models.ManyToManyField('self')
@property
def graph(self):
return facepy.GraphAPI(self.access_token)
@property
def js_session(self):
return simplejson.dumps({
'access_token': self.access_token,
'uid': self.user_id
})
@property
def friends(self):
return utils.get_from_graph_api(self.graph, "me/friends")['data']
def update_app_friends(self):
friends = self.friends
friends_ids = [f['id'] for f in friends]
self.app_friends.clear()
self.app_friends.add(*FacebookUser.objects.filter(user_id__in=friends_ids))
def get_auth_address(request, redirect_to, scope=''):
state = unicode(uuid1())
request.session['state'] = state
return 'https://www.facebook.com/dialog/oauth?client_id=%s&redirect_uri=%s&scope=%s&state=%s' % (
settings.FACEBOOK_APP_ID, redirect_to, scope, state
)
|
Remove extra semicolon injection in legacy stylesheet | /* global legacyConvert, module, project */
module.exports = function(grunt) {
grunt.registerTask('convertLegacy', function(task) {
var dest = legacyConvert[task],
content = grunt.file.read(dest),
rootSize = project.style.legacy.rootSize,
rootValue = 10;
// Determine root value for unit conversion
if (rootSize.indexOf('%') !== -1) {
rootValue = (rootSize.replace('%', '') / 100) * 16;
} else if (rootSize.indexOf('px') !== -1) {
rootValue = rootSize.replace('px', '');
} else if (rootSize.indexOf('em') !== -1) {
rootValue = rootSize.replace('em', '');
} else if (rootSize.indexOf('pt') !== -1) {
rootValue = rootSize.replace('pt', '');
}
content = content.replace(/(-?[.\d]+)rem/gi, function(str, match) {
return (match * rootValue) + 'px';
}).replace(/opacity:([.\d]+)/gi, function(str, match) {
return 'filter:alpha(opacity=' + Math.round((match * 100) * 100 / 100) + ')';
}).replace(/::/g, ':');
grunt.file.write(dest, content);
});
}; | /* global legacyConvert, module, project */
module.exports = function(grunt) {
grunt.registerTask('convertLegacy', function(task) {
var dest = legacyConvert[task],
content = grunt.file.read(dest),
rootSize = project.style.legacy.rootSize,
rootValue = 10;
// Determine root value for unit conversion
if (rootSize.indexOf('%') !== -1) {
rootValue = (rootSize.replace('%', '') / 100) * 16;
} else if (rootSize.indexOf('px') !== -1) {
rootValue = rootSize.replace('px', '');
} else if (rootSize.indexOf('em') !== -1) {
rootValue = rootSize.replace('em', '');
} else if (rootSize.indexOf('pt') !== -1) {
rootValue = rootSize.replace('pt', '');
}
content = content.replace(/(-?[.\d]+)rem/gi, function(str, match) {
return (match * rootValue) + 'px';
}).replace(/opacity:([.\d]+)/gi, function(str, match) {
return 'filter:alpha(opacity=' + Math.round((match * 100) * 100 / 100) + ');';
}).replace(/::/g, ':');
grunt.file.write(dest, content);
});
}; |
Enable every/some methods to return early to prevent iterating over entire array | // Arrays also come with the standard methods every and some. Both take a predicate function that, when called with an array element as argument, returns true or false. Just like && returns a true value only when the expressions on both sides are true, every returns true only when the predicate returns true for all elements of the array. Similarly, some returns true as soon as the predicate returns true for any of the elements. They do not process more elements than necessary—for example, if some finds that the predicate holds for the first element of the array, it will not look at the values after that.
// Write two functions, every and some, that behave like these methods, except that they take the array as their first argument rather than being a method.
function every(array, action) {
for (let i = 0; i < array.length; i++) {
if (!action(array[i]))
return false;
}
return true;
}
function some(array, action) {
for (let i = 0; i < array.length; i++) {
if (action(array[i]))
return true;
}
return false;
}
console.log(every([NaN, NaN, NaN], isNaN));
console.log(every([NaN, NaN, 4], isNaN));
console.log(some([NaN, 3, 4], isNaN));
console.log(some([2, 3, 4], isNaN));
| // Arrays also come with the standard methods every and some. Both take a predicate function that, when called with an array element as argument, returns true or false. Just like && returns a true value only when the expressions on both sides are true, every returns true only when the predicate returns true for all elements of the array. Similarly, some returns true as soon as the predicate returns true for any of the elements. They do not process more elements than necessary—for example, if some finds that the predicate holds for the first element of the array, it will not look at the values after that.
// Write two functions, every and some, that behave like these methods, except that they take the array as their first argument rather than being a method.
function every(array, action) {
let conditional = true;
for (let i = 0; i < array.length; i++) {
if (!action(array[i])) conditional = false;
}
return conditional;
}
function some(array, action) {
let conditional = false;
for (let i = 0; i < array.length; i++) {
if (action(array[i])) conditional = true;
}
return conditional;
}
console.log(every([NaN, NaN, NaN], isNaN));
console.log(every([NaN, NaN, 4], isNaN));
console.log(some([NaN, 3, 4], isNaN));
console.log(some([2, 3, 4], isNaN));
|
Move into one class attribute. | <?php
if(isset($CreateGameMessage))
{
echo $CreateGameMessage;
} ?>
<table class="standard ajax" id="GameList">
<tr>
<th>Players</th>
<th>Current Turn</th>
<th></th>
</tr><?php
foreach($ChessGames as $ChessGame)
{ ?>
<tr>
<td><?php
echo $ChessGame->getWhitePlayer()->getLinkedDisplayName(false); ?> vs <?php echo $ChessGame->getBlackPlayer()->getLinkedDisplayName(false); ?>
</td>
<td><?php
echo $ChessGame->getCurrentTurnPlayer()->getLinkedDisplayName(false); ?>
</td>
<td>
<div class="buttonA"><a class="buttonA" href="<?php echo $ChessGame->getPlayGameHREF(); ?>"> Play </a></div>
</td>
</tr><?php
}
?>
</table>
<form action="<?php echo Globals::getChessCreateHREF(); ?>" method="POST">
<label for="player_id">Challenge: </label>
<select id="player_id" name="player_id"><?php
foreach($PlayerList as $PlayerID => $PlayerName)
{
?><option value="<?php echo $PlayerID; ?>"><?php echo $PlayerName; ?></option><?php
} ?>
</select><br/>
<input type="submit"/>
</form> | <?php
if(isset($CreateGameMessage))
{
echo $CreateGameMessage;
} ?>
<table class="standard" id="GameList" class="ajax">
<tr>
<th>Players</th>
<th>Current Turn</th>
<th></th>
</tr><?php
foreach($ChessGames as $ChessGame)
{ ?>
<tr>
<td><?php
echo $ChessGame->getWhitePlayer()->getLinkedDisplayName(false); ?> vs <?php echo $ChessGame->getBlackPlayer()->getLinkedDisplayName(false); ?>
</td>
<td><?php
echo $ChessGame->getCurrentTurnPlayer()->getLinkedDisplayName(false); ?>
</td>
<td>
<div class="buttonA"><a class="buttonA" href="<?php echo $ChessGame->getPlayGameHREF(); ?>"> Play </a></div>
</td>
</tr><?php
}
?>
</table>
<form action="<?php echo Globals::getChessCreateHREF(); ?>" method="POST">
<label for="player_id">Challenge: </label>
<select id="player_id" name="player_id"><?php
foreach($PlayerList as $PlayerID => $PlayerName)
{
?><option value="<?php echo $PlayerID; ?>"><?php echo $PlayerName; ?></option><?php
} ?>
</select><br/>
<input type="submit"/>
</form> |
Remove RES definition as potential use case is unknow right now
Change-Id: I6d7d44598755632dbe5d069bc0de3e740e7ccc17 | /*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.net;
/**
* Represents type of wavelength grid.
*
* <p>
* See Open Networking Foundation "Optical Transport Protocol Extensions Version 1.0".
* </p>
*/
public enum GridType {
DWDM, // Dense Wavelength Division Multiplexing
CWDM, // Coarse WDM
FLEX // Flex Grid
}
| /*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.net;
/**
* Represents type of wavelength grid.
*
* <p>
* See Open Networking Foundation "Optical Transport Protocol Extensions Version 1.0".
* </p>
*/
public enum GridType {
RES, // ??
DWDM, // Dense Wavelength Division Multiplexing
CWDM, // Coarse WDM
FLEX // Flex Grid
}
|
Use dataframe to show how semantic information is used | """
Plotting a diagonal correlation matrix
======================================
_thumb: .3, .6
"""
from string import letters
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="white")
# Generate a large random dataset
rs = np.random.RandomState(33)
d = pd.DataFrame(data=rs.normal(size=(100, 26)),
columns=list(letters[:26]))
# Compute the correlation matrix
corr = d.corr()
# Generate a mask for the upper triangle
mask = np.zeros_like(corr, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True
# Set up the matplotlib figure
f, ax = plt.subplots(figsize=(11, 9))
# Generate a custom diverging colormap
cmap = sns.diverging_palette(220, 10, as_cmap=True)
# Draw the heatmap with the mask and correct aspect ratio
sns.heatmap(corr, mask=mask, cmap=cmap, vmax=.3,
square=True, xticklabels=5, yticklabels=5,
linewidths=.5, cbar_kws={"shrink": .5}, ax=ax)
| """
Plotting a diagonal correlation matrix
======================================
_thumb: .3, .6
"""
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="white")
# Generate a large random dataset
rs = np.random.RandomState(33)
d = rs.normal(size=(30, 100))
# Compute the correlation matrix
corr = np.corrcoef(d)
# Generate a mask for the upper triangle
mask = np.zeros_like(corr, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True
# Set up the matplotlib figure
f, ax = plt.subplots(figsize=(11, 9))
# Generate a custom diverging colormap
cmap = sns.diverging_palette(220, 10, as_cmap=True)
# Draw the heatmap with the mask and correct aspect ratio
sns.heatmap(corr, mask=mask, cmap=cmap, vmax=.3,
square=True, xticklabels=5, yticklabels=5,
linewidths=.5, cbar_kws={"shrink": .5}, ax=ax)
|
Disable dev tools on production | import { createStore, applyMiddleware, compose } from 'redux'
import createSagaMiddleware from 'redux-saga'
import { hashHistory } from 'react-router'
import { routerMiddleware } from 'react-router-redux'
export const sagaMiddleware = createSagaMiddleware()
export default (initialState) => {
const reducer = require('../reducer').default
const store = createStore(
reducer,
initialState,
compose(
applyMiddleware(
routerMiddleware(hashHistory),
sagaMiddleware
),
global.devToolsExtension && process.env.NODE_ENV !== 'production' ?
global.devToolsExtension() : f => f
)
)
if (module.hot) {
module.hot.accept('../reducer', () => {
store.replaceReducer(require('../reducer').default)
})
}
return store
}
| import { createStore, applyMiddleware, compose } from 'redux'
import createSagaMiddleware from 'redux-saga'
import { hashHistory } from 'react-router'
import { routerMiddleware } from 'react-router-redux'
export const sagaMiddleware = createSagaMiddleware()
export default (initialState) => {
const reducer = require('../reducer').default
const store = createStore(
reducer,
initialState,
compose(
applyMiddleware(
routerMiddleware(hashHistory),
sagaMiddleware
),
global.devToolsExtension ? global.devToolsExtension() : f => f
)
)
if (module.hot) {
module.hot.accept('../reducer', () => {
store.replaceReducer(require('../reducer').default)
})
}
return store
}
|
Correct way to detect file language | package com.rudeshko.csscomb;
import com.intellij.lang.css.CSSLanguage;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.psi.PsiFile;
public class CssCombAction extends AnAction {
public void actionPerformed(AnActionEvent e) {
PsiFile psiFile = getPsiFileFromActionEvent(e);
if (psiFile != null) {
psiFile.acceptChildren(new CSSCombVisitor());
}
}
@Override
public void update(AnActionEvent e) {
e.getPresentation().setEnabled(isCss(e));
}
private boolean isCss(AnActionEvent e) {
PsiFile psiFile = getPsiFileFromActionEvent(e);
return psiFile != null && psiFile.getLanguage().isKindOf(CSSLanguage.INSTANCE);
}
private static PsiFile getPsiFileFromActionEvent(AnActionEvent e) {
return e.getData(LangDataKeys.PSI_FILE);
}
}
| package com.rudeshko.csscomb;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.psi.PsiFile;
public class CssCombAction extends AnAction {
public void actionPerformed(AnActionEvent e) {
PsiFile psiFile = e.getData(LangDataKeys.PSI_FILE);
if (psiFile != null) {
psiFile.acceptChildren(new CSSCombVisitor());
}
}
@Override
public void update(AnActionEvent e) {
e.getPresentation().setEnabled(isCss(e));
}
private boolean isCss(AnActionEvent e) {
PsiFile psiFile = e.getData(LangDataKeys.PSI_FILE);
return psiFile != null && "CSS".equals(psiFile.getLanguage().getDisplayName());
}
}
|
Fix url in distutils description. | #!/usr/bin/env python
from distutils.core import setup
setup(
name="django-auth-ldap",
version="1.0b7",
description="Django LDAP authentication backend",
long_description="""This is a Django authentication backend that authenticates against an LDAP service. Configuration can be as simple as a single distinguished name template, but there are many rich configuration options for working with users, groups, and permissions.
This package requires Python 2.3, Django 1.0, and python-ldap. Documentation can be found at http://packages.python.org/django-auth-ldap/.
""",
url="http://bitbucket.org/psagers/django-auth-ldap/",
author="Peter Sagerson",
author_email="psagers_pypi@ignorare.net",
license="BSD",
packages=["django_auth_ldap"],
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Web Environment",
"Programming Language :: Python",
"Framework :: Django",
"Intended Audience :: Developers",
"Intended Audience :: System Administrators",
"License :: OSI Approved :: BSD License",
"Topic :: Internet :: WWW/HTTP",
"Topic :: System :: Systems Administration :: Authentication/Directory :: LDAP",
"Topic :: Software Development :: Libraries :: Python Modules",
],
keywords=["django", "ldap", "authentication"],
)
| #!/usr/bin/env python
from distutils.core import setup
setup(
name="django-auth-ldap",
version="1.0b7",
description="Django LDAP authentication backend",
long_description="""This is a Django authentication backend that authenticates against an LDAP service. Configuration can be as simple as a single distinguished name template, but there are many rich configuration options for working with users, groups, and permissions.
This package requires Python 2.3, Django 1.0, and python-ldap. Documentation can be found at <a href="http://packages.python.org/django-auth-ldap/">http://packages.python.org/django-auth-ldap/</a>.
""",
url="http://bitbucket.org/psagers/django-auth-ldap/",
author="Peter Sagerson",
author_email="psagers_pypi@ignorare.net",
license="BSD",
packages=["django_auth_ldap"],
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Web Environment",
"Programming Language :: Python",
"Framework :: Django",
"Intended Audience :: Developers",
"Intended Audience :: System Administrators",
"License :: OSI Approved :: BSD License",
"Topic :: Internet :: WWW/HTTP",
"Topic :: System :: Systems Administration :: Authentication/Directory :: LDAP",
"Topic :: Software Development :: Libraries :: Python Modules",
],
keywords=["django", "ldap", "authentication"],
)
|
Create and confirm photo upload | var express = require('express');
var router = express.Router();
var crypto = require('crypto');
function get_unique_filename(id) {
var data = new Date() + id;
var filename = crypto.createHash('md5').update(data).digest('hex');
return filename
}
// TODO: Fix route and fix to post request
// TODO: Fix req.body
router.get('/create', function(req,res) {
var s3 = req.app.get('s3');
var filename = get_unique_filename(req.body['userid']);
s3.presignedPutObject('pixelectstaging', filename, 1000, function(e, presignedUrl) {
if (e) {
console.log(e);
res.send("Error generating presigned url");
} else {
res.send(presignedUrl);
}
});
});
// TODO: Fix route and fix to post request
// TODO: Fix req.body
router.post('/confirm', function(req, res) {
var models = req.app.get('models');
models.Photo.create({
link: req.body['link'],
userId: req.body['userid'],
groupId: req.body['groupid']
}).then(() => {
res.send("Success");
}).catch((e) => {
console.log(e);
res.send("Error");
});
});
module.exports = router; | var express = require('express');
var router = express.Router();
// TODO: Fix 'testing'. Unique filename required
// TODO: Fix route
// TODO: Fix userId and groupId
// TODO: Fix to post
router.get('/:groupid', function(req,res) {
var models = req.app.get('models');
var s3 = req.app.get('s3');
var presignedUrl = s3.presignedPutObject('pixelectstaging', 'testing', 1000, function(e, presignedUrl) {
if (e) {
console.log(e);
res.send("Error");
} else {
models.Photo.create({
link: presignedUrl,
userId: 1,
groupId: req.params.groupid
}).then(() => {
res.send(presignedUrl);
}).catch((e) => {
console.log(e);
res.send("Error");
});
}
});
});
module.exports = router; |
Move the pylint message and fix comment length | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# 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.
# =============================================================================
"""Exposes the python wrapper for TensorRT graph transforms."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# pylint: disable=unused-import,wildcard-import,g-import-not-at-top
try:
from tensorflow.contrib.tensorrt.python import *
except Exception as e:
no_trt_message = (
'**** Failed to initialize TensorRT. This is either because the TensorRT'
' installation path is not in LD_LIBRARY_PATH, or because you do not have'
' it installed. If not installed, please go to'
' https://developer.nvidia.com/tensorrt to download and install'
' TensorRT ****')
print(no_trt_message)
raise e
# pylint: enable=unused-import,wildcard-import,g-import-not-at-top
| # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# 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.
# =============================================================================
"""Exposes the python wrapper for TensorRT graph transforms."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# pylint: disable=unused-import,wildcard-import
try:
from tensorflow.contrib.tensorrt.python import * # pylint: disable=import-not-at-top
except Exception as e:
no_trt_message = (
'**** Failed to initialize TensorRT. This is either because the TensorRT'
' installation path is not in LD_LIBRARY_PATH, or because you do not have it'
' installed. If not installed, please go to'
' https://developer.nvidia.com/tensorrt to download and install'
' TensorRT ****')
print(no_trt_message)
raise e
# pylint: enable=unused-import,wildcard-import
|
Fix empty ID and EMAIL attributes of org:people:list result | <?php
namespace Pantheon\Terminus\Friends;
use Pantheon\Terminus\Models\User;
/**
* Class UserJoinTrait
* @package Pantheon\Terminus\Friends
*/
trait UserJoinTrait
{
/**
* @var User
*/
private $user;
/**
* @inheritdoc
*/
public function getReferences()
{
return array_merge(parent::getReferences(), $this->getUser()->getReferences());
}
/**
* @inheritdoc
*/
public function getUser()
{
if (empty($this->user)) {
$nickname = \uniqid(__FUNCTION__ . '-');
$this->getContainer()
->add($nickname, User::class)
->addArgument($this->get('user'));
$user = $this->getContainer()->get($nickname);
$user->memberships = [$this];
$this->setUser($user);
}
return $this->user;
}
/**
* @inheritdoc
*/
public function setUser(User $user)
{
$this->user = $user;
}
}
| <?php
namespace Pantheon\Terminus\Friends;
use Pantheon\Terminus\Models\User;
/**
* Class UserJoinTrait
* @package Pantheon\Terminus\Friends
*/
trait UserJoinTrait
{
/**
* @var User
*/
private $user;
/**
* @inheritdoc
*/
public function getReferences()
{
return array_merge(parent::getReferences(), $this->getUser()->getReferences());
}
/**
* @inheritdoc
*/
public function getUser()
{
if (empty($this->user)) {
$nickname = \uniqid(__FUNCTION__ . '-');
$this->getContainer()
->add($nickname, User::class)
->addArgument([$this->get('user')]);
$user = $this->getContainer()->get($nickname);
$user->memberships = [$this];
$this->setUser($user);
}
return $this->user;
}
/**
* @inheritdoc
*/
public function setUser(User $user)
{
$this->user = $user;
}
}
|
Change order of Couch locations | var cradle = require('cradle');
var applyDesignDocuments = require('./design-documents');
var couchLocation = process.env.CLOUDANT_URL || process.env.COUCHDB || 'http://localhost';
var couch = new(cradle.Connection)(couchLocation, 5984, {
cache: true,
raw: false
});
var db = couch.database('emergencybadges');
db.setup = function (callback) {
db.exists(function (err, exists) {
if (err) {
console.log('error', err);
} else if (exists) {
console.log('Database exists.');
if (typeof callback === 'function') callback();
} else {
console.log('Database does not exist. Creating.');
db.create(function (err, res) {
if (!err) {
applyDesignDocuments(db);
if (typeof callback === 'function') callback();
}
});
}
});
};
db.updateDesignDocuments = function (callback) {
applyDesignDocuments(db);
if (typeof callback === 'function') callback();
};
module.exports = db; | var cradle = require('cradle');
var applyDesignDocuments = require('./design-documents');
var couchLocation = process.env.COUCHDB || process.env.CLOUDANT_URL;
var couch = new(cradle.Connection)(couchLocation, 5984, {
cache: true,
raw: false
});
var db = couch.database('emergencybadges');
db.setup = function (callback) {
db.exists(function (err, exists) {
if (err) {
console.log('error', err);
} else if (exists) {
console.log('Database exists.');
if (typeof callback === 'function') callback();
} else {
console.log('Database does not exist. Creating.');
db.create(function (err, res) {
if (!err) {
applyDesignDocuments(db);
if (typeof callback === 'function') callback();
}
});
}
});
};
db.updateDesignDocuments = function (callback) {
applyDesignDocuments(db);
if (typeof callback === 'function') callback();
};
module.exports = db; |
Include intake.cat. YAML is easier than entry_points. | # Import intake to run driver discovery first and avoid circular import issues.
import intake
import warnings
import logging
logger = logging.getLogger(__name__)
from .v1 import Broker, Header, ALL, temp, temp_config
from .utils import (lookup_config, list_configs, describe_configs,
wrap_in_doct, DeprecatedDoct, wrap_in_deprecated_doct)
from .discovery import MergedCatalog, EntrypointsCatalog, V0Catalog
# A catalog created from discovered entrypoints, v0, and intake YAML catalogs.
catalog = MergedCatalog([EntrypointsCatalog(), V0Catalog(), intake.cat])
# set version string using versioneer
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
### Legacy imports ###
try:
from .databroker import DataBroker
except ImportError:
pass
else:
from .databroker import (DataBroker, DataBroker as db,
get_events, get_table, stream, get_fields,
restream, process)
from .pims_readers import get_images
| # Import intake to run driver discovery first and avoid circular import issues.
import intake
del intake
import warnings
import logging
logger = logging.getLogger(__name__)
from .v1 import Broker, Header, ALL, temp, temp_config
from .utils import (lookup_config, list_configs, describe_configs,
wrap_in_doct, DeprecatedDoct, wrap_in_deprecated_doct)
from .discovery import MergedCatalog, EntrypointsCatalog, V0Catalog
# A catalog created from discovered entrypoints and v0 catalogs.
catalog = MergedCatalog([EntrypointsCatalog(), V0Catalog()])
# set version string using versioneer
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
### Legacy imports ###
try:
from .databroker import DataBroker
except ImportError:
pass
else:
from .databroker import (DataBroker, DataBroker as db,
get_events, get_table, stream, get_fields,
restream, process)
from .pims_readers import get_images
|
Use .env to store secret | const _ = require("lodash");
const express = require("express");
const router = express.Router();
const session = require("express-session");
const connect = require("../../utils/database.js");
const restrict = require("../../utils/middlewares/restrict.js");
const auth = require("../../utils/auth.js");
const jwt = require('jsonwebtoken');
const CharError = require("../../utils/charError.js");
const Promise = require("bluebird");
Promise.promisifyAll(jwt);
require('dotenv').config();
const secret = process.env.JWT_SECRET;
// Catch all for authentication (temporary)
router.use(function(req, res, next){
// Anonymous access to API
if(typeof req.token == "undefined" && process.env.ALLOW_ANNONYMOUS_TOKENS == "true"){
req.user = {
username: "Anonymous",
role: "anonymous"
};
next();
return;
}
// Authenticate here and also set the logged in users role accordingly
// Verify auth token
jwt.verifyAsync(req.token, secret).then(function(payload){
req.user = {
username: payload.username,
role: payload.role
};
next();
}).catch(function(err){
next(new CharError("Auth Token Invalid", err.message, 403));
});
});
module.exports = router; | const _ = require("lodash");
const express = require("express");
const router = express.Router();
const session = require("express-session");
const connect = require("../../utils/database.js");
const restrict = require("../../utils/middlewares/restrict.js");
const auth = require("../../utils/auth.js");
const jwt = require('jsonwebtoken');
const CharError = require("../../utils/charError.js");
const Promise = require("bluebird");
Promise.promisifyAll(jwt);
require('dotenv').config();
const secret = "secret_key_PLEASE_CHANGE";
// Catch all for authentication (temporary)
router.use(function(req, res, next){
// Anonymous access to API
if(typeof req.token == "undefined" && process.env.ALLOW_ANNONYMOUS_TOKENS == "true"){
req.user = {
username: "Anonymous",
role: "anonymous"
};
next();
return;
}
// Authenticate here and also set the logged in users role accordingly
// Verify auth token
jwt.verifyAsync(req.token, secret).then(function(payload){
req.user = {
username: payload.username,
role: payload.role
};
next();
}).catch(function(err){
next(new CharError("Auth Token Invalid", err.message, 403));
});
});
module.exports = router; |
feat: Change test setup script to change working directory to temp dir | var os = require('os');
var fs = require('fs-extra');
var path = require('path');
var exec = require('child_process').exec;
const PROJECT_DIRECTORY = path.join(__dirname, '..');
const OS_TEMP_LOCATION = path.join(os.tmpdir(), 'node-static-site-generator-tests');
console.log('1) Setting up environment for testing');
console.log('2) Copying source files to OS temp directory');
fs.copy(PROJECT_DIRECTORY, OS_TEMP_LOCATION, {
clobber: true,
filter: function(directory) {
//exclude specific directories (mainly node_modules) from being copied over
return directory.indexOf('karma') === -1 && directory.indexOf('phantom') === -1 && directory.indexOf('express') === -1 && directory.indexOf('build') === -1 && directory.indexOf('release') === -1 && directory.indexOf('_source') === -1;
}
}, function (err) {
if (err) {
console.error('3) Unable to copy source files');
return console.error(err)
}
process.chdir(path.join(OS_TEMP_LOCATION ,'generatorTests'));
exec('mocha', function(err, stdout, stderr) {
console.log(stdout);
});
}) | var os = require('os');
var fs = require('fs-extra');
var path = require('path');
var exec = require('child_process').exec;
const PROJECT_DIRECTORY = path.join(__dirname, '..');
const OS_TEMP_LOCATION = path.join(os.tmpdir(), 'node-static-site-generator-tests');
console.log('1) Setting up environment for testing');
console.log('2) Copying source files to OS temp directory');
fs.copy(PROJECT_DIRECTORY, OS_TEMP_LOCATION, {
clobber: true,
filter: function(directory) {
//exclude specific directories (mainly node_modules) from being copied over
return directory.indexOf('karma') === -1 && directory.indexOf('phantom') === -1 && directory.indexOf('express') === -1 && directory.indexOf('build') === -1 && directory.indexOf('release') === -1 && directory.indexOf('_source') === -1;
}
}, function (err) {
if (err) {
console.error('3) Unable to copy source files');
return console.error(err)
}
console.log('3) Source files copied - Test setup complete');
exec('mocha', function(err, stdout, stderr) {
console.log(stdout);
});
}) |
Remove carriage returns in Anki exporter | # Copyright (C) 2013 Braden Walters
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from karteikarten.models import Card
class AnkiExporter(object):
'''
Exports cards to ANKI Text File.
'''
@staticmethod
def export(cardset):
result = u'front\tback\n'
for card in Card.objects.filter(parent_card_set = cardset):
result += card.front.replace('\n', '<br />').replace('\r', '') + '\t' + \
card.back.replace('\n', '<br />').replace('\r', '') + '\n'
return result
@staticmethod
def getExtension():
return '.txt'
| # Copyright (C) 2013 Braden Walters
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from karteikarten.models import Card
class AnkiExporter(object):
'''
Exports cards to ANKI Text File.
'''
@staticmethod
def export(cardset):
result = u'front\tback\n'
for card in Card.objects.filter(parent_card_set = cardset):
result += card.front.replace('\n', '<br />') + '\t' + \
card.back.replace('\n', '<br />') + '\n'
return result
@staticmethod
def getExtension():
return '.txt'
|
Remove superflous line, remove duplicate data | import json
def _send_message(message, content: dict, close: bool):
message.reply_channel.send({
'text': json.dumps(content),
'close': close,
})
def send_message(message, message_id, handler, close=False, error=None, **additional_data):
content = dict()
if message_id:
content['id'] = message_id
if handler:
content['type'] = handler
if error:
content['error'] = error
if additional_data:
content['data'] = additional_data
if not content:
raise Exception('Cannot send an empty message.')
_send_message(message, content, close=close)
def send_success(message, message_id, handler, close=False, **additional_data):
"""
This method directly wraps send_message but checks the existence of id and type.
"""
if not message_id or not handler:
raise Exception('You have to provide a message ID and handler on success messages.')
send_message(message, message_id, handler, close=close, **additional_data)
def send_error(message, message_id, handler, error, close=False, **additional_data):
"""
This method wraps send_message and makes sure that error is a keyword argument.
"""
send_message(message, message_id, handler, close=close, error=error, **additional_data)
| import json
def _send_message(message, content: dict, close: bool):
message.reply_channel.send({
'text': json.dumps(content),
'close': close,
})
def send_message(message, message_id, handler, close=False, error=None, **additional_data):
content = dict()
if message_id:
content['id'] = message_id
if handler:
content['type'] = handler
if error:
content['error'] = error
if additional_data:
content['data'] = additional_data
content.update(**additional_data)
if not content:
raise Exception('Cannot send an empty message.')
_send_message(message, content, close=close)
def send_success(message, message_id, handler, close=False, **additional_data):
"""
This method directly wraps send_message but checks the existence of id and type.
"""
if not message_id or not handler:
raise Exception('You have to provide a message ID and handler on success messages.')
send_message(message, message_id, handler, close=close, **additional_data)
def send_error(message, message_id, handler, error, close=False, **additional_data):
"""
This method wraps send_message and makes sure that error is a keyword argument.
"""
send_message(message, message_id, handler, close=close, error=error, **additional_data)
|
Remove some err checks, return it directly | /*
Package identity provides type that allows to authorize request
*/
package identity
import (
"github.com/google/uuid"
)
// Identity data to be encode in auth token
type Identity struct {
ID uuid.UUID `json:"id"`
Email string `json:"email"`
Roles []string `json:"roles"`
}
// WithEmail returns a new Identity with given email value
func WithEmail(email string) (*Identity, error) {
i, err := New()
if err != nil {
return nil, err
}
i.Email = email
return i, nil
}
// WithValues returns a new Identity for given values
func WithValues(id uuid.UUID, email string, roles []string) *Identity {
return &Identity{id, email, roles}
}
// New returns a new Identity
func New() (*Identity, error) {
id, err := uuid.NewRandom()
return &Identity{
ID: id,
}, err
}
| /*
Package identity provides type that allows to authorize request
*/
package identity
import (
"github.com/google/uuid"
)
// Identity data to be encode in auth token
type Identity struct {
ID uuid.UUID `json:"id"`
Email string `json:"email"`
Roles []string `json:"roles"`
}
// WithEmail returns a new Identity with given email value
func WithEmail(email string) (*Identity, error) {
i, err := New()
if err != nil {
return nil, err
}
i.Email = email
return i, nil
}
// WithValues returns a new Identity for given values
func WithValues(id uuid.UUID, email string, roles []string) *Identity {
return &Identity{id, email, roles}
}
// New returns a new Identity
func New() (*Identity, error) {
id, err := uuid.NewRandom()
if err != nil {
return nil, err
}
return &Identity{
ID: id,
}, nil
}
|
Fix issue link example comment | /*
Create an issue link
*/
module.exports = function (task, jira, grunt, callback) {
'use strict';
// ## Create an issue link between two issues ##
// ### Takes ###
//
// * link: a link object
// * callback: for when it’s done
//
// ### Returns ###
// * error: string if there was an issue, null if success
//
// [Jira Doc](http://docs.atlassian.com/jira/REST/latest/#id288232)
/* {
* 'type': {
* 'name': 'requirement'
* },
* 'inwardIssue': {
* 'key': 'SYS-2080'
* },
* 'outwardIssue': {
* 'key': 'SYS-2081'
* },
* 'comment': {
* 'body': 'Linked related issue!',
* 'visibility': {
* 'type': 'GROUP',
* 'value': 'jira-users'
* }
* }
* }
*/
var link = task.getValue('link');
jira.issueLink(link, callback);
};
| /*
Create an issue link
*/
module.exports = function (task, jira, grunt, callback) {
'use strict';
// ## Create an issue link between two issues ##
// ### Takes ###
//
// * link: a link object
// * callback: for when it’s done
//
// ### Returns ###
// * error: string if there was an issue, null if success
//
// [Jira Doc](http://docs.atlassian.com/jira/REST/latest/#id288232)
//
/* {
* 'linkType': 'Duplicate',
* 'fromIssueKey': 'HSP-1',
* 'toIssueKey': 'MKY-1',
* 'comment': {
* 'body': 'Linked related issue!',
* 'visibility': {
* 'type': 'GROUP',
* 'value': 'jira-users'
* }
* }
* }
*/
var link = task.getValue('link');
jira.issueLink(link, callback);
};
|
DOC: Update PIL error install URL
Update URL for PIL import error
to point to Pillow installation
instead of PIL, for the latter
is somewhat out of date and
does not even Python 3 at the
moment unlike Pillow.
Closes gh-5779. | from __future__ import division, print_function, absolute_import
_have_pil = True
try:
from scipy.misc.pilutil import imread as _imread
except ImportError:
_have_pil = False
__all__ = ['imread']
# Use the implementation of `imread` in `scipy.misc.pilutil.imread`.
# If it weren't for the different names of the first arguments of
# ndimage.io.imread and misc.pilutil.imread, we could simplify this file
# by writing
# from scipy.misc.pilutil import imread
# Unfortunately, because the argument names are different, that
# introduces a backwards incompatibility.
def imread(fname, flatten=False, mode=None):
if _have_pil:
return _imread(fname, flatten, mode)
raise ImportError("Could not import the Python Imaging Library (PIL)"
" required to load image files. Please refer to"
" http://pillow.readthedocs.org/en/latest/installation.html"
" for installation instructions.")
if _have_pil and _imread.__doc__ is not None:
imread.__doc__ = _imread.__doc__.replace('name : str', 'fname : str')
| from __future__ import division, print_function, absolute_import
_have_pil = True
try:
from scipy.misc.pilutil import imread as _imread
except ImportError:
_have_pil = False
__all__ = ['imread']
# Use the implementation of `imread` in `scipy.misc.pilutil.imread`.
# If it weren't for the different names of the first arguments of
# ndimage.io.imread and misc.pilutil.imread, we could simplify this file
# by writing
# from scipy.misc.pilutil import imread
# Unfortunately, because the argument names are different, that
# introduces a backwards incompatibility.
def imread(fname, flatten=False, mode=None):
if _have_pil:
return _imread(fname, flatten, mode)
raise ImportError("Could not import the Python Imaging Library (PIL)"
" required to load image files. Please refer to"
" http://pypi.python.org/pypi/PIL/ for installation"
" instructions.")
if _have_pil and _imread.__doc__ is not None:
imread.__doc__ = _imread.__doc__.replace('name : str', 'fname : str')
|
Update Sanction exception error message and docstrings | class OSFError(Exception):
"""Base class for exceptions raised by the Osf application"""
pass
class NodeError(OSFError):
"""Raised when an action cannot be performed on a Node model"""
pass
class NodeStateError(NodeError):
"""Raised when the Node's state is not suitable for the requested action
Example: Node.remove_node() is called, but the node has non-deleted children
"""
pass
class SanctionTokenError(NodeError):
"""Base class for errors arising from the user of a sanction token."""
pass
class InvalidSanctionRejectionToken(SanctionTokenError):
"""Raised if a Sanction subclass disapproval token submitted is invalid
or associated with another admin authorizer
"""
message_short = "Invalid Token"
message_long = "This disapproval link is invalid. Are you logged into the correct account?"
class InvalidSanctionApprovalToken(SanctionTokenError):
"""Raised if a Sanction subclass approval token submitted is invalid
or associated with another admin authorizer
"""
message_short = "Invalid Token"
message_long = "This disapproval link is invalid. Are you logged into the correct account?"
| class OSFError(Exception):
"""Base class for exceptions raised by the Osf application"""
pass
class NodeError(OSFError):
"""Raised when an action cannot be performed on a Node model"""
pass
class NodeStateError(NodeError):
"""Raised when the Node's state is not suitable for the requested action
Example: Node.remove_node() is called, but the node has non-deleted children
"""
pass
class SanctionTokenError(NodeError):
"""Base class for errors arising from the user of a sanction token."""
pass
class InvalidSanctionRejectionToken(SanctionTokenError):
"""Raised if a embargo disapproval token is not found."""
message_short = "Invalid Token"
message_long = "This embargo disapproval link is invalid. Are you logged into the correct account?"
class InvalidSanctionApprovalToken(SanctionTokenError):
"""Raised if a embargo disapproval token is not found."""
message_short = "Invalid Token"
message_long = "This embargo disapproval link is invalid. Are you logged into the correct account?"
|
Add billing_address and migrate data | # -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-08-22 23:41
from __future__ import unicode_literals
from django.db import migrations, models
def add_billing_address(apps, schema_editor):
''' Data migration add billing_address in Bill from user billing_address
field
'''
Bill = apps.get_model('billjobs', 'Bill')
for bill in Bill.objects.all():
bill.billing_address = bill.user.userprofile.billing_address
bill.save()
class Migration(migrations.Migration):
dependencies = [
('billjobs', '0002_service_is_available_squashed_0005_bill_issuer_address_default'),
]
operations = [
migrations.AddField(
model_name='bill',
name='billing_address',
field=models.CharField(max_length=1024),
),
migrations.RunPython(add_billing_address),
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-08-22 23:41
from __future__ import unicode_literals
from django.db import migrations
def add_billing_address(apps, schema_editor):
''' Data migration add billing_address in Bill from user billing_address
field
'''
Bill = apps.get_model('billjobs', 'Bill')
for bill in Bill.objects.all():
bill.billing_address = bill.user.billing_address
bill.save()
class Migration(migrations.Migration):
dependencies = [
('billjobs', '0002_service_is_available_squashed_0005_bill_issuer_address_default'),
]
operations = [
migrations.RunPython(add_billing_address),
]
|
Remove unused AttributeMeta type constants | from collections import OrderedDict
from malcolm.core.serializable import Serializable
class AttributeMeta(Serializable):
"""Abstract base class for Meta objects"""
def __init__(self, name, description, *args):
super(AttributeMeta, self).__init__(name, *args)
self.description = description
def validate(self, value):
"""
Abstract function to validate a given value
Args:
value(abstract): Value to validate
"""
raise NotImplementedError(
"Abstract validate function must be implemented in child classes")
def to_dict(self):
"""Convert object attributes into a dictionary"""
d = OrderedDict()
d["description"] = self.description
d["typeid"] = self.typeid
return d
| from collections import OrderedDict
from malcolm.core.serializable import Serializable
class AttributeMeta(Serializable):
"""Abstract base class for Meta objects"""
# Type constants
SCALAR = "scalar"
TABLE = "table"
SCALARARRAY = "scalar_array"
def __init__(self, name, description, *args):
super(AttributeMeta, self).__init__(name, *args)
self.description = description
def validate(self, value):
"""
Abstract function to validate a given value
Args:
value(abstract): Value to validate
"""
raise NotImplementedError(
"Abstract validate function must be implemented in child classes")
def to_dict(self):
"""Convert object attributes into a dictionary"""
d = OrderedDict()
d["description"] = self.description
d["typeid"] = self.typeid
return d
|
Add support for handling errors and warnings | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by @kungfusheep
# Copyright (c) 2016 @kungfusheep
#
# License: MIT
#
"""This module exports the Stylelint plugin class."""
import os
from SublimeLinter.lint import Linter, util
class Stylelint(Linter):
"""Provides an interface to stylelint."""
syntax = ('css', 'css3', 'sass', 'scss', 'postcss')
cmd = ('node', os.path.dirname(os.path.realpath(__file__)) + '/stylelint_wrapper.js', '@')
error_stream = util.STREAM_BOTH
config_file = ('--config', '.stylelintrc', '~')
tempfile_suffix = 'css'
regex = (
r'^\s*(?P<line>[0-9]+)\:(?P<col>[0-9]+)\s*(?:(?P<error>✖)|(?P<warning>⚠))\s*(?P<message>.+)'
)
| #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by @kungfusheep
# Copyright (c) 2016 @kungfusheep
#
# License: MIT
#
"""This module exports the Stylelint plugin class."""
import os
from SublimeLinter.lint import Linter, util
class Stylelint(Linter):
"""Provides an interface to stylelint."""
syntax = ('css', 'css3', 'sass', 'scss', 'postcss')
cmd = ('node', os.path.dirname(os.path.realpath(__file__)) + '/stylelint_wrapper.js', '@')
error_stream = util.STREAM_BOTH
config_file = ('--config', '.stylelintrc', '~')
tempfile_suffix = 'css'
regex = (
r'^\s*(?P<line>[0-9]+)\:(?P<col>[0-9]+)\s*(?P<message>.+)'
)
|
Test app should register with NopRegistry | package testutils
import (
"net/http/httptest"
"github.com/gorilla/mux"
"github.com/mailgun/scroll"
"github.com/mailgun/scroll/registry"
)
// TestApp wraps a regular app adding features that can be used in unit tests.
type TestApp struct {
RestHelper
app *scroll.App
testServer *httptest.Server
}
// NewTestApp creates a new app should be used in unit tests.
func NewTestApp() *TestApp {
router := mux.NewRouter()
registry := ®istry.NopRegistry{}
config := scroll.AppConfig{
Name: "test",
Router: router,
Registry: registry}
return &TestApp{
RestHelper{},
scroll.NewAppWithConfig(config),
httptest.NewServer(router),
}
}
// GetApp returns an underlying "real" app for the test app.
func (testApp *TestApp) GetApp() *scroll.App {
return testApp.app
}
// GetURL returns the base URL of the underlying test server.
func (testApp *TestApp) GetURL() string {
return testApp.testServer.URL
}
// Close shuts down the underlying test server.
func (testApp *TestApp) Close() {
testApp.testServer.Close()
}
| package testutils
import (
"net/http/httptest"
"github.com/gorilla/mux"
"github.com/mailgun/scroll"
)
// TestApp wraps a regular app adding features that can be used in unit tests.
type TestApp struct {
RestHelper
app *scroll.App
testServer *httptest.Server
}
// NewTestApp creates a new app should be used in unit tests.
func NewTestApp() *TestApp {
router := mux.NewRouter()
return &TestApp{
RestHelper{},
scroll.NewAppWithConfig(scroll.AppConfig{Router: router}),
httptest.NewServer(router),
}
}
// GetApp returns an underlying "real" app for the test app.
func (testApp *TestApp) GetApp() *scroll.App {
return testApp.app
}
// GetURL returns the base URL of the underlying test server.
func (testApp *TestApp) GetURL() string {
return testApp.testServer.URL
}
// Close shuts down the underlying test server.
func (testApp *TestApp) Close() {
testApp.testServer.Close()
}
|
Enable overriding of the default url | 'use strict';
import assign from 'lodash.assign';
import path from 'path';
import url from 'url';
import ResultList from './result-list';
const requiredDefaults = {
page: 1,
per_page: 20,
url: 'https://pixabay.com/api'
};
const pixabayjs = {
_auth: {},
_makeConfig: function(endpoint, opts) {
const conf = assign({}, requiredDefaults, this.defaults, this._auth, opts);
const urlObj = url.parse(conf.url);
urlObj.pathname = path.join(urlObj.pathname, endpoint, '/');
conf.url = url.format(urlObj);
return conf;
},
defaults: {},
authenticate: function(key) {
this._auth.key = key;
},
imageResultList: function(search, opts, onSuccess, onFailure) {
const conf = this._makeConfig('', opts);
return new ResultList(search, conf, onSuccess, onFailure);
},
videoResultList: function(search, opts, onSuccess, onFailure) {
const conf = this._makeConfig('videos', opts);
return new ResultList(search, conf, onSuccess, onFailure);
}
};
export default pixabayjs;
module.exports = pixabayjs;
| 'use strict';
import assign from 'lodash.assign';
import ResultList from './result-list';
const requiredDefaults = {
page: 1,
per_page: 20,
};
const pixabayjs = {
_auth: {},
_makeConfig: function(url, opts) {
const urlObj = { url };
return assign({}, requiredDefaults, urlObj, this.defaults, this._auth,
opts);
},
defaults: {},
authenticate: function(key) {
this._auth.key = key;
},
imageResultList: function(search, opts, onSuccess, onFailure) {
const url = 'https://pixabay.com/api';
const conf = this._makeConfig(url, opts);
return new ResultList(search, conf, onSuccess, onFailure);
},
videoResultList: function(search, opts, onSuccess, onFailure) {
const url = 'https://pixabay.com/api/videos';
const conf = this._makeConfig(url, opts);
return new ResultList(search, conf, onSuccess, onFailure);
}
};
export default pixabayjs;
module.exports = pixabayjs;
|
Save page location when annotating. | import Axios from 'axios';
export function request (url, method, data = {}, options = {scroll: true}) {
let promise = Axios.post(url, data, {
headers: {
'X-HTTP-Method-Override': method,
'X-CSRF-Token': document.querySelector('meta[name=csrf-token]').getAttribute('content')
},
});
promise.catch(e => {
if (e.response) return e.response;
throw e;
})
.then(response => {
let html = response.data;
let location = response.request.responseURL;
document.location.reload(true);
if (options["modal"]){
options["modal"].destroy();
}
})
.done();
return promise;
}
export var get = (url, data = {}, options = {}) => request(url, 'get', data, options)
export var post = (url, data = {}, options = {}) => request(url, 'post', data, options)
export var rest_delete = (url, data = {}, options = {}) => request(url, 'delete', data, options)
export var patch = (url, data = {}, options = {}) => request(url, 'patch', data, options) | import Axios from 'axios';
export function request (url, method, data = {}, options = {scroll: true}) {
let promise = Axios.post(url, data, {
headers: {
'X-HTTP-Method-Override': method,
'X-CSRF-Token': document.querySelector('meta[name=csrf-token]').getAttribute('content')
},
});
promise.catch(e => {
if (e.response) return e.response;
throw e;
})
.then(response => {
let html = response.data;
let location = response.request.responseURL;
window.location.replace(location);
if (options["modal"]){
options["modal"].destroy();
}
})
.done();
return promise;
}
export var get = (url, data = {}, options = {}) => request(url, 'get', data, options)
export var post = (url, data = {}, options = {}) => request(url, 'post', data, options)
export var rest_delete = (url, data = {}, options = {}) => request(url, 'delete', data, options)
export var patch = (url, data = {}, options = {}) => request(url, 'patch', data, options) |
Use `Object.create` instead of `new` for prototype inheritance. | 'use strict';
var google = global.google;
function onAdd() {
var panes = this.getPanes();
panes.overlayLayer.appendChild(this.el);
}
function positionOverlayByDimensions(projectedLatLng) {
var offsetHeight = this.el.offsetHeight,
offsetWidth = this.el.offsetWidth;
this.el.style.top = projectedLatLng.y - offsetHeight + 'px';
this.el.style.left = projectedLatLng.x - Math.floor(offsetWidth / 2) + 'px';
}
function draw() {
var projection = this.getProjection(),
projectedLatLng = projection.fromLatLngToDivPixel(this.point);
positionOverlayByDimensions.call(this, projectedLatLng);
}
function BaseOverlay(options) {
this.el = options.el;
this.point = new google.maps.LatLng(options.point);
this.el.style.position = 'absolute';
}
BaseOverlay.prototype = Object.create(google.maps.OverlayView.prototype);
BaseOverlay.prototype.constructor = BaseOverlay;
BaseOverlay.prototype.onAdd = onAdd;
BaseOverlay.prototype.draw = draw;
module.exports = BaseOverlay;
| 'use strict';
var google = global.google;
function onAdd() {
var panes = this.getPanes();
panes.overlayLayer.appendChild(this.el);
}
function positionOverlayByDimensions(projectedLatLng) {
var offsetHeight = this.el.offsetHeight,
offsetWidth = this.el.offsetWidth;
this.el.style.top = projectedLatLng.y - offsetHeight + 'px';
this.el.style.left = projectedLatLng.x - Math.floor(offsetWidth / 2) + 'px';
}
function draw() {
var projection = this.getProjection(),
projectedLatLng = projection.fromLatLngToDivPixel(this.point);
positionOverlayByDimensions.call(this, projectedLatLng);
}
function BaseOverlay(options) {
this.el = options.el;
this.point = new google.maps.LatLng(options.point);
this.el.style.position = 'absolute';
}
BaseOverlay.prototype = new google.maps.OverlayView();
BaseOverlay.prototype.onAdd = onAdd;
BaseOverlay.prototype.draw = draw;
module.exports = BaseOverlay;
|
Allow passing a model to the rules for more advanced rule setting. | <?php
namespace UMFlint\Repository\Rules;
abstract class BaseRules
{
/**
* Array of rules.
*
* @param null $model
* @return array
*/
abstract protected function rules($model = null): array;
/**
* Get rules.
*
* @author Donald Wilcox <dowilcox@umflint.edu>
* @param null $model
* @return array
*/
public static function getRules($model = null): array
{
return (new static)->rules($model);
}
/**
* Custom validation messages.
*
* @return array
*/
protected function messages()
{
return [];
}
/**
* Get messages.
*
* @author Donald Wilcox <dowilcox@umflint.edu>
* @return array
*/
public static function getMessages(): array
{
return (new static)->messages();
}
} | <?php
namespace UMFlint\Repository\Rules;
abstract class BaseRules
{
/**
* Array of rules.
*
* @return array
*/
abstract protected function rules(): array;
/**
* Get rules.
*
* @author Donald Wilcox <dowilcox@umflint.edu>
* @return array
*/
public static function getRules(): array
{
return (new static)->rules();
}
/**
* Custom validation messages.
*
* @return array
*/
protected function messages()
{
return [];
}
/**
* Get messages.
*
* @author Donald Wilcox <dowilcox@umflint.edu>
* @return array
*/
public static function getMessages(): array
{
return (new static)->messages();
}
} |
Add items to cart UI on ITEM_ADDED | import { addClass, addId, button, div, h1, i, p, section, text, ul } from '../builders';
import { $ } from '../helpers';
import modalItem from './modalItem';
export default function modal(store) {
const close = addId(addClass(i(), 'fa', 'fa-times', 'close'), 'close');
const title = addClass(h1(text('Cart')), 'title');
const cartContainer = addId(div(p(text('Your cart is empty.'))), 'cart-items');
const checkoutButton = addClass(button(text('Checkout')), 'button', 'is-fullwidth');
const modalContainer = addClass(div(close, title, cartContainer, checkoutButton), 'modal-container');
const modalEle = addId(addClass(section(modalContainer), 'modal'), 'modal');
store.on('TOGGLE_SHOW_CART', ({ cartVisible }) => {
const ele = $('#modal');
if (cartVisible) {
ele.addClass('show');
} else {
ele.removeClass('show');
}
});
store.on('ITEM_ADDED', ({ items, cart }) => {
const cartArray = [...cart];
const cartItems = cartArray.map(itemId => modalItem(items[itemId]));
const cartList = addClass(ul(...cartItems), 'menu');
$('#cart-items').children(cartList);
});
return modalEle;
}
| import { addClass, addId, button, div, h1, i, p, section, text, ul } from '../builders';
import { $ } from '../helpers';
import modalItem from './modalItem';
export default function modal(store, items = []) {
const close = addId(addClass(i(), 'fa', 'fa-times', 'close'), 'close');
const title = addClass(h1(text('Cart')), 'title');
let cart;
if (items.length === 0) {
cart = p(text('Your cart is empty.'));
} else {
const cartItems = items.map(modalItem);
cart = addClass(ul(...cartItems), 'menu');
}
const checkoutButton = addClass(button(text('Checkout')), 'button', 'is-fullwidth');
const modalContainer = addClass(div(close, title, cart, checkoutButton), 'modal-container');
const modalEle = addId(addClass(section(modalContainer), 'modal'), 'modal');
store.on('TOGGLE_SHOW_CART', ({ cartVisible }) => {
const ele = $('#modal');
if (cartVisible) {
ele.addClass('show');
} else {
ele.removeClass('show');
}
});
store.on('ITEM_ADDED', ({ items, cart}) => {
});
return modalEle;
}
|
Allow extensions on last parameter | import re
from ...errors import BinstarError
from .downloader import *
from .uploader import *
from .finder import *
from .scm import *
def parse(handle):
"""
>>> parse("user/project:main.ipynb")
('user', 'project', 'main.ipynb')
>>> parse("project")
(None, 'project', None)
>>> parse("user/project")
('user', 'project', None)
:param handle: String
:return: username, project, file
"""
r = r'^(?P<user0>\w+)/(?P<project0>\w+):(?P<notebook0>\w+)$|^(?P<user1>\w+)/(?P<project1>\w+)$|^(?P<project2>.+)$'
try:
parsed = re.compile(r).match(handle).groupdict()
except AttributeError:
raise BinstarError("{} can't be parsed".format(handle))
if parsed['project2'] is not None:
return None, parsed['project2'], None
elif parsed['project1'] is not None:
return parsed['user1'], parsed['project1'], None
else:
return parsed['user0'], parsed['project0'], parsed['notebook0']
| import re
from ...errors import BinstarError
from .downloader import *
from .uploader import *
from .finder import *
from .scm import *
def parse(handle):
"""
>>> parse("user/project:main.ipynb")
('user', 'project', 'main.ipynb')
>>> parse("project")
(None, 'project', None)
>>> parse("user/project")
('user', 'project', None)
:param handle: String
:return: username, project, file
"""
r = r'^(?P<user0>\w+)/(?P<project0>\w+):(?P<notebook0>\w+)$|^(?P<user1>\w+)/(?P<project1>\w+)$|^(?P<project2>\w+)$'
try:
parsed = re.compile(r).match(handle).groupdict()
except AttributeError:
raise BinstarError("{} can't be parsed".format(handle))
if parsed['project2'] is not None:
return None, parsed['project2'], None
elif parsed['project1'] is not None:
return parsed['user1'], parsed['project1'], None
else:
return parsed['user0'], parsed['project0'], parsed['notebook0']
|
Include comments in Role serializer | from rest_framework import serializers
from .models import Challenge, Role
from core.serializers import UserSerializer
from comments.serializers import CommentSerializer
class RoleSerializer(serializers.ModelSerializer):
#user = UserSerializer()
#challenge = serializers.RelatedField()
comment_set = CommentSerializer()
class Meta:
model = Role
fields = ("id", "user", "type", "challenge", "comment_set")
class ChallengeSerializer(serializers.ModelSerializer):
#role_set = serializers.HyperlinkedRelatedField(view_name="role_api_retrieve", many=True)
#role_set = serializers.RelatedField(many=True)
#role_set = serializers.SlugRelatedField(many=True, slug_field="type")
role_set = RoleSerializer(many=True)
class Meta:
model = Challenge
fields = ("id", "title", "body", "repo_name", "creation_datetime",
"role_set")
| from rest_framework import serializers
from .models import Challenge, Role
from core.serializers import UserSerializer
class RoleSerializer(serializers.ModelSerializer):
#user = serializers.RelatedField(many=True)
#user = serializers.PrimaryKeyRelatedField()
#user = serializers.HyperlinkedRelatedField()
user = UserSerializer()
#challenge = ChallengeSerializer()
challenge = serializers.RelatedField()
class Meta:
model = Role
fields = ("id", "user", "type", "challenge")
class ChallengeSerializer(serializers.ModelSerializer):
#role_set = serializers.HyperlinkedRelatedField(view_name="role_api_retrieve", many=True)
#role_set = serializers.RelatedField(many=True)
#role_set = serializers.SlugRelatedField(many=True, slug_field="type")
role_set = RoleSerializer(many=True)
class Meta:
model = Challenge
fields = ("id", "title", "body", "repo_name", "creation_datetime",
"role_set")
|
Prepare for new Nordea header
In June, Nordea will switch to a new web-interface.
This new interface also has a new csv-export format.
This commit adapts Nordea to the new format, while the previous
header is called "Nordea (gamal)".
I might remove the previous header come late June, after Nordea has
made the switch. | """ Banks' header configurations.
Stored in a dictionary where the keys are bank names in lowercase and
only alpha-characters. A bank's header should include "date" and
"amount", otherwise it cannot be parsed since YNAB requires these two
fields.
"""
from collections import namedtuple
Bank = namedtuple('Bank', ['name', 'header', 'delimiter'])
banks = dict()
def toKey(name : str) -> str:
key = [c for c in name if c.isalpha()]
key = ''.join(key)
return key.lower()
NordeaOldHeader = ['Date', 'Transaction', 'Memo', 'Amount', 'Balance']
NordeaOld = Bank('Nordea (gamla)', NordeaOldHeader, delimiter=',')
banks[toKey(NordeaOld.name)] = NordeaOld
# All information regarding the payee is in a different field called "Rubrik"
# while "Betalningsmottagare" (i.e, "payee" in English) is empty.
# This makes no sense, but that's the format they currently use.
NordeaHeader = ['Date', 'Amount', "Sender" ,"TruePayee", "Name", "Payee", "Balance", "Currency"]
Nordea = Bank('Nordea', NordeaHeader, delimiter=';')
banks[toKey(Nordea.name)] = Nordea
IcaHeader = ['Date', 'Payee', 'Transaction', 'Memo', 'Amount', 'Balance']
Ica = Bank('ICA Banken', IcaHeader, delimiter=';')
banks[toKey(Ica.name)] = Ica | """ Banks' header configurations.
Stored in a dictionary where the keys are bank names in lowercase and
only alpha-characters. A bank's header should include "date" and
"amount", otherwise it cannot be parsed since YNAB requires these two
fields.
"""
from collections import namedtuple
Bank = namedtuple('Bank', ['name', 'header', 'delimiter'])
banks = dict()
def toKey(name : str) -> str:
key = [c for c in name if c.isalpha()]
key = ''.join(key)
return key.lower()
NordeaHeader = ['Date', 'Transaction', 'Memo', 'Amount', 'Balance']
Nordea = Bank('Nordea', NordeaHeader, delimiter=',')
banks[toKey(Nordea.name)] = Nordea
IcaHeader = ['Date', 'Payee', 'Transaction', 'Memo', 'Amount', 'Balance']
Ica = Bank('ICA Banken', IcaHeader, delimiter=';')
banks[toKey(Ica.name)] = Ica |
Clean up default parser, expose Delims | package multitemplate
import (
"text/template"
"text/template/parse"
)
var GoLeftDelim, GoRightDelim string
type defaultParser struct {
left, right string
}
func (ms *defaultParser) ParseTemplate(name, src string, funcs template.FuncMap) (map[string]*parse.Tree, error) {
var t *template.Template
var e error
if GoRightDelim != "" || GoLeftDelim != "" {
t, e = template.New(name).Funcs(funcs).Delims(GoLeftDelim, GoRightDelim).Parse(src)
} else {
t, e = template.New(name).Funcs(funcs).Parse(src)
}
if e != nil {
return nil, e
}
ret := make(map[string]*parse.Tree)
for _, t := range t.Templates() {
ret[t.Name()] = t.Tree
}
return ret, nil
}
func (ms *defaultParser) String() string {
return "html/template: Standard Library Template"
}
func init() {
Parsers["tmpl"] = &defaultParser{}
}
| package multitemplate
import (
"text/template"
"text/template/parse"
"github.com/acsellers/multitemplate"
)
type defaultParser struct{}
func (ms *multiStruct) ParseTemplate(name, src string, funcs template.FuncMap) (map[string]*parse.Tree, error) {
t, e := template.New(name).Funcs(funcs).Parse(src)
if e != nil {
return nil, e
}
ret := make(map[string]*parse.Tree)
for _, t := range t.Templates() {
ret[t.Name()] = t.Tree
}
return ret, nil
}
func (ms *multiStruct) String() string {
return "html/template: Standard Library Template"
}
func init() {
ms := multiStruct{}
multitemplate.Parsers["default"] = &ms
multitemplate.Parsers["tmpl"] = &ms
}
|
Make MMe match BMe and remove references to the removed AnnotationChecker class | package com.mcmoddev.modernmetals.integration;
import com.google.common.collect.Lists;
import com.mcmoddev.modernmetals.ModernMetals;
import com.mcmoddev.modernmetals.integration.ModernMetalsPlugin;
import com.mcmoddev.lib.integration.IIntegration;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.discovery.ASMDataTable.ASMData;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import java.util.List;
public enum IntegrationManager {
INSTANCE;
private List<IIntegration> integrations = Lists.newArrayList();
public void preInit(FMLPreInitializationEvent event) {
for( final ASMData asmDataItem : event.getAsmData().getAll(ModernMetalsPlugin.class.getCanonicalName()) ) {
String modId = asmDataItem.getAnnotationInfo().get("value").toString();
String className = asmDataItem.getClassName();
if (Loader.isModLoaded(modId)) {
IIntegration integration;
try {
integration = Class.forName(className).asSubclass(IIntegration.class).newInstance();
ModernMetals.logger.info("MODERNMETALS Loaded: "+modId);
integrations.add(integration);
integration.init();
} catch (final Exception e) {
// do nothing
}
}
}
}
} | package com.mcmoddev.modernmetals.integration;
import com.google.common.collect.Lists;
import com.mcmoddev.lib.integration.IIntegration;
import com.mcmoddev.lib.util.AnnotationChecker;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import java.util.List;
public enum IntegrationManager {
INSTANCE;
private List<IIntegration> integrations = Lists.newArrayList();
public void preInit(FMLPreInitializationEvent event) {
AnnotationChecker.getInstances(event.getAsmData(), ModernMetalsPlugin.class, IIntegration.class).stream()
.forEachOrdered(integration -> {
Class<? extends IIntegration> integrationClass = integration.getClass();
ModernMetalsPlugin plugin = integrationClass.getAnnotation(ModernMetalsPlugin.class);
if (Loader.isModLoaded(plugin.value())) {
FMLLog.severe("MODERNMETALS: Loaded " + plugin.value());
integrations.add(integration);
integration.init();
}
});
}
} |
Fix buildHtml import to be buildHTML | /* eslint-disable import/no-dynamic-require, react/no-danger */
export { default as extractTemplates } from './extractTemplates'
export { default as preparePlugins } from './preparePlugins'
export { default as prepareRoutes } from './prepareRoutes'
export { default as fetchSiteData } from './fetchSiteData'
export { default as exportSharedRouteData } from './exportSharedRouteData'
export { default as buildHTML } from './buildHTML'
export { default as generateRoutes } from './generateRoutes'
export { default as generateBrowserPlugins } from './generateBrowserPlugins'
export { default as fetchRoutes } from './fetchRoutes'
export { default as exportRoute } from './exportRoute'
export { default as exporter } from './exporter'
export { default as buildXML } from './buildXML'
export { default as exportRoutes } from './exportRoutes'
export { default as getConfig } from './getConfig'
export { reloadRoutes, startDevServer, buildProductionBundles } from './webpack'
| /* eslint-disable import/no-dynamic-require, react/no-danger */
export { default as extractTemplates } from './extractTemplates'
export { default as preparePlugins } from './preparePlugins'
export { default as prepareRoutes } from './prepareRoutes'
export { default as fetchSiteData } from './fetchSiteData'
export { default as exportSharedRouteData } from './exportSharedRouteData'
export { default as buildHtml } from './buildHtml'
export { default as generateRoutes } from './generateRoutes'
export { default as generateBrowserPlugins } from './generateBrowserPlugins'
export { default as fetchRoutes } from './fetchRoutes'
export { default as exportRoute } from './exportRoute'
export { default as exporter } from './exporter'
export { default as buildXML } from './buildXML'
export { default as exportRoutes } from './exportRoutes'
export { default as getConfig } from './getConfig'
export { reloadRoutes, startDevServer, buildProductionBundles } from './webpack'
|
Move tests for Resource.wait_until_finished() into a separate class. | #
# Project: retdec-python
# Copyright: (c) 2015 by Petr Zemek <s3rvac@gmail.com> and contributors
# License: MIT, see the LICENSE file for more details
#
"""Tests for the :mod:`retdec.resource` module."""
import unittest
from unittest import mock
from retdec.conn import APIConnection
from retdec.resource import Resource
class ResourceTests(unittest.TestCase):
"""Tests for :class:`retdec.resource.Resource`."""
def test_id_returns_passed_id(self):
r = Resource('ID', mock.Mock(spec_set=APIConnection))
self.assertEqual(r.id, 'ID')
class ResourceWaitUntilFinishedTests(unittest.TestCase):
"""Tests for :func:`retdec.resource.Resource.wait_until_finished()`."""
def test_returns_when_resource_is_finished(self):
conn_mock = mock.Mock(spec_set=APIConnection)
conn_mock.send_get_request.return_value = {'finished': True}
r = Resource('ID', conn_mock)
r.wait_until_finished()
conn_mock.send_get_request.assert_called_once_with('/ID/status')
| #
# Project: retdec-python
# Copyright: (c) 2015 by Petr Zemek <s3rvac@gmail.com> and contributors
# License: MIT, see the LICENSE file for more details
#
"""Tests for the :mod:`retdec.resource` module."""
import unittest
from unittest import mock
from retdec.conn import APIConnection
from retdec.resource import Resource
class ResourceTests(unittest.TestCase):
"""Tests for :class:`retdec.resource.Resource`."""
def test_id_returns_passed_id(self):
r = Resource('ID', mock.Mock(spec_set=APIConnection))
self.assertEqual(r.id, 'ID')
def test_wait_until_finished_returns_when_resource_is_finished(self):
conn_mock = mock.Mock(spec_set=APIConnection)
conn_mock.send_get_request.return_value = {'finished': True}
r = Resource('ID', conn_mock)
r.wait_until_finished()
conn_mock.send_get_request.assert_called_once_with('/ID/status')
|
Create new terminal instances for each socket. | var Pty = require("pty.js");
var Tty = module.exports = {};
var _term = null;
Tty.create = function (options, callback) {
_term = Pty.fork(process.env.SHELL, [], {
name: "Browser Term",
cols: options.cols,
rows: options.rows,
cwd: process.env.HOME
});
_term.on("data", function(data) {
options.socket.emit("data", data);
});
_term.on("close", function() {
options.socket.emit("kill");
Tty.kill();
});
return _term;
};
Tty.data = function (data) {
if (!_term) { return; }
_term.write(data);
};
Tty.kill= function () {
if (!_term) { return; }
_term.destroy();
_term = null;
};
Tty.resize= function () {
if (!_term) { return; }
_term.resize(cols, rows);
};
Tty.process= function (callback) {
if (!_term) { return; }
callback(_term.process);
};
Tty.disconnect= function () {
// TODO
};
Tty.paste= function (callback) {
// TODO
callback();
};
| var Pty = require("pty.js");
var Tty = module.exports = {};
var _term = null;
var _data = [];
Tty.create = function (options, callback) {
_term = _term || Pty.fork(process.env.SHELL, [], {
name: "Browser Term",
cols: options.cols,
rows: options.rows,
cwd: process.env.HOME
});
_term.on("data", function(data) {
_data.push(data);
options.socket.emit("data", data);
});
_term.on("close", function() {
options.socket.emit("kill");
Tty.kill();
});
for (var i = 0; i < _data.length; ++i) {
options.socket.emit("data", _data[i]);
}
return _term;
};
Tty.data = function (data) {
if (!_term) { return; }
_term.write(data);
};
Tty.kill= function () {
if (!_term) { return; }
_term.destroy();
_term = null;
};
Tty.resize= function () {
if (!_term) { return; }
_term.resize(cols, rows);
};
Tty.process= function (callback) {
if (!_term) { return; }
callback(_term.process);
};
Tty.disconnect= function () {
// TODO
};
Tty.paste= function (callback) {
// TODO
callback();
};
|
Fix incorrect variable on line 26 | require('dotenv').load();
var moment = require('moment');
var fixturesEpl = require('./fixtures/epl.json')['fixtures'];
var fixturesCl = require('./fixtures/cl.json')['fixtures'];
var postMessage = require('./lib/postMessage.js');
var matches_rn = [];
var now = moment().utc();
fixturesEpl.forEach(function(entry) {
// set the entry date to be the entry date in utc and a unix number
entry.date = moment(entry.date).utc();
// if the match is within 10 minutes of the current time,
// and it has not been sent, then add the match to the lest of matches_rn
if( (0 <= entry.date - now)
&& (entry.date.diff(now, 'minutes') <= 10)
&& (!entry.hasOwnProperty('sent'))
) {
matches_rn.push(entry.homeTeamName + ' vs ' + entry.awayTeamName);
}
});
if(matches_rn.length > 0) {
if(matches_rn.length == 1) {
plural = 'match';
}
else {
plural = 'matches';
}
// post a message using the BOT_ID and matches_rn
postMessage(process.env.BOT_ID,
matches_rn.length + ' ' + plural + ' kicking off soon:\n' +
matches_rn.join(',\n')
);
}
else {
console.log('no matches found');
}
| require('dotenv').load();
var moment = require('moment');
var fixturesEpl = require('./fixtures/epl.json')['fixtures'];
var fixturesCl = require('./fixtures/cl.json')['fixtures'];
var postMessage = require('./lib/postMessage.js');
var matches_rn = [];
var now = moment().utc();
fixturesEpl.forEach(function(entry) {
// set the entry date to be the entry date in utc and a unix number
entry.date = moment(entry.date).utc();
// if the match is within 10 minutes of the current time,
// and it has not been sent, then add the match to the lest of matches_rn
if( (0 <= entry.date - now)
&& (entry.date.diff(now, 'minutes') <= 10)
&& (!entry.hasOwnProperty('sent'))
) {
matches_rn.push(entry.homeTeamName + ' vs ' + entry.awayTeamName);
}
});
if(matches_rn.length > 0) {
if(matches_send == 1) {
plural = 'match';
}
else {
plural = 'matches';
}
// post a message using the BOT_ID and matches_rn
postMessage(process.env.BOT_ID,
matches_rn.length + ' ' + plural + ' kicking off soon:\n' +
matches_rn.join(',\n')
);
}
else {
console.log('no matches found');
}
|
Use absolute resource path in Pyglet
It appears that a recent change in Pyglet causes relative paths to fail here. | """Loads and manages art assets"""
import pyglet
import os
_ASSET_PATHS = ["res"]
_ASSET_FILE_NAMES = [
"black_key_down.png",
"black_key_up.png",
"white_key_down.png",
"white_key_up.png",
"staff_line.png",
]
class Assets(object):
_loadedAssets = None
@staticmethod
def loadAssets():
Assets._loadedAssets = dict()
Assets._updateResourcePath()
for f in _ASSET_FILE_NAMES:
Assets.loadAsset(f)
@staticmethod
def loadAsset(filename):
Assets._loadedAssets[filename] = pyglet.resource.image(filename)
@staticmethod
def _updateResourcePath():
for p in _ASSET_PATHS:
pyglet.resource.path.append(os.path.join(os.getcwd(), p))
pyglet.resource.reindex()
@staticmethod
def get(filename):
if Assets._loadedAssets is None:
raise RuntimeError("You must initialize the asset manager before "
"retrieving assets")
return Assets._loadedAssets[filename]
| """Loads and manages art assets"""
import pyglet
_ASSET_PATHS = ["res"]
_ASSET_FILE_NAMES = [
"black_key_down.png",
"black_key_up.png",
"white_key_down.png",
"white_key_up.png",
"staff_line.png",
]
class Assets(object):
_loadedAssets = None
@staticmethod
def loadAssets():
Assets._loadedAssets = dict()
Assets._updateResourcePath()
for f in _ASSET_FILE_NAMES:
Assets.loadAsset(f)
@staticmethod
def loadAsset(filename):
Assets._loadedAssets[filename] = pyglet.resource.image(filename)
@staticmethod
def _updateResourcePath():
for p in _ASSET_PATHS:
pyglet.resource.path.append(p)
pyglet.resource.reindex()
@staticmethod
def get(filename):
if Assets._loadedAssets is None:
raise RuntimeError("You must initialize the asset manager before "
"retrieving assets")
return Assets._loadedAssets[filename]
|
Move the invocation into the parens that contain the function | function(){
'use strict';
/*
This file contains tests for the labels that get rendered next to each bar
*/
describe('BarLabelGroup', function(){
var BarLabelGroup, subject, data;
beforeEach(function(){
BarLabelGroup = growstuff.BarLabelGroup;
var bars = [
{name: 'Shade', value: 0.2},
{name: 'Half Shade', value: 0.5}
];
data = {
bars: bars
};
subject = new BarLabelGroup(data);
subject.render(d3.select('#jasmine_content').append('svg'));
})
it('draws a group for labels', function(){
expect($('g.bar-label')).toExist()
});
it('draws 2 bar labels', function(){
expect($('g.bar-label text')).toHaveLength(2);
})
it ('has text for 2 bar labels', function(){
//jquery jasmine appends text from all text elements
// into one string
expect($('g.bar-label text')).toHaveText('ShadeHalf Shade');
})
});
}(); | (function(){
'use strict';
/*
This file contains tests for the labels that get rendered next to each bar
*/
describe('BarLabelGroup', function(){
var BarLabelGroup, subject, data;
beforeEach(function(){
BarLabelGroup = growstuff.BarLabelGroup;
var bars = [
{name: 'Shade', value: 0.2},
{name: 'Half Shade', value: 0.5}
];
data = {
bars: bars
};
subject = new BarLabelGroup(data);
subject.render(d3.select('#jasmine_content').append('svg'));
})
it('draws a group for labels', function(){
expect($('g.bar-label')).toExist()
});
it('draws 2 bar labels', function(){
expect($('g.bar-label text')).toHaveLength(2);
})
it ('has text for 2 bar labels', function(){
//jquery jasmine appends text from all text elements
// into one string
expect($('g.bar-label text')).toHaveText('ShadeHalf Shade');
})
});
})(); |
Update release version to 0.3.1 | from setuptools import setup, find_packages
from os.path import join, dirname
setup(
name='pandas-validation',
version='0.3.1',
description=(
'A Python package for validating data with pandas'),
long_description=open(
join(dirname(__file__), 'README.rst'), encoding='utf-8').read(),
packages=find_packages(exclude=['docs', 'tests*']),
py_modules=['pandasvalidation'],
install_requires=['pandas>=0.16'],
author='Markus Englund',
author_email='jan.markus.englund@gmail.com',
url='https://github.com/jmenglund/pandas-validation',
license='MIT',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6'],
keywords=['pandas', 'validation'],
)
| from setuptools import setup, find_packages
from os.path import join, dirname
setup(
name='pandas-validation',
version='0.3.0',
description=(
'A Python package for validating data with pandas'),
long_description=open(
join(dirname(__file__), 'README.rst'), encoding='utf-8').read(),
packages=find_packages(exclude=['docs', 'tests*']),
py_modules=['pandasvalidation'],
install_requires=['pandas>=0.16'],
author='Markus Englund',
author_email='jan.markus.englund@gmail.com',
url='https://github.com/jmenglund/pandas-validation',
license='MIT',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6'],
keywords=['pandas', 'validation'],
)
|
Remove uniqueness constraints on Workflow and TaskGroup
* Titles need not be unique anymore |
"""Remove prohibitive foreign key constraints
Revision ID: 32221e9f330c
Revises: 235b7b9989be
Create Date: 2014-08-04 20:34:36.697866
"""
# revision identifiers, used by Alembic.
revision = '32221e9f330c'
down_revision = '235b7b9989be'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.drop_constraint(
'uq_t_workflows', table_name='workflows', type_='unique')
op.drop_constraint(
'uq_t_task_groups', table_name='task_groups', type_='unique')
op.drop_constraint(
'cycle_task_group_object_tasks_ibfk_4',
table_name='cycle_task_group_object_tasks',
type_='foreignkey'
)
op.drop_constraint(
'cycle_task_group_objects_ibfk_4',
table_name='cycle_task_group_objects',
type_='foreignkey'
)
def downgrade():
pass
|
"""Remove prohibitive foreign key constraints
Revision ID: 32221e9f330c
Revises: 235b7b9989be
Create Date: 2014-08-04 20:34:36.697866
"""
# revision identifiers, used by Alembic.
revision = '32221e9f330c'
down_revision = '235b7b9989be'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.drop_constraint(
'cycle_task_group_object_tasks_ibfk_4',
table_name='cycle_task_group_object_tasks',
type_='foreignkey'
)
op.drop_constraint(
'cycle_task_group_objects_ibfk_4',
table_name='cycle_task_group_objects',
type_='foreignkey'
)
def downgrade():
pass
|
Set test parameters default to true | <?php
namespace Flotz\TxtLocalBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('flotz_txt_local');
$rootNode
->children()
->scalarNode('username')->isRequired()->cannotBeEmpty()->end()
->scalarNode('hash')->isRequired()->cannotBeEmpty()->end()
->scalarNode('apiKey')->defaultFalse()->end()
->scalarNode('test')->defaultTrue()->end()
->end();
return $treeBuilder;
}
}
| <?php
namespace Flotz\TxtLocalBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('flotz_txt_local');
$rootNode
->children()
->scalarNode('username')->isRequired()->cannotBeEmpty()->end()
->scalarNode('hash')->isRequired()->cannotBeEmpty()->end()
->scalarNode('apiKey')->defaultFalse()->end()
->scalarNode('test')->defaultFalse()->end()
->end();
return $treeBuilder;
}
}
|
fix: Remove typehint for PHP 5.5.
Signed-off-by: Bruno Gaspar <367518169777ee9ae71cfcee56304a59ac5423c1@gmail.com> | <?php
/**
* Part of the Stripe package.
*
* NOTICE OF LICENSE
*
* Licensed under the 3-clause BSD License.
*
* This source file is subject to the 3-clause BSD License that is
* bundled with this package in the LICENSE file.
*
* @package Stripe
* @version 2.1.0
* @author Cartalyst LLC
* @license BSD License (3-clause)
* @copyright (c) 2011-2018, Cartalyst LLC
* @link http://cartalyst.com
*/
namespace Cartalyst\Stripe\Api;
class EphemeralKey extends Api
{
/**
* Creates a new Ephemeral Key.
*
* @param string $customer
* @return array
*/
public function create($customer)
{
return $this->_post('ephemeral_keys', compact('customer'));
}
/**
* Deletes the given Ephemeral Key.
*
* @param string $ephemeralKey
* @return array
*/
public function delete($ephemeralKey)
{
return $this->_delete("ephemeral_keys/{$ephemeralKey}");
}
}
| <?php
/**
* Part of the Stripe package.
*
* NOTICE OF LICENSE
*
* Licensed under the 3-clause BSD License.
*
* This source file is subject to the 3-clause BSD License that is
* bundled with this package in the LICENSE file.
*
* @package Stripe
* @version 2.1.0
* @author Cartalyst LLC
* @license BSD License (3-clause)
* @copyright (c) 2011-2018, Cartalyst LLC
* @link http://cartalyst.com
*/
namespace Cartalyst\Stripe\Api;
class EphemeralKey extends Api
{
/**
* Creates a new Ephemeral Key.
*
* @param string $customer
* @return array
*/
public function create(string $customer)
{
return $this->_post('ephemeral_keys', compact('customer'));
}
/**
* Deletes the given Ephemeral Key.
*
* @param string $ephemeralKey
* @return array
*/
public function delete(string $ephemeralKey)
{
return $this->_delete("ephemeral_keys/{$ephemeralKey}");
}
}
|
Fix PDO password param definition | <?php
chdir(dirname(__DIR__));
if (php_sapi_name() === 'cli-server' && is_file( dirname(__FILE__) . $_SERVER['REQUEST_URI'])) {
return false;
}
# setup autoloading
require 'vendor/autoload.php';
# starts the session, required for flash messages
session_start();
# load configs
$config = array_replace_recursive(require 'config-defaults.php', file_exists('config.php') ? require 'config.php' : array());
# wireup dependencies
$injector = new Auryn\Provider();
$injector->define('Ed\Model', array(':config' => $config));
$injector->define('PDO', array(':dsn' => $config['db']['dsn'], ':username' => $config['db']['username'], ':passwd' => $config['db']['password']));
# initialize locale
# note: will not work on builtin server
putenv('LC_ALL=' . $config['ui']['locale']);
setlocale(LC_ALL, $config['ui']['locale']);
bindtextdomain('messages', 'locales');
textdomain('messages');
# handle request
\Http\Resource::handle($config['resources'], array($injector, 'make'));
| <?php
chdir(dirname(__DIR__));
if (php_sapi_name() === 'cli-server' && is_file( dirname(__FILE__) . $_SERVER['REQUEST_URI'])) {
return false;
}
# setup autoloading
require 'vendor/autoload.php';
# starts the session, required for flash messages
session_start();
# load configs
$config = array_replace_recursive(require 'config-defaults.php', file_exists('config.php') ? require 'config.php' : array());
# wireup dependencies
$injector = new Auryn\Provider();
$injector->define('Ed\Model', array(':config' => $config));
$injector->define('PDO', array(':dsn' => $config['db']['dsn'], ':username' => $config['db']['username'], ':password' => $config['db']['password']));
# initialize locale
# note: will not work on builtin server
putenv('LC_ALL=' . $config['ui']['locale']);
setlocale(LC_ALL, $config['ui']['locale']);
bindtextdomain('messages', 'locales');
textdomain('messages');
# handle request
\Http\Resource::handle($config['resources'], array($injector, 'make'));
|
Fix tooltip flickering on Firefox. | import { getSelectedAlgorithm } from './utils.js';
import {
secretInput,
secretBase64Checkbox,
} from '../dom-elements.js';
import log from 'loglevel';
import tippy from 'tippy.js';
import { b64utohex, utf8tohex } from 'jsrsasign';
export function minSecretLengthCheck(event) {
const alg = getSelectedAlgorithm();
if(alg.indexOf('HS') !== 0) {
log.error(`Secret input tooltip handler for wrong algorithm: ${alg}`);
return;
}
const algBits = parseInt(alg.substr(2));
const inputBits = secretBase64Checkbox.checked ?
b64utohex(secretInput.value).length / 2 * 8 :
utf8tohex(secretInput.value).length / 2 * 8;
console.log(utf8tohex(secretInput.value));
if(inputBits < algBits) {
if(!secretInput._tippy.state.visible) {
secretInput._tippy.show();
}
} else {
secretInput._tippy.hide();
}
}
export function setupSecretLengthTooltip() {
tippy(secretInput, {
trigger: 'manual',
placement: 'right',
arrow: true,
arrowTransform: 'scale(0.75)',
size: 'large'
});
}
| import { getSelectedAlgorithm } from './utils.js';
import {
secretInput,
secretBase64Checkbox,
} from '../dom-elements.js';
import log from 'loglevel';
import tippy from 'tippy.js';
import { b64utohex, utf8tohex } from 'jsrsasign';
export function minSecretLengthCheck(event) {
const alg = getSelectedAlgorithm();
if(alg.indexOf('HS') !== 0) {
log.error(`Secret input tooltip handler for wrong algorithm: ${alg}`);
return;
}
const algBits = parseInt(alg.substr(2));
const inputBits = secretBase64Checkbox.checked ?
b64utohex(secretInput.value).length / 2 * 8 :
utf8tohex(secretInput.value).length / 2 * 8;
console.log(utf8tohex(secretInput.value));
if(inputBits < algBits) {
secretInput._tippy.show();
} else {
secretInput._tippy.hide();
}
}
export function setupSecretLengthTooltip() {
tippy(secretInput, {
trigger: 'manual',
placement: 'right',
arrow: true,
arrowTransform: 'scale(0.75)',
size: 'large'
});
}
|
Fix imports style and made feed_name optional | from __future__ import unicode_literals
from django.core.management import CommandError, BaseCommand
from ....integrations.feeds import SaleorFeed
from ....integrations import utils
class Command(BaseCommand):
help = ('Updates integration feeds.'
'If feed name not provided, updates all available feeds')
feed_classes = {'saleor': SaleorFeed}
def add_arguments(self, parser):
parser.add_argument('feed_name', nargs='*', type=str, default=None)
def handle(self, *args, **options):
feed_names = options.get('feed_name') or self.feed_classes.keys()
for feed_name in feed_names:
feed = self.feed_classes.get(feed_name)
if feed is None:
raise CommandError('Feed "%s" does not exist' % feed_name)
utils.update_feed(feed())
| from __future__ import unicode_literals
from django.core.management import CommandError, BaseCommand
from saleor.integrations.feeds import SaleorFeed
from saleor.integrations import utils
class Command(BaseCommand):
help = 'Updates integration feeds. '
feed_classes = {'saleor': SaleorFeed}
def add_arguments(self, parser):
parser.add_argument('feed_name', nargs='+', type=str)
def handle(self, *args, **options):
feed_names = options['feed_name'] or self.feed_classes.keys()
for feed_name in feed_names:
feed = self.feed_classes.get(feed_name)
if feed is None:
raise CommandError('Feed "%s" does not exist' % feed_name)
utils.update_feed(feed())
|
Choose the pulses to update depending on library | #update waveforms in target sequence from current ChanParams settings.
#Warning: this updates all channels, beware of possible conflicts
import argparse
import sys, os
parser = argparse.ArgumentParser()
parser.add_argument('pyqlabpath', help='path to PyQLab directory')
parser.add_argument('seqPath', help='path of sequence to be updated')
parser.add_argument('seqName', help='name of sequence to be updated')
args = parser.parse_args()
from QGL import *
from QGL.drivers import APS2Pattern
from QGL import config
qubits = ChannelLibrary.channelLib.connectivityG.nodes()
edges = ChannelLibrary.channelLib.connectivityG.edges()
pulseList = []
for q in qubits:
if config.pulse_primitives_lib == 'standard':
pulseList.append([AC(q, ct) for ct in range(24)])
else:
pulseList.append([X90(q), Y90(q), X90m(q), Y90m(q)])
for edge in edges:
pulseList.append(ZX90_CR(edge[0],edge[1]))
#update waveforms in the desired sequence (generated with APS2Pattern.SAVE_WF_OFFSETS = True)
PatternUtils.update_wf_library(pulseList, os.path.normpath(os.path.join(args.seqPath, args.seqName))) | #update waveforms in target sequence from current ChanParams settings.
#Warning: this updates all channels, beware of possible conflicts
import argparse
import sys, os
parser = argparse.ArgumentParser()
parser.add_argument('pyqlabpath', help='path to PyQLab directory')
parser.add_argument('seqPath', help='path of sequence to be updated')
parser.add_argument('seqName', help='name of sequence to be updated')
args = parser.parse_args()
from QGL import *
from QGL.drivers import APS2Pattern
qubits = ChannelLibrary.channelLib.connectivityG.nodes()
edges = ChannelLibrary.channelLib.connectivityG.edges()
pulseList = []
for q in qubits:
pulseList.append([AC(q, ct) for ct in range(24)])
for edge in edges:
pulseList.append(ZX90_CR(edge[0],edge[1]))
#update waveforms in the desired sequence (generated with APS2Pattern.SAVE_WF_OFFSETS = True)
PatternUtils.update_wf_library(pulseList, os.path.normpath(os.path.join(args.seqPath, args.seqName))) |
Allow later versions of libraries, e.g. lxml | from setuptools import setup, find_packages
setup(
name='exchangerates',
version='0.3.3',
description="A module to make it easier to handle historical exchange rates",
long_description="",
classifiers=[
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
'Programming Language :: Python :: 3.7.5'
],
author='Mark Brough',
author_email='mark@brough.io',
url='http://github.com/markbrough/exchangerates',
license='MIT',
packages=find_packages(exclude=['ez_setup', 'examples']),
namespace_packages=[],
include_package_data=True,
zip_safe=False,
install_requires=[
'lxml >= 4.4.0',
'requests >= 2.22.0',
'six >= 1.12.0'
],
entry_points={
}
)
| from setuptools import setup, find_packages
setup(
name='exchangerates',
version='0.3.2',
description="A module to make it easier to handle historical exchange rates",
long_description="",
classifiers=[
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
'Programming Language :: Python :: 3.6'
],
author='Mark Brough',
author_email='mark@brough.io',
url='http://github.com/markbrough/exchangerates',
license='MIT',
packages=find_packages(exclude=['ez_setup', 'examples']),
namespace_packages=[],
include_package_data=True,
zip_safe=False,
install_requires=[
'lxml == 4.4.0',
'requests == 2.22.0',
'six == 1.12.0'
],
entry_points={
}
)
|
Use setting file on /etc | #!/usr/bin/env python
import twitter
import json
class Twitter:
def __init__(self):
with open('/etc/twitter.json') as data_file:
data = json.load(data_file)
encoding = None
self.api = twitter.Api(consumer_key=data["consumer_key"], consumer_secret=data["consumer_secret"],
access_token_key=data["access_key"], access_token_secret=data["access_secret"],
input_encoding=encoding)
def postTweet(self,message):
try:
status = self.api.PostUpdate(message)
except:
#TODO clean message and add more exception
print 'twitter fail because message too long or encoding problem' | #!/usr/bin/env python
import twitter
class Twitter:
def __init__(self):
consumer_key = "WXfZoJi7i8TFmrGOK5Y7dVHon"
consumer_secret = "EE46ezCkgKwy8GaKOFFCuMMoZbwDprnEXjhVMn7vI7cYaTbdcA"
access_key = "867082422885785600-AJ0LdE8vc8uMs21VDv2jrkwkQg9PClG"
access_secret = "qor8vV5kGqQ7mJDeW83uKUk2E8MUGqp5biTTswoN4YEt6"
encoding = None
self.api = twitter.Api(consumer_key=consumer_key, consumer_secret=consumer_secret,
access_token_key=access_key, access_token_secret=access_secret,
input_encoding=encoding)
def postTweet(self,message):
try:
status = self.api.PostUpdate(message)
except:
#TODO clean message and add more exception
print 'twitter fail because message too long or encoding problem' |
Store every single request for debug and security purposes | <?php
require_once('vendor/autoload.php');
if (!PRODUCTION)
{
error_reporting(E_ALL);
ini_set('display_errors','On');
}
function phoxy_conf()
{
$ret = phoxy_default_conf();
$ret["api_xss_prevent"] = PRODUCTION;
return $ret;
}
function default_addons()
{
$ret =
[
"cache" => PRODUCTION ? ['global' => '10m'] : "no",
"result" => "canvas",
];
return $ret;
}
include('phoxy/phoxy_return_worker.php');
phoxy_return_worker::$add_hook_cb = function($that)
{
global $USER_SENSITIVE;
if ($USER_SENSITIVE)
$that->obj['cache'] = 'no';
};
phpsql\OneLineConfig(conf()->db->connection_string);
db::Query("INSERT INTO requests(url, get, post, headers, server) VALUES ($1, $2, $3, $4, $5)",
[
$_SERVER['QUERY_STRING'],
json_encode($_GET),
json_encode($_POST),
json_encode(getallheaders()),
json_encode($_SERVER),
]);
include('phoxy/load.php'); | <?php
require_once('vendor/autoload.php');
if (!PRODUCTION)
{
error_reporting(E_ALL);
ini_set('display_errors','On');
}
function phoxy_conf()
{
$ret = phoxy_default_conf();
$ret["api_xss_prevent"] = PRODUCTION;
return $ret;
}
function default_addons()
{
$ret =
[
"cache" => PRODUCTION ? ['global' => '10m'] : "no",
"result" => "canvas",
];
return $ret;
}
include('phoxy/phoxy_return_worker.php');
phoxy_return_worker::$add_hook_cb = function($that)
{
global $USER_SENSITIVE;
if ($USER_SENSITIVE)
$that->obj['cache'] = 'no';
};
phpsql\OneLineConfig(conf()->db->connection_string);
include('phoxy/load.php'); |
Make stage outputter a little cleaner | '''
Display clean output of an overstate stage
'''
#[{'group2': {'match': ['fedora17-2', 'fedora17-3'],
# 'require': ['group1'],
# 'sls': ['nginx', 'edit']}
# }
# ]
# Import Salt libs
import salt.utils
def output(data):
'''
Format the data for printing stage information from the overstate system
'''
colors = salt.utils.get_colors(__opts__.get('color'))
ostr = ''
for comp in data:
for name, stage in comp.items():
ostr += '{0}{1}: {2}\n'.format(
colors['LIGHT_BLUE'],
name,
colors['ENDC'])
for key in sorted(stage):
ostr += ' {0}{1}: {2}{3}\n'.format(
colors['LIGHT_BLUE'],
key,
stage[key],
colors['ENDC'])
return ostr
| '''
Display clean output of an overstate stage
'''
#[{'group2': {'match': ['fedora17-2', 'fedora17-3'],
# 'require': ['group1'],
# 'sls': ['nginx', 'edit']}
# }
# ]
# Import Salt libs
import salt.utils
def output(data):
'''
Format the data for printing stage information from the overstate system
'''
colors = salt.utils.get_colors(__opts__.get('color'))
ostr = ''
for comp in data:
for name, stage in comp.items():
ostr += '{0}{1}:{2}\n'.format(colors['LIGHT_BLUE'], name, colors['ENDC'])
for key in sorted(stage):
ostr += ' {0}{1}:{2}{3}\n'.format(
colors['LIGHT_BLUE'],
key,
stage[key],
colors['ENDC'])
return ostr
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.