text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Update test for importing from a legacy package. | import { a, b, c, C, F } from "import-export-from.js";
import { legacyRelative } from "node:./import-export-legacy.js";
import { exports as legacyPackage } from "node:pkg";
export var tests = {
"imports and exports" (test) {
test
._("exported variables")
.equals(a, "export-a")
.equals(b, "export-b")
.equals(c, "export-c")
._("functions")
.equals(F(), "export-F")
._("classes")
.equals(C.x(), "export-C")
;
},
"legacy import" (test) {
test
._("relative import")
.equals(legacyRelative, "legacy-relative")
._("package import with default")
.equals(legacyPackage(), "legacy-package")
;
}
};
| import { a, b, c, C, F } from "import-export-from.js";
import { legacyRelative } from "node:./import-export-legacy.js";
import { default as legacyPackage } from "node:pkg";
export var tests = {
"imports and exports" (test) {
test
._("exported variables")
.equals(a, "export-a")
.equals(b, "export-b")
.equals(c, "export-c")
._("functions")
.equals(F(), "export-F")
._("classes")
.equals(C.x(), "export-C")
;
},
"legacy import" (test) {
test
._("relative import")
.equals(legacyRelative, "legacy-relative")
._("package import with default")
.equals(legacyPackage, "legacy-package")
;
}
};
|
Make serialize null values option to false | <?php
namespace Serializer;
/**
* Class SerializationContext
*
* @package Serializer
* @author Tales Santos <tales.maxmilhas@gmail.com>
*/
class SerializationContext
{
private $groups = ['Default'];
private $serializeNull = false;
public static function create(): SerializationContext
{
return new self;
}
/**
* @param array $groups
* @return SerializationContext
*/
public function setGroups(array $groups): SerializationContext
{
$this->groups = $groups;
return $this;
}
public function getGroups(): array
{
return $this->groups;
}
public function setSerializeNull(bool $enabled)
{
$this->serializeNull = $enabled;
return $this;
}
public function shouldSerializeNull(): bool
{
return $this->serializeNull;
}
}
| <?php
namespace Serializer;
/**
* Class SerializationContext
*
* @package Serializer
* @author Tales Santos <tales.maxmilhas@gmail.com>
*/
class SerializationContext
{
private $groups = ['Default'];
private $serializeNull = true;
public static function create(): SerializationContext
{
return new self;
}
/**
* @param array $groups
* @return SerializationContext
*/
public function setGroups(array $groups): SerializationContext
{
$this->groups = $groups;
return $this;
}
public function getGroups(): array
{
return $this->groups;
}
public function setSerializeNull(bool $enabled)
{
$this->serializeNull = $enabled;
return $this;
}
public function shouldSerializeNull(): bool
{
return $this->serializeNull;
}
}
|
Update scope to use changed profile | from gevent.wsgi import WSGIServer
from flask import Flask, redirect, url_for
from flask_dance.contrib.google import make_google_blueprint, google
from werkzeug.contrib.fixers import ProxyFix
import os
app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app)
app.secret_key = os.urandom(64)
blueprint = make_google_blueprint(
client_id=os.environ.get('GOOGLE_CLIENT_ID', ''),
client_secret=os.environ.get('GOOGLE_CLIENT_SECRET', ''),
scope=['https://www.googleapis.com/auth/userinfo.profile']
)
app.register_blueprint(blueprint, url_prefix='/login')
@app.route('/')
def index():
if not google.authorized:
return redirect(url_for('google.login'))
resp = google.get('/oauth2/v2/userinfo')
assert resp.ok, resp.text
return '<h2>Your Google OAuth ID is: {}</h2>'.format(resp.json()["id"])
if __name__ == "__main__":
http_server = WSGIServer(('0.0.0.0', 8080), app)
print('serving on {}:{}'.format('0.0.0.0', 8080))
http_server.serve_forever()
| from gevent.wsgi import WSGIServer
from flask import Flask, redirect, url_for
from flask_dance.contrib.google import make_google_blueprint, google
from werkzeug.contrib.fixers import ProxyFix
import os
app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app)
app.secret_key = os.urandom(64)
blueprint = make_google_blueprint(
client_id=os.environ.get('GOOGLE_CLIENT_ID', ''),
client_secret=os.environ.get('GOOGLE_CLIENT_SECRET', ''),
scope=['profile']
)
app.register_blueprint(blueprint, url_prefix='/login')
@app.route('/')
def index():
if not google.authorized:
return redirect(url_for('google.login'))
resp = google.get('/oauth2/v2/userinfo')
assert resp.ok, resp.text
return '<h2>Your Google OAuth ID is: {}</h2>'.format(resp.json()["id"])
if __name__ == "__main__":
http_server = WSGIServer(('0.0.0.0', 8080), app)
print('serving on {}:{}'.format('0.0.0.0', 8080))
http_server.serve_forever()
|
Update default url to encoded one | (function() {
'use strict';
function setEditorValue(val) {
var editor = document.getElementById('editor');
editor.value = val;
}
function getEditorValue() {
var editor = document.getElementById('editor');
return editor.value || '';
}
function decode(url) {
return decodeURIComponent(url);
}
function encode(url) {
return encodeURIComponent(url);
}
// Set default value
setEditorValue(decode(document.URL));
var decoder = document.getElementById('btn-decode');
var encoder = document.getElementById('btn-encode');
// Add Event Listeners
decoder.addEventListener('click', function() {
var url = getEditorValue();
setEditorValue(decode(url));
});
encoder.addEventListener('click', function() {
var url = getEditorValue();
setEditorValue(encode(url));
});
})(); | (function() {
'use strict';
function setEditorValue(val) {
var editor = document.getElementById('editor');
editor.value = val;
}
function getEditorValue() {
var editor = document.getElementById('editor');
return editor.value || '';
}
function decode(url) {
return decodeURIComponent(url);
}
function encode(url) {
return encodeURIComponent(url);
}
// Set default value
setEditorValue(document.URL);
var decoder = document.getElementById('btn-decode');
var encoder = document.getElementById('btn-encode');
// Add Event Listeners
decoder.addEventListener('click', function() {
var url = getEditorValue();
setEditorValue(decode(url));
});
encoder.addEventListener('click', function() {
var url = getEditorValue();
setEditorValue(encode(url));
});
})(); |
Add regex for timestamp and sha. | import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
from router import Router
from views import IndexView, CurrentView, HistoryIndexView, HistoryView
mount_path = '/tmp/gitfs/mnt'
router = Router(remote_url='/home/zalman/dev/presslabs/test-repo.git',
repos_path='/tmp/gitfs/repos/',
mount_path=mount_path)
# TODO: replace regex with the strict one for the Historyview
# -> r'^/history/(?<date>(19|20)\d\d[-](0[1-9]|1[012])[-](0[1-9]|[12][0-9]|3[01]))/',
router.register(r'^/history/(?P<date>\d{4}-\d{1,2}-\d{1,2})/(?P<time>\d{2}:\d{2}:\d{2})-(?P<commit_sha1>[0-9a-f]{10})', HistoryView)
router.register(r'^/history/(?P<date>\d{4}-\d{1,2}-\d{1,2})', HistoryIndexView)
router.register(r'^/history', HistoryIndexView)
router.register(r'^/current', CurrentView)
router.register(r'^/', IndexView)
from fuse import FUSE
FUSE(router, mount_path, foreground=True, nonempty=True)
| import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
from router import Router
from views import IndexView, CurrentView, HistoryIndexView, HistoryView
mount_path = '/tmp/gitfs/mnt'
router = Router(remote_url='/home/zalman/dev/presslabs/test-repo.git',
repos_path='/tmp/gitfs/repos/',
mount_path=mount_path)
# TODO: replace regex with the strict one for the Historyview
# -> r'^/history/(?<date>(19|20)\d\d[-](0[1-9]|1[012])[-](0[1-9]|[12][0-9]|3[01]))/',
router.register(r'^/history/(?P<date>\d{4}-\d{1,2}-\d{1,2})', HistoryView)
router.register(r'^/history', HistoryIndexView)
router.register(r'^/current', CurrentView)
router.register(r'^/', IndexView)
from fuse import FUSE
FUSE(router, mount_path, foreground=True, nonempty=True)
|
Add punctuation to be consistent | package buffalo
import (
"net/http"
"github.com/gorilla/sessions"
)
// Session wraps the "github.com/gorilla/sessions" API
// in something a little cleaner and a bit more useable.
type Session struct {
Session *sessions.Session
req *http.Request
res http.ResponseWriter
}
// Save the current session.
func (s *Session) Save() error {
return s.Session.Save(s.req, s.res)
}
// Get a value from the current session.
func (s *Session) Get(name interface{}) interface{} {
return s.Session.Values[name]
}
// Set a value onto the current session. If a value with that name
// already exists it will be overridden with the new value.
func (s *Session) Set(name, value interface{}) {
s.Session.Values[name] = value
}
// Delete a value from the current session.
func (s *Session) Delete(name interface{}) {
delete(s.Session.Values, name)
}
// Get a session using a request and response.
func (a *App) getSession(r *http.Request, w http.ResponseWriter) *Session {
session, _ := a.SessionStore.Get(r, a.SessionName)
return &Session{
Session: session,
req: r,
res: w,
}
}
| package buffalo
import (
"net/http"
"github.com/gorilla/sessions"
)
// Session wraps the "github.com/gorilla/sessions" API
// in something a little cleaner and a bit more useable.
type Session struct {
Session *sessions.Session
req *http.Request
res http.ResponseWriter
}
// Save the current session
func (s *Session) Save() error {
return s.Session.Save(s.req, s.res)
}
// Get a value from the current session
func (s *Session) Get(name interface{}) interface{} {
return s.Session.Values[name]
}
// Set a value onto the current session. If a value with that name
// already exists it will be overridden with the new value.
func (s *Session) Set(name, value interface{}) {
s.Session.Values[name] = value
}
// Delete a value from the current session.
func (s *Session) Delete(name interface{}) {
delete(s.Session.Values, name)
}
// Get a session using a request and response.
func (a *App) getSession(r *http.Request, w http.ResponseWriter) *Session {
session, _ := a.SessionStore.Get(r, a.SessionName)
return &Session{
Session: session,
req: r,
res: w,
}
}
|
Remove unique constraint for ListSubscribers table | 'use strict';
module.exports = function(sequelize, DataTypes) {
var listsubscriber = sequelize.define('listsubscriber', {
email: DataTypes.STRING,
subscribed: { type: DataTypes.BOOLEAN, defaultValue: true },
unsubscribeKey: { type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4 },
mostRecentStatus: { type: DataTypes.STRING, defaultValue: 'unconfirmed' }, // bounce:permanent, bounce:transient, complaint
additionalData: { type: DataTypes.JSONB, defaultValue: {} }
}, {
classMethods: {
associate: function(models) {
// associations can be defined here
listsubscriber.belongsTo(models.list);
listsubscriber.hasMany(models.campaignanalyticslink);
listsubscriber.hasMany(models.campaignanalyticsopen);
listsubscriber.hasMany(models.campaignsubscriber);
}
},
indexes: [
{
fields:['email']
}
]
});
return listsubscriber;
};
| 'use strict';
module.exports = function(sequelize, DataTypes) {
var listsubscriber = sequelize.define('listsubscriber', {
email: DataTypes.STRING,
subscribed: { type: DataTypes.BOOLEAN, defaultValue: true },
unsubscribeKey: { type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4 },
mostRecentStatus: { type: DataTypes.STRING, defaultValue: 'unconfirmed' }, // bounce:permanent, bounce:transient, complaint
additionalData: { type: DataTypes.JSONB, defaultValue: {} }
}, {
classMethods: {
associate: function(models) {
// associations can be defined here
listsubscriber.belongsTo(models.list);
listsubscriber.hasMany(models.campaignanalyticslink);
listsubscriber.hasMany(models.campaignanalyticsopen);
listsubscriber.hasMany(models.campaignsubscriber);
}
},
indexes: [
{
unique: true,
fields:['email']
}
]
});
return listsubscriber;
};
|
Prepend “Mc” to expected exception name | from nose.tools import assert_raises
from mediawords.db.schema.version import *
def test_schema_version_from_lines():
assert_raises(McSchemaVersionFromLinesException, schema_version_from_lines, 'no version')
# noinspection SqlDialectInspection,SqlNoDataSourceInspection
assert schema_version_from_lines("""
CREATE OR REPLACE FUNCTION set_database_schema_version() RETURNS boolean AS $$
DECLARE
-- Database schema version number (same as a SVN revision number)
-- Increase it by 1 if you make major database schema changes.
MEDIACLOUD_DATABASE_SCHEMA_VERSION CONSTANT INT := 4588;
BEGIN
-- Update / set database schema version
DELETE FROM database_variables WHERE name = 'database-schema-version';
INSERT INTO database_variables (name, value) VALUES
('database-schema-version', MEDIACLOUD_DATABASE_SCHEMA_VERSION::int);
return true;
END;
$$
LANGUAGE 'plpgsql';
""") == 4588
| from nose.tools import assert_raises
from mediawords.db.schema.version import *
def test_schema_version_from_lines():
assert_raises(SchemaVersionFromLinesException, schema_version_from_lines, 'no version')
# noinspection SqlDialectInspection,SqlNoDataSourceInspection
assert schema_version_from_lines("""
CREATE OR REPLACE FUNCTION set_database_schema_version() RETURNS boolean AS $$
DECLARE
-- Database schema version number (same as a SVN revision number)
-- Increase it by 1 if you make major database schema changes.
MEDIACLOUD_DATABASE_SCHEMA_VERSION CONSTANT INT := 4588;
BEGIN
-- Update / set database schema version
DELETE FROM database_variables WHERE name = 'database-schema-version';
INSERT INTO database_variables (name, value) VALUES
('database-schema-version', MEDIACLOUD_DATABASE_SCHEMA_VERSION::int);
return true;
END;
$$
LANGUAGE 'plpgsql';
""") == 4588
|
Remove newline characters at the end of each string | const Assert = require('assert');
const Child = require('child_process');
const Fs = require('fs');
const Path = require('path');
var packagePath = Path.join(process.cwd(), 'package.json');
var out = Object.prototype, keys = [];
function execute(options, done) {
var key = keys.shift();
if (!key) return done(null, out);
Child.exec(options[key], function (err, stdout) {
out[key] = err ? err.toString() : stdout.replace(/\n/g, '');
return execute(options, done);
});
}
module.exports = function (options, done) {
if (typeof options === 'function') {
done = options;
options = {};
}
Assert.equal(typeof options, 'object', 'Options must be an object');
Assert.equal(typeof done, 'function', 'Must pass in a callback function');
options = Object.assign({ node: 'node -v', npm: 'npm -v' }, options);
keys = Object.keys(options);
Fs.readFile(packagePath, 'utf8', function (err, packageJson) {
if (err) return done(err);
packageJson = JSON.parse(packageJson);
out = {
name: packageJson.name,
version: packageJson.version,
env: process.env.NODE_ENV // eslint-disable-line no-process-env
};
return execute(options, done);
});
};
| const Assert = require('assert');
const Child = require('child_process');
const Fs = require('fs');
const Path = require('path');
var packagePath = Path.join(process.cwd(), 'package.json');
var out = Object.prototype, keys = [];
function execute(options, done) {
var key = keys.shift();
if (!key) return done(null, out);
Child.exec(options[key], function (err, stdout) {
out[key] = err ? err.toString() : stdout;
return execute(options, done);
});
}
module.exports = function (options, done) {
if (typeof options === 'function') {
done = options;
options = {};
}
Assert.equal(typeof options, 'object', 'Options must be an object');
Assert.equal(typeof done, 'function', 'Must pass in a callback function');
options = Object.assign({ node: 'node -v', npm: 'npm -v' }, options);
keys = Object.keys(options);
Fs.readFile(packagePath, 'utf8', function (err, packageJson) {
if (err) return done(err);
packageJson = JSON.parse(packageJson);
out = {
name: packageJson.name,
version: packageJson.version,
env: process.env.NODE_ENV // eslint-disable-line no-process-env
};
return execute(options, done);
});
};
|
Remove an unnecessary arrow function | import mapValues from 'lodash.mapValues';
import isPlainObject from 'lodash.isPlainObject';
import { Iterable } from 'immutable';
export function isImmutable(obj) {
return Iterable.isIterable(obj);
}
export function toJS(obj) {
return obj.toJS();
}
export function toJSDeep(obj) {
/* eslint no-use-before-define: 0 */
return mapValues(obj, convert);
}
export function convert(obj) {
if (isImmutable(obj)) {
return toJS(obj);
} else if (isPlainObject(obj)) {
return toJSDeep(obj);
}
return obj;
}
export default function immutableToJS() {
return createStore => (reducer, initialState) => {
const store = createStore(reducer, initialState);
return {
...store,
getState: () => {
const state = store.getState();
return convert(state);
},
};
};
}
| import mapValues from 'lodash.mapValues';
import isPlainObject from 'lodash.isPlainObject';
import { Iterable } from 'immutable';
export function isImmutable(obj) {
return Iterable.isIterable(obj);
}
export function toJS(obj) {
return obj.toJS();
}
export function toJSDeep(obj) {
/* eslint no-use-before-define: 0 */
return mapValues(obj, value => convert(value));
}
export function convert(obj) {
if (isImmutable(obj)) {
return toJS(obj);
} else if (isPlainObject(obj)) {
return toJSDeep(obj);
}
return obj;
}
export default function immutableToJS() {
return createStore => (reducer, initialState) => {
const store = createStore(reducer, initialState);
return {
...store,
getState: () => {
const state = store.getState();
return convert(state);
},
};
};
}
|
Change back extension command name | package extension
import (
"fmt"
"github.com/kayex/sirius"
"golang.org/x/net/context"
"googlemaps.github.io/maps"
)
type Geocode struct {
APIKey string
}
func (x *Geocode) Run(m sirius.Message, cfg sirius.ExtensionConfig) (sirius.MessageAction, error) {
cmd, match := m.Command("address")
if !match {
return sirius.NoAction(), nil
}
c, err := maps.NewClient(maps.WithAPIKey(x.APIKey))
if err != nil {
return nil, err
}
r := &maps.GeocodingRequest{
Address: cmd.Args[0],
}
res, err := c.Geocode(context.Background(), r)
if err != nil {
return nil, err
}
pos := res[0]
location := pos.Geometry.Location
formatted := fmt.Sprintf("*%v*\n`(%.6f, %.6f)`", pos.FormattedAddress, location.Lat, location.Lng)
edit := m.EditText().ReplaceWith(formatted)
return edit, nil
}
| package extension
import (
"fmt"
"github.com/kayex/sirius"
"golang.org/x/net/context"
"googlemaps.github.io/maps"
)
type Geocode struct {
APIKey string
}
func (x *Geocode) Run(m sirius.Message, cfg sirius.ExtensionConfig) (sirius.MessageAction, error) {
cmd, match := m.Command("geocode")
if !match {
return sirius.NoAction(), nil
}
c, err := maps.NewClient(maps.WithAPIKey(x.APIKey))
if err != nil {
return nil, err
}
r := &maps.GeocodingRequest{
Address: cmd.Args[0],
}
res, err := c.Geocode(context.Background(), r)
if err != nil {
return nil, err
}
pos := res[0]
location := pos.Geometry.Location
formatted := fmt.Sprintf("*%v*\n`(%.6f, %.6f)`", pos.FormattedAddress, location.Lat, location.Lng)
edit := m.EditText().ReplaceWith(formatted)
return edit, nil
}
|
Fix code style issues with Black | # -*- coding: utf-8 -*-
import os
from scout.demo import cnv_report_path
from scout.commands import cli
def test_load_cnv_report(mock_app, case_obj):
"""Testing the load delivery report cli command"""
# Make sure the path to delivery report is a valid path
assert os.path.isfile(cnv_report_path)
runner = mock_app.test_cli_runner()
assert runner
# Test CLI function
result = runner.invoke(
cli,
["load", "cnv-report", case_obj["_id"], cnv_report_path, "-u"],
)
assert "saved report to case!" in result.output
assert result.exit_code == 0
def test_invalid_path_load_cnv_report(mock_app, case_obj):
"""Testing the load delivery report cli command"""
runner = mock_app.test_cli_runner()
assert runner
# Test CLI function
result = runner.invoke(
cli,
["load", "cnv-report", case_obj["_id"], "invalid-path", "-u"],
)
assert "Path 'invalid-path' does not exist." in result.output
assert result.exit_code == 2
| # -*- coding: utf-8 -*-
import os
from scout.demo import cnv_report_path
from scout.commands import cli
def test_load_cnv_report(mock_app, case_obj):
"""Testing the load delivery report cli command"""
# Make sure the path to delivery report is a valid path
assert os.path.isfile(cnv_report_path)
runner = mock_app.test_cli_runner()
assert runner
# Test CLI function
result = runner.invoke(cli, ["load", "cnv-report", case_obj["_id"], cnv_report_path, "-u"],)
assert "saved report to case!" in result.output
assert result.exit_code == 0
def test_invalid_path_load_cnv_report(mock_app, case_obj):
"""Testing the load delivery report cli command"""
runner = mock_app.test_cli_runner()
assert runner
# Test CLI function
result = runner.invoke(cli, ["load", "cnv-report", case_obj["_id"], "invalid-path", "-u"],)
assert "Path 'invalid-path' does not exist." in result.output
assert result.exit_code == 2
|
Add missing assertion in test | from __future__ import absolute_import
from django.db import models
from sentry.utils.models import Model
from sentry.testutils import TestCase
# There's a good chance this model wont get created in the db, so avoid
# assuming it exists in these tests.
class DummyModel(Model):
foo = models.CharField(max_length=32)
class ModelTest(TestCase):
def test_foo_hasnt_changed_on_init(self):
inst = DummyModel(id=1, foo='bar')
self.assertFalse(inst.has_changed('foo'))
def test_foo_has_changes_before_save(self):
inst = DummyModel(id=1, foo='bar')
inst.foo = 'baz'
self.assertTrue(inst.has_changed('foo'))
self.assertEquals(inst.old_value('foo'), 'bar')
def test_foo_hasnt_changed_after_save(self):
inst = DummyModel(id=1, foo='bar')
inst.foo = 'baz'
self.assertTrue(inst.has_changed('foo'))
self.assertEquals(inst.old_value('foo'), 'bar')
models.signals.post_save.send(instance=inst, sender=type(inst), created=False)
self.assertFalse(inst.has_changed('foo'))
| from __future__ import absolute_import
from django.db import models
from sentry.utils.models import Model
from sentry.testutils import TestCase
# There's a good chance this model wont get created in the db, so avoid
# assuming it exists in these tests.
class DummyModel(Model):
foo = models.CharField(max_length=32)
class ModelTest(TestCase):
def test_foo_hasnt_changed_on_init(self):
inst = DummyModel(id=1, foo='bar')
self.assertFalse(inst.has_changed('foo'))
def test_foo_has_changes_before_save(self):
inst = DummyModel(id=1, foo='bar')
inst.foo = 'baz'
self.assertTrue(inst.has_changed('foo'))
self.assertEquals(inst.old_value('foo'), 'bar')
def test_foo_hasnt_changed_after_save(self):
inst = DummyModel(id=1, foo='bar')
inst.foo = 'baz'
self.assertTrue(inst.has_changed('foo'))
self.assertEquals(inst.old_value('foo'), 'bar')
models.signals.post_save.send(instance=inst, sender=type(inst), created=False)
|
Add update to PRescriptionPage using new reducer | /* eslint-disable react/forbid-prop-types */
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Wizard } from '../widgets';
import { PrescriberSelect } from '../widgets/Tabs/PrescriberSelect';
import { ItemSelect } from '../widgets/Tabs/ItemSelect';
import { PrescriptionConfirmation } from '../widgets/Tabs/PrescriptionConfirmation';
import { useRecordListener } from '../hooks';
import { WizardActions } from '../actions/WizardActions';
const tabs = [PrescriberSelect, ItemSelect, PrescriptionConfirmation];
const titles = ['Select the Prescriber', 'Select items', 'Finalise'];
export const Prescription = ({ transaction, completePrescription }) => {
useRecordListener(completePrescription, transaction, 'Transaction');
return <Wizard tabs={tabs} titles={titles} />;
};
const mapDispatchToProps = dispatch => {
const completePrescription = () => dispatch(WizardActions.complete());
return { completePrescription };
};
export const PrescriptionPage = connect(null, mapDispatchToProps)(Prescription);
Prescription.propTypes = {
transaction: PropTypes.object.isRequired,
completePrescription: PropTypes.func.isRequired,
};
| /* eslint-disable react/forbid-prop-types */
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Wizard } from '../widgets';
import { PrescriberSelect } from '../widgets/Tabs/PrescriberSelect';
import { ItemSelect } from '../widgets/Tabs/ItemSelect';
import { PrescriptionConfirmation } from '../widgets/Tabs/PrescriptionConfirmation';
import {
selectItem,
selectPrescriber,
switchTab,
editQuantity,
} from '../reducers/PrescriptionReducer';
const mapDispatchToProps = dispatch => {
const choosePrescriber = prescriberID => dispatch(selectPrescriber(prescriberID));
const chooseItem = itemID => dispatch(selectItem(itemID));
const nextTab = currentTab => dispatch(switchTab(currentTab + 1));
const updateQuantity = (id, quantity) => dispatch(editQuantity(id, quantity));
return { nextTab, choosePrescriber, chooseItem, updateQuantity };
};
const mapStateToProps = state => {
const { prescription, patient, prescriber } = state;
return { ...prescription, ...patient, ...prescriber };
};
const tabs = [PrescriberSelect, ItemSelect, PrescriptionConfirmation];
const titles = ['Select the Prescriber', 'Select items', 'Finalise'];
export const Prescription = ({ currentTab, nextTab }) => (
<Wizard tabs={tabs} titles={titles} currentTabIndex={currentTab} onPress={nextTab} />
);
export const PrescriptionPage = connect(mapStateToProps, mapDispatchToProps)(Prescription);
Prescription.propTypes = {
currentTab: PropTypes.number.isRequired,
nextTab: PropTypes.func.isRequired,
};
|
Use the item access variant instead | from django.db import models
from django.utils.timezone import now
from towel import deletion
from towel.managers import SearchManager
from towel.modelview import ModelViewURLs
class PersonManager(SearchManager):
search_fields = ('family_name', 'given_name')
class Person(models.Model):
created = models.DateTimeField(default=now)
family_name = models.CharField(max_length=100)
given_name = models.CharField(max_length=100)
objects = PersonManager()
urls = ModelViewURLs(lambda obj: {'pk': obj.pk})
def __unicode__(self):
return u'%s %s' % (self.given_name, self.family_name)
def get_absolute_url(self):
return self.urls['detail']
class EmailManager(SearchManager):
search_fields = ('person__family_name', 'person__given_name', 'email')
class EmailAddress(deletion.Model):
person = models.ForeignKey(Person)
email = models.EmailField()
objects = EmailManager()
urls = ModelViewURLs(lambda obj: {'pk': obj.pk})
def __unicode__(self):
return self.email
def get_absolute_url(self):
return self.urls['detail']
| from django.db import models
from django.utils.timezone import now
from towel import deletion
from towel.managers import SearchManager
from towel.modelview import ModelViewURLs
class PersonManager(SearchManager):
search_fields = ('family_name', 'given_name')
class Person(models.Model):
created = models.DateTimeField(default=now)
family_name = models.CharField(max_length=100)
given_name = models.CharField(max_length=100)
objects = PersonManager()
urls = ModelViewURLs(lambda obj: {'pk': obj.pk})
def __unicode__(self):
return u'%s %s' % (self.given_name, self.family_name)
def get_absolute_url(self):
return self.urls.url('detail')
class EmailManager(SearchManager):
search_fields = ('person__family_name', 'person__given_name', 'email')
class EmailAddress(deletion.Model):
person = models.ForeignKey(Person)
email = models.EmailField()
objects = EmailManager()
urls = ModelViewURLs(lambda obj: {'pk': obj.pk})
def __unicode__(self):
return self.email
def get_absolute_url(self):
return self.urls.url('detail')
|
Update Nooku Framework, Model::set() has been removed | <?
/**
* Belgian Police Web Platform - Districts Component
*
* @copyright Copyright (C) 2012 - 2013 Timble CVBA. (http://www.timble.net)
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://www.police.be
*/
?>
<? $officers = @object('com:districts.model.districts_officers')->district($district->id)->getRowset(); ?>
<? if(count($officers)) : ?>
<div class="clearfix article separator">
<? foreach ($officers as $officer) : ?>
<?= @template('com:districts.view.district.default_officer.html', array('officer' => @object('com:districts.model.officer')->id($officer->districts_officer_id)->getRow())); ?>
<? endforeach ?>
</div>
<? else : ?>
<h2><?= @text('No neighbourhood officer found') ?></h2>
<? endif ?>
<div class="clearfix">
<?
$contact = @object('com:contacts.model.contact')->id($district->contacts_contact_id)->getRow();
$contact->misc = null;
?>
<?= @template('com:contacts.view.contact.hcard.html', array('contact' => $contact)); ?>
</div> | <?
/**
* Belgian Police Web Platform - Districts Component
*
* @copyright Copyright (C) 2012 - 2013 Timble CVBA. (http://www.timble.net)
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://www.police.be
*/
?>
<? $officers = @object('com:districts.model.districts_officers')->district($district->id)->getRowset(); ?>
<? if(count($officers)) : ?>
<div class="clearfix article separator">
<? foreach ($officers as $officer) : ?>
<?= @template('com:districts.view.district.default_officer.html', array('officer' => @object('com:districts.model.officer')->set('id', $officer->districts_officer_id)->getRow())); ?>
<? endforeach ?>
</div>
<? else : ?>
<h2><?= @text('No neighbourhood officer found') ?></h2>
<? endif ?>
<div class="clearfix">
<?
$contact = @object('com:contacts.model.contact')->set('id', $district->contacts_contact_id)->getRow();
$contact->misc = null;
?>
<?= @template('com:contacts.view.contact.hcard.html', array('contact' => $contact)); ?>
</div> |
Make tests pass in all browsers (co relies on global Promise) | // let referee = require('referee')
// let {assert} = referee
// let {beforeEach, afterEach} = window
//
// // assertions counting
// let expected = 0
// referee.add('expect', {
// assert: (exp) => {
// expected = exp
// return true
// }
// })
// beforeEach(() => {
// referee.count = 0
// })
// afterEach(function () {
// var self = this
// if (expected === false) return
// try {
// assert(expected === referee.count - 1, 'expected ' + expected + ' assertions, got ' + referee.count)
// } catch (err) {
// err.message = err.message + ' in ' + self.currentTest.title
// throw err
// // self.currentTest.emit('error', err)
// // self.test.emit('error', err)
// }
// expected = false
// })
// need to do this for co to work
let Promise = require('es6-promise').Promise
window.Promise = Promise
let testsContext = require.context('.', true, /Test$/)
testsContext.keys().forEach(testsContext)
| // let referee = require('referee')
// let {assert} = referee
// let {beforeEach, afterEach} = window
//
// // assertions counting
// let expected = 0
// referee.add('expect', {
// assert: (exp) => {
// expected = exp
// return true
// }
// })
// beforeEach(() => {
// referee.count = 0
// })
// afterEach(function () {
// var self = this
// if (expected === false) return
// try {
// assert(expected === referee.count - 1, 'expected ' + expected + ' assertions, got ' + referee.count)
// } catch (err) {
// err.message = err.message + ' in ' + self.currentTest.title
// throw err
// // self.currentTest.emit('error', err)
// // self.test.emit('error', err)
// }
// expected = false
// })
let testsContext = require.context('.', true, /Test$/)
testsContext.keys().forEach(testsContext)
|
Add another case to delete | <?php
declare(strict_types=1);
/*
* This file is part of the Sonata Project package.
*
* (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sonata\DoctrineORMAdminBundle\Tests\Functional;
use Symfony\Component\HttpFoundation\Request;
final class BatchActionsTest extends BaseFunctionalTestCase
{
/**
* @dataProvider provideBatchActionsCases
*/
public function testBatchActions(string $url, string $action): void
{
$this->client->request(Request::METHOD_GET, $url);
$this->client->submitForm('OK', [
'all_elements' => true,
'action' => $action,
]);
$this->client->submitForm('Yes, execute');
self::assertResponseIsSuccessful();
}
/**
* @return iterable<array<string>>
*
* @phpstan-return iterable<array{0: string}>
*/
public static function provideBatchActionsCases(): iterable
{
yield 'Normal delete' => ['/admin/tests/app/book/list', 'delete'];
yield 'Joined delete' => ['/admin/tests/app/author/list', 'delete'];
yield 'More than 20 items delete' => ['/admin/tests/app/sub/list', 'delete'];
}
}
| <?php
declare(strict_types=1);
/*
* This file is part of the Sonata Project package.
*
* (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sonata\DoctrineORMAdminBundle\Tests\Functional;
use Symfony\Component\HttpFoundation\Request;
final class BatchActionsTest extends BaseFunctionalTestCase
{
/**
* @dataProvider provideBatchActionsCases
*/
public function testBatchActions(string $url, string $action): void
{
$this->client->request(Request::METHOD_GET, $url);
$this->client->submitForm('OK', [
'all_elements' => true,
'action' => $action,
]);
$this->client->submitForm('Yes, execute');
self::assertResponseIsSuccessful();
}
/**
* @return iterable<array<string>>
*
* @phpstan-return iterable<array{0: string}>
*/
public static function provideBatchActionsCases(): iterable
{
yield 'Normal delete' => ['/admin/tests/app/book/list', 'delete'];
yield 'Joined delete' => ['/admin/tests/app/author/list', 'delete'];
}
}
|
Upgrade version to 0.0.12.post6 (choice_dict)
Signed-off-by: Fabrice Normandin <ee438dab901b32439200d6bb23a0e635234ed3f0@gmail.com> | import sys
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
packages = setuptools.find_namespace_packages(include=['simple_parsing*'])
print("PACKAGES FOUND:", packages)
print(sys.version_info)
setuptools.setup(
name="simple_parsing",
version="0.0.12.post6",
author="Fabrice Normandin",
author_email="fabrice.normandin@gmail.com",
description="A small utility for simplifying and cleaning up argument parsing scripts.",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/lebrice/SimpleParsing",
packages=packages,
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
python_requires='>=3.6',
install_requires=[
"typing_inspect",
"dataclasses;python_version<'3.7'",
]
)
| import sys
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
packages = setuptools.find_namespace_packages(include=['simple_parsing*'])
print("PACKAGES FOUND:", packages)
print(sys.version_info)
setuptools.setup(
name="simple_parsing",
version="0.0.12.post5",
author="Fabrice Normandin",
author_email="fabrice.normandin@gmail.com",
description="A small utility for simplifying and cleaning up argument parsing scripts.",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/lebrice/SimpleParsing",
packages=packages,
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
python_requires='>=3.6',
install_requires=[
"typing_inspect",
"dataclasses;python_version<'3.7'",
]
)
|
Consolidate hasattr + getter to single statement with default value. | # -*- coding: utf-8 -*-
from flask import request
from modularodm.storedobject import StoredObject as GenericStoredObject
from modularodm.ext.concurrency import with_proxies, proxied_members
from bson import ObjectId
from .handlers import client, database, set_up_storage
from api.base.api_globals import api_globals
class DummyRequest(object):
pass
dummy_request = DummyRequest()
def get_cache_key():
"""
Fetch a request key from either a Django or Flask request. Fall back on a process-global dummy object
if we are not in either type of request
"""
# TODO: This is ugly use of exceptions; is there a better way to track whether in a given type of request?
try:
return request._get_current_object()
except RuntimeError: # Not in a flask request context
if getattr(api_globals, 'request', None) is not None:
return api_globals.request
else: # Not in a Django request
return dummy_request
@with_proxies(proxied_members, get_cache_key)
class StoredObject(GenericStoredObject):
pass
__all__ = [
'StoredObject',
'ObjectId',
'client',
'database',
'set_up_storage',
]
| # -*- coding: utf-8 -*-
from flask import request
from modularodm.storedobject import StoredObject as GenericStoredObject
from modularodm.ext.concurrency import with_proxies, proxied_members
from bson import ObjectId
from .handlers import client, database, set_up_storage
from api.base.api_globals import api_globals
class DummyRequest(object):
pass
dummy_request = DummyRequest()
def get_cache_key():
"""
Fetch a request key from either a Django or Flask request. Fall back on a process-global dummy object
if we are not in either type of request
"""
# TODO: This is ugly use of exceptions; is there a better way to track whether in a given type of request?
try:
return request._get_current_object()
except RuntimeError: # Not in a flask request context
if hasattr(api_globals, 'request') and api_globals.request is not None:
return api_globals.request
else: # Not in a Django request
return dummy_request
@with_proxies(proxied_members, get_cache_key)
class StoredObject(GenericStoredObject):
pass
__all__ = [
'StoredObject',
'ObjectId',
'client',
'database',
'set_up_storage',
]
|
Fix NPE because deltaValue can be null | package org.hiero.sketch.dataset.api;
import java.io.Serializable;
/**
* A partial result always describes a DELTA between the previous partial result
* and the current one.
* @param <T> Type of data in partial result.
*/
public class PartialResult<T> implements Serializable {
/**
* How much more has been deltaDone from the computation has been deltaDone
* since the previous partial result. A number between 0 and 1. Even if this
* is 1, it does not necessarily mean that the work is finished.
*/
public final double deltaDone;
/**
* Additional data computed since the previous partial result.
*/
public final T deltaValue;
/**
* Creates a partial result.
* @param deltaDone How much more has been done. A number between 0 and 1.
* @param deltaValue Extra result produced.
*/
public PartialResult(double deltaDone, final T deltaValue) {
if (deltaDone < 0) {
throw new RuntimeException("Illegal value for deltaDone");
} else if (deltaDone > 1) {
// This can happen due to double addition imprecision.
deltaDone = 1.0;
}
this.deltaDone = deltaDone;
this.deltaValue = deltaValue;
}
@Override
public String toString() {
return "PR[" + Double.toString(this.deltaDone) + "," + this.deltaValue + "]";
}
}
| package org.hiero.sketch.dataset.api;
import java.io.Serializable;
/**
* A partial result always describes a DELTA between the previous partial result
* and the current one.
* @param <T> Type of data in partial result.
*/
public class PartialResult<T> implements Serializable {
/**
* How much more has been deltaDone from the computation has been deltaDone
* since the previous partial result. A number between 0 and 1. Even if this
* is 1, it does not necessarily mean that the work is finished.
*/
public final double deltaDone;
/**
* Additional data computed since the previous partial result.
*/
public final T deltaValue;
/**
* Creates a partial result.
* @param deltaDone How much more has been done. A number between 0 and 1.
* @param deltaValue Extra result produced.
*/
public PartialResult(double deltaDone, final T deltaValue) {
if (deltaDone < 0) {
throw new RuntimeException("Illegal value for deltaDone");
} else if (deltaDone > 1) {
// This can happen due to double addition imprecision.
deltaDone = 1.0;
}
this.deltaDone = deltaDone;
this.deltaValue = deltaValue;
}
@Override
public String toString() {
return "PR[" + Double.toString(this.deltaDone) + "," + this.deltaValue.toString() + "]";
}
}
|
Add a note about autoloading (ProvidePlugin options) | let mix = require('laravel-mix');
/*
|--------------------------------------------------------------------------
| Mix Asset Management
|--------------------------------------------------------------------------
|
| Mix provides a clean, fluent API for defining some Webpack build steps
| for your Laravel application. By default, we are compiling the Sass
| file for your application, as well as bundling up your JS files.
|
*/
mix.js('src/app.js', 'dist/')
.sass('src/app.scss', 'dist/');
// Full API
// mix.js(src, output);
// mix.extract(vendorLibs);
// mix.sass(src, output);
// mix.less(src, output);
// mix.combine(files, destination);
// mix.copy(from, to);
// mix.minify(file);
// mix.sourceMaps(); // Enable sourcemaps
// mix.version(); // Enable versioning.
// mix.disableNotifications();
// mix.setPublicPath('path/to/public');
// mix.autoload({}); <-- Will be passed to Webpack's ProvidePlugin.
// mix.webpackConfig({}); <-- Override webpack.config.js, without editing the file directly.
| let mix = require('laravel-mix');
/*
|--------------------------------------------------------------------------
| Mix Asset Management
|--------------------------------------------------------------------------
|
| Mix provides a clean, fluent API for defining some Webpack build steps
| for your Laravel application. By default, we are compiling the Sass
| file for your application, as well as bundling up your JS files.
|
*/
mix.js('src/app.js', 'dist/')
.sass('src/app.scss', 'dist/');
// Full API
// mix.js(src, output);
// mix.extract(vendorLibs);
// mix.sass(src, output);
// mix.less(src, output);
// mix.combine(files, destination);
// mix.copy(from, to);
// mix.minify(file);
// mix.sourceMaps(); // Enable sourcemaps
// mix.version(); // Enable versioning.
// mix.disableNotifications();
// mix.setPublicPath('path/to/public'); <-- Useful for Node apps.
// mix.webpackConfig({}); <-- Override webpack.config.js, without editing the file directly.
|
Change module type on typescript for server side compilation to commonjs
Signed-off-by: Michele Ursino <0d7cbec952c33d7c21e19d50988899883a4c91e0@amilink.com> | var gulp = require('gulp');
var watch = require('gulp-watch');
var uglify = require('gulp-uglify');
var print = require('gulp-print');
var tsc = require('gulp-tsc');
gulp.task('ts_server', function() {
return gulp.src( [ '*.ts', '**/*.ts', '!./public/**/*.ts', '!./node_modules/**/*.ts' ] )
.pipe( print(function(filepath) { return "TSC server side: " + filepath; } ) )
.pipe( tsc( { module: 'commonjs', target: 'ES5', sourcemap: false, emitError: false } ) )
.pipe(gulp.dest('./'))
.pipe( print(function(filepath) { return "Result: " + filepath; } ) );
});
gulp.task('ts_client', function() {
return gulp.src( [ './public/**/*.ts' ] )
.pipe( print( function(filepath) { return "Tsc client side: " + filepath; } ) )
.pipe( tsc( { module: 'amd', target: 'ES5', sourcemap: true, emitError: false } ) )
.pipe(gulp.dest('./'));
});
// Default Task
gulp.task( 'default', ['ts_server','ts_client'] );
| var gulp = require('gulp');
var watch = require('gulp-watch');
var uglify = require('gulp-uglify');
var print = require('gulp-print');
var tsc = require('gulp-tsc');
gulp.task('ts_server', function() {
return gulp.src( [ '*.ts', '**/*.ts', '!./public/**/*.ts', '!./node_modules/**/*.ts' ] )
.pipe( print(function(filepath) { return "TSC server side: " + filepath; } ) )
.pipe( tsc( { module: 'amd', target: 'ES5', sourcemap: false, emitError: false } ) )
.pipe(gulp.dest('./'))
.pipe( print(function(filepath) { return "Result: " + filepath; } ) );
});
gulp.task('ts_client', function() {
return gulp.src( [ './public/**/*.ts' ] )
.pipe( print( function(filepath) { return "Tsc client side: " + filepath; } ) )
.pipe( tsc( { module: 'amd', target: 'ES5', sourcemap: true, emitError: false } ) )
.pipe(gulp.dest('./'));
});
// Default Task
gulp.task( 'default', ['ts_server','ts_client'] );
|
:fire: Clean exports from typer, remove unneeded Click components, add needed ones
Clean exports from typer, remove unneeded Click components | """Typer, build great CLIs. Easy to code. Based on Python type hints."""
__version__ = "0.0.4"
from click.exceptions import Abort, Exit # noqa
from click.termui import ( # noqa
clear,
confirm,
echo_via_pager,
edit,
get_terminal_size,
getchar,
launch,
pause,
progressbar,
prompt,
secho,
style,
unstyle,
)
from click.utils import ( # noqa
echo,
format_filename,
get_app_dir,
get_binary_stream,
get_text_stream,
open_file,
)
from .main import Typer, run # noqa
from .models import BinaryFileRead, BinaryFileWrite, Context, TextFile # noqa
from .params import Argument, Option # noqa
| """Typer, build great CLIs. Easy to code. Based on Python type hints."""
__version__ = "0.0.4"
from click.exceptions import ( # noqa
Abort,
BadArgumentUsage,
BadOptionUsage,
BadParameter,
ClickException,
FileError,
MissingParameter,
NoSuchOption,
UsageError,
)
from click.termui import ( # noqa
clear,
confirm,
echo_via_pager,
edit,
get_terminal_size,
getchar,
launch,
pause,
progressbar,
prompt,
secho,
style,
unstyle,
)
from click.utils import ( # noqa
echo,
format_filename,
get_app_dir,
get_binary_stream,
get_os_args,
get_text_stream,
open_file,
)
from .main import Typer, run # noqa
from .models import BinaryFileRead, BinaryFileWrite, Context, TextFile # noqa
from .params import Argument, Option # noqa
|
chromium: Move the login detection setup in a function | console.log("goa: GOA content script for GMail loading");
function detectLoginInfo(selector, services) {
console.log("goa: Scraping for login info");
var r = document.evaluate(selector, document.body, null, XPathResult.STRING_TYPE, null);
var loginName = r.stringValue;
if (!loginName)
return false;
var msg = {
type: 'login-detected',
data: {
identity: loginName,
provider: 'google',
services: services,
authenticationDomain: 'google.com'
}
};
console.log("goa: Detected login info:", msg);
chrome.extension.sendMessage(msg);
return true;
}
function setupGoaIntegration(selector, services)
{
// Run detectLoginInfo() on any DOM change if not ready yet
if (!detectLoginInfo()) {
var t = {};
t.observer = new WebKitMutationObserver(function(mutations, observer) {
if (detectLoginInfo(selector, services)) {
observer.disconnect();
clearTimeout(t.timeout);
}
});
t.observer.observe(document.body, { childList: true, subtree: true, characterData: true });
t.timeout = setTimeout(function() {
console.log("goa: Give up, unable to find any login info");
t.observer.disconnect();
}, 10000);
};
}
setupGoaIntegration (
'//*[@role="navigation"]//*[starts-with(@href, "https://profiles.google.com/")]//text()[contains(.,"@")]',
['mail']
);
| console.log("goa: GOA content script for GMail loading");
function detectLoginInfo() {
console.log("goa: Scraping for login info");
var selector = '//*[@role="navigation"]//*[starts-with(@href, "https://profiles.google.com/")]//text()[contains(.,"@")]';
var r = document.evaluate(selector, document.body, null, XPathResult.STRING_TYPE, null);
var loginName = r.stringValue;
if (!loginName)
return false;
var msg = {
type: 'login-detected',
data: {
identity: loginName,
provider: 'google',
services: ['mail'],
authenticationDomain: 'google.com'
}
};
console.log("goa: Detected login info:", msg);
chrome.extension.sendMessage(msg);
return true;
}
// Run detectLoginInfo() on any DOM change if not ready yet
if (!detectLoginInfo()) {
var t = {};
t.observer = new WebKitMutationObserver(function(mutations, observer) {
if (detectLoginInfo()) {
observer.disconnect();
clearTimeout(t.timeout);
}
});
t.observer.observe(document.body, { childList: true, subtree: true, characterData: true });
t.timeout = setTimeout(function() {
console.log("goa: Give up, unable to find any login info");
t.observer.disconnect();
}, 10000);
};
|
Comment tests better, a bit | var assert = require('assert');
describe('Landing page', function() {
it('should have the correct title', function(done, server, client) {
// Get the title with some Laika mumbo jumbo and a dash of jQuery:
var title = client.evalSync(function() {
var titleText = $('title').text();
// Laika test functions don't end with a return call. Instead, they use
// emit('return', anything);
// You can pass anything, object or whatever you want.
emit('return', titleText);
});
// Check if it's correct.
assert.equal(title, 'mds');
// All tests end with the 'done' callback.
done();
});
it('should display "Hello world!"', function(done, server, client) {
var paragraph = client.evalSync(function() {
emit('return', $('p').text());
});
assert.equal(paragraph, "Hello world!");
done();
});
}); | var assert = require('assert');
describe('Landing page', function() {
it('should have the correct title', function(done, server, client) {
// Get the title with some Laika mumbo jumbo and a dash of jQuery:
var title = client.evalSync(function() {
var titleText = $('title').text();
emit('return', titleText);
});
// Check if it's correct.
assert.equal(title, 'mds');
// All tests end with the 'done' callback.
done();
});
it('should display "Hello world!"', function(done, server, client) {
var paragraph = client.evalSync(function() {
emit('return', $('p').text());
});
assert.equal(paragraph, "Hello world!");
done();
});
}); |
Use IpUtils to check for local addresses | <?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;
use Symfony\Component\HttpFoundation\IpUtils;
// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);
$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
Debug::enable();
require_once __DIR__.'/../app/AppKernel.php';
$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$clientIps = $request->getClientIps();
$lastClientIp = $clientIps[count($clientIps) - 1];
if (!IpUtils::checkIp($lastClientIp, ['127.0.0.1', 'fe80::1', '::1', '193.108.249.215', '78.137.6.142', '10.0.0.0/8'])) {
header('HTTP/1.0 403 Forbidden');
exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
| <?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;
// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);
// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
|| isset($_SERVER['HTTP_X_FORWARDED_FOR'])
|| !(in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', 'fe80::1', '::1', '193.108.249.215')) || php_sapi_name() === 'cli-server'
|| strpos(@$_SERVER['REMOTE_ADDR'], '10.0.3.') === 0
|| strpos(@$_SERVER['REMOTE_ADDR'], '10.0.4.') === 0
)
) {
header('HTTP/1.0 403 Forbidden');
exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}
$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
Debug::enable();
require_once __DIR__.'/../app/AppKernel.php';
$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
|
Add user id field to snapshot migration | const TABLE_NAME = 'snapshots';
exports.up = function(knex) {
function table(t) {
t.increments().primary();
t.string('organizationId').unsigned().references('organizations.id');
t.string('userId').unsigned().references('users.id');
t.string('score');
t.json('profile').notNullable();
t.dateTime('createdAt').notNullable().defaultTo(knex.fn.now());
t.dateTime('updatedAt').notNullable().defaultTo(knex.fn.now());
}
return knex.schema
.createTable(TABLE_NAME, table)
.then(() => {
console.log(`${TABLE_NAME} table is created!`);
});
};
exports.down = function(knex) {
return knex.schema
.dropTable(TABLE_NAME)
.then(() => {
console.log(`${TABLE_NAME} table was dropped!`);
});
};
| const TABLE_NAME = 'snapshots';
exports.up = function(knex) {
function table(t) {
t.increments().primary();
t.string('organizationId').unsigned().references('organizations.id');
t.string('score');
t.json('profile').notNullable();
t.dateTime('createdAt').notNullable().defaultTo(knex.fn.now());
t.dateTime('updatedAt').notNullable().defaultTo(knex.fn.now());
}
return knex.schema
.createTable(TABLE_NAME, table)
.then(() => {
console.log(`${TABLE_NAME} table is created!`);
});
};
exports.down = function(knex) {
return knex.schema
.dropTable(TABLE_NAME)
.then(() => {
console.log(`${TABLE_NAME} table was dropped!`);
});
};
|
Create button event with method
Change variable name to be better described.
Optimize output flow by disable its editable.
Remove unnecessary color changer. | /**
* Part of Employ
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DashboardFrame extends CommonFrame implements ActionListener {
JButton buttonAddData = new JButton("Add");
JButton buttonDeleteData = new JButton("Delete");
JTextField textInputNumber = new JTextField(10);
JTextField textOutputNumber = new JTextField(10);
// define dashboard for special frame
public DashboardFrame() {
super("Dashboard");
buttonAddData.setActionCommand("addData");
buttonDeleteData.setActionCommand("deleteData");
buttonAddData.addActionListener(this);
buttonDeleteData.addActionListener(this);
textInputNumber.addActionListener(this);
textOutputNumber.setEditable(false);
add(buttonAddData);
add(buttonDeleteData);
add(textInputNumber);
add(textOutputNumber);
}
// get input number in text input
void getTextInput() {
String inputNumber = textInputNumber.getText();
textOutputNumber.setText(inputNumber);
}
// clear input number in text input
void clearInputNumber() {
textOutputNumber.setText("");
}
// define listener action when button is clicked
public void actionPerformed(ActionEvent event) {
if (event.getActionCommand().equals("addData"))
getTextInput();
else if (event.getActionCommand().equals("deleteData"))
clearInputNumber();
else
getContentPane().setBackground(Color.white);
repaint();
}
}
| /**
* Part of Employ
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DashboardFrame extends CommonFrame implements ActionListener {
JButton buttonAddData = new JButton("Add");
JButton buttonDeleteData = new JButton("Delete");
JTextField textNumber = new JTextField(10);
JTextField textOutput = new JTextField(10);
// define dashboard for special frame
public DashboardFrame() {
super("Dashboard");
buttonAddData.setActionCommand("addData");
buttonDeleteData.setActionCommand("deleteData");
buttonAddData.addActionListener(this);
buttonDeleteData.addActionListener(this);
textNumber.addActionListener(this);
add(buttonAddData);
add(buttonDeleteData);
add(textNumber);
add(textOutput);
}
// define listener action when button "Add" is clicked
public void actionPerformed(ActionEvent event) {
String inputNumber = textNumber.getText();
textOutput.setText(inputNumber);
if (event.getActionCommand().equals("addData"))
getContentPane().setBackground(Color.white);
else if (event.getActionCommand().equals("deleteData"))
getContentPane().setBackground(Color.darkGray);
else
getContentPane().setBackground(Color.black);
repaint();
}
}
|
Set selection when editing an entity from manuscript view. | import { Command } from 'substance'
/*
This command intended to switch view and scroll to the selected node.
Command state becoming active only for certain type of custom selection,
e.g. if you want to use it, provide config with selectionType property.
*/
export default class EditEntityCommand extends Command {
getCommandState (params, context) {
let sel = params.selection
let newState = {
disabled: true
}
if (sel.isCustomSelection()) {
if (sel.customType === this.config.selectionType) {
newState.disabled = false
newState.nodeId = sel.nodeId
}
}
return newState
}
execute (params, context) {
const appState = context.appState
const viewName = appState.get('viewName')
if (viewName !== 'metadata') {
const sel = params.selection
const nodeId = sel.nodeId
context.editor.send('updateViewName', 'metadata')
// HACK: using the ArticlePanel instance to get to the current editor
// so that we can dispatch 'executeCommand'
let editor = context.articlePanel.refs.content
editor.send('scrollTo', { nodeId })
// HACK: this is a mess because context.api is a different instance after
// switching to metadata view
// TODO: we should extend ArticleAPI to allow for this
editor.api.selectFirstRequiredPropertyOfMetadataCard(nodeId)
}
}
}
| import { Command } from 'substance'
/*
This command intended to switch view and scroll to the selected node.
Command state becoming active only for certain type of custom selection,
e.g. if you want to use it, provide config with selectionType property.
*/
export default class EditEntityCommand extends Command {
getCommandState (params, context) {
let sel = params.selection
let newState = {
disabled: true
}
if (sel.isCustomSelection()) {
if (sel.customType === this.config.selectionType) {
newState.disabled = false
newState.nodeId = sel.nodeId
}
}
return newState
}
execute (params, context) {
const appState = context.appState
const viewName = appState.get('viewName')
if (viewName !== 'metadata') {
const sel = params.selection
context.editor.send('updateViewName', 'metadata')
context.articlePanel.refs.content.send('scrollTo', { nodeId: sel.nodeId })
}
}
}
|
Change lincense, BSD to MIT | #!/usr/bin/env python
from setuptools import setup
long_description = open('README.rst').read()
setup(name="quik",
version="0.2.2-dev",
description="A fast and lightweight Python template engine",
long_description=long_description,
author="Thiago Avelino",
author_email="thiago@avelino.xxx",
url="https://github.com/avelino/quik",
license="MIT",
py_modules=['quik'],
zip_safe=False,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Text Processing :: Markup :: HTML'],
keywords="template, engine, web, fast, lightweight",
include_package_data=True,)
| #!/usr/bin/env python
from setuptools import setup
long_description = open('README.rst').read()
setup(name="quik",
version="0.2.2-dev",
description="A fast and lightweight Python template engine",
long_description=long_description,
author="Thiago Avelino",
author_email="thiago@avelino.xxx",
url="https://github.com/avelino/quik",
license="MIT",
py_modules=['quik'],
zip_safe=False,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Text Processing :: Markup :: HTML'],
keywords="template, engine, web, fast, lightweight",
include_package_data=True,)
|
Change PhoneGap version to 0.9.3. | /*
* PhoneGap is available under *either* the terms of the modified BSD license *or* the
* MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
*
* Copyright (c) 2005-2010, Nitobi Software Inc.
* Copyright (c) 2010, IBM Corporation
*/
package com.phonegap.device;
import net.rim.device.api.script.Scriptable;
import net.rim.device.api.system.DeviceInfo;
/**
* PhoneGap plugin that provides device information, including:
*
* - Device platform version (e.g. 2.13.0.95). Not to be confused with BlackBerry OS version.
* - Unique device identifier (UUID).
* - PhoneGap software version.
*/
public final class DeviceFeature extends Scriptable {
public static final String FIELD_PLATFORM = "platform";
public static final String FIELD_UUID = "uuid";
public static final String FIELD_PHONEGAP = "phonegap";
public Object getField(String name) throws Exception {
if (name.equals(FIELD_PLATFORM)) {
return new String(DeviceInfo.getPlatformVersion());
}
else if (name.equals(FIELD_UUID)) {
return new Integer(DeviceInfo.getDeviceId());
}
else if (name.equals(FIELD_PHONEGAP)) {
return "0.9.3";
}
return super.getField(name);
}
}
| /*
* PhoneGap is available under *either* the terms of the modified BSD license *or* the
* MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
*
* Copyright (c) 2005-2010, Nitobi Software Inc.
* Copyright (c) 2010, IBM Corporation
*/
package com.phonegap.device;
import net.rim.device.api.script.Scriptable;
import net.rim.device.api.system.DeviceInfo;
/**
* PhoneGap plugin that provides device information, including:
*
* - Device platform version (e.g. 2.13.0.95). Not to be confused with BlackBerry OS version.
* - Unique device identifier (UUID).
* - PhoneGap software version.
*/
public final class DeviceFeature extends Scriptable {
public static final String FIELD_PLATFORM = "platform";
public static final String FIELD_UUID = "uuid";
public static final String FIELD_PHONEGAP = "phonegap";
public Object getField(String name) throws Exception {
if (name.equals(FIELD_PLATFORM)) {
return new String(DeviceInfo.getPlatformVersion());
}
else if (name.equals(FIELD_UUID)) {
return new Integer(DeviceInfo.getDeviceId());
}
else if (name.equals(FIELD_PHONEGAP)) {
return "0.9.2";
}
return super.getField(name);
}
}
|
Fix null in admin account | /*
* The MIT License (MIT)
*
* Copyright (c) 2019 Vladimir
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.devproserv.courses.model;
/**
* Deals with admins.
*
* @since 0.5.0
*/
public final class NestAdmins implements Nest {
@Override
public Responsible makeUser() {
return new Admin(new User(-1, "no login", "no pass"));
}
}
| /*
* The MIT License (MIT)
*
* Copyright (c) 2019 Vladimir
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.devproserv.courses.model;
/**
* Deals with admins.
*
* @since 0.5.0
*/
public final class NestAdmins implements Nest {
@Override
public Responsible makeUser() {
return null;
}
}
|
Move RasterIO and Shapely to optional dependencies | import os.path
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
# read README as the long description
readme = 'README' if os.path.exists('README') else 'README.md'
with open(readme, 'r') as f:
long_description = f.read()
setup(
name='spandex',
version='0.1dev',
description='Spatial Analysis and Data Exploration',
long_description=long_description,
author='Synthicity',
author_email='ejanowicz@synthicity.com',
license='BSD',
url='https://github.com/synthicity/spandex',
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python :: 2.7',
'License :: OSI Approved :: BSD License'
],
packages=find_packages(exclude=['*.tests']),
install_requires=[
'gdal>=1.10.1',
'numpy>=1.8.0',
'pandas>=0.13.1',
'psycopg2>=2.5.4',
],
extras_require={
'RasterIO': ['rasterio>=0.12', 'rasterstats>=0.4'],
'Shapely': ['shapely>=1.3.2']
}
)
| import os.path
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
# read README as the long description
readme = 'README' if os.path.exists('README') else 'README.md'
with open(readme, 'r') as f:
long_description = f.read()
setup(
name='spandex',
version='0.1dev',
description='Spatial Analysis and Data Exploration',
long_description=long_description,
author='Synthicity',
author_email='ejanowicz@synthicity.com',
license='BSD',
url='https://github.com/synthicity/spandex',
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python :: 2.7',
'License :: OSI Approved :: BSD License'
],
packages=find_packages(exclude=['*.tests']),
install_requires=[
'gdal>=1.10.1',
'numpy>=1.8.0',
'pandas>=0.13.1',
'psycopg2>=2.5.4',
'rasterio>=0.12',
'rasterstats>=0.4',
'shapely>=1.3.2'
]
)
|
Replace group with static username | """
Permissions classes for User accounts API views.
"""
from __future__ import unicode_literals
from django.conf import settings
from rest_framework import permissions
USERNAME_REPLACEMENT_GROUP = "username_replacement_admin"
class CanDeactivateUser(permissions.BasePermission):
"""
Grants access to AccountDeactivationView if the requesting user is a superuser
or has the explicit permission to deactivate a User account.
"""
def has_permission(self, request, view):
return request.user.has_perm('student.can_deactivate_users')
class CanRetireUser(permissions.BasePermission):
"""
Grants access to the various retirement API endpoints if the requesting user is
a superuser, the RETIREMENT_SERVICE_USERNAME, or has the explicit permission to
retire a User account.
"""
def has_permission(self, request, view):
return request.user.has_perm('accounts.can_retire_user')
class CanReplaceUsername(permissions.BasePermission):
"""
Grants access to the Username Replacement API for anyone in the group,
including the service user.
"""
def has_permission(self, request, view):
return request.user.username == getattr(settings, "USERNAME_REPLACEMENT_WORKER")
| """
Permissions classes for User accounts API views.
"""
from __future__ import unicode_literals
from rest_framework import permissions
USERNAME_REPLACEMENT_GROUP = "username_replacement_admin"
class CanDeactivateUser(permissions.BasePermission):
"""
Grants access to AccountDeactivationView if the requesting user is a superuser
or has the explicit permission to deactivate a User account.
"""
def has_permission(self, request, view):
return request.user.has_perm('student.can_deactivate_users')
class CanRetireUser(permissions.BasePermission):
"""
Grants access to the various retirement API endpoints if the requesting user is
a superuser, the RETIREMENT_SERVICE_USERNAME, or has the explicit permission to
retire a User account.
"""
def has_permission(self, request, view):
return request.user.has_perm('accounts.can_retire_user')
class CanReplaceUsername(permissions.BasePermission):
"""
Grants access to the Username Replacement API for anyone in the group,
including the service user.
"""
def has_permission(self, request, view):
return request.user.groups.filter(name=USERNAME_REPLACEMENT_GROUP).exists()
|
Fix code after a bad rebase/merge | Artist = (function(){
// Artist constructor. Given an object describing an artist, copy
// all of its local properties into `this'.
var Artist = function(record) {
};
Artist.prototype = {
// Create a new record if the `id' property is `undefined',
// otherwise update an existing record. Return a promise from the
// Ajax library.
save: function() {
},
// Optional: Write a `destroy' method that deletes the artist.
// Return a promise.
destroy: function() {
},
};
// Should fetch a single artist via Ajax. Return a promise that
// resolves to an instance of the Artist function.
var fetchOne = function(id) {
};
// Should fetch all artists via Ajax. Return a promise that
// resolves to an array of Artist objects.
var fetchAll = function() {
};
// Public interface:
return {
fetchOne: fetchOne,
fetchAll: fetchAll,
create: function(record) {
return new Artist(record);
},
};
})();
| Artist = (function(){
// Artist constructor. Given an object describing an artist, copy
// all of its local properties into `this'.
var Artist = function(record) {
};
Artist.prototype = {
// Create a new record if the `id' property is `undefined',
// otherwise update an existing record. Return a promise from the
// Ajax library.
save: function() {
},
// Optional: Write a `destroy' method that deletes the artist.
// Return a promise.
destroy: function() {
},
};
// Should fetch a single artist via Ajax. Return a promise that
// resolves to an instance of the Artist function.
var fetchOne = function(id) {
};
// Should fetch all artists via Ajax. Return a promise that
// resolves to an array of Artist objects.
};
// Public interface:
return {
fetchOne: fetchOne,
fetchAll: fetchAll,
create: function(record) {
return new Artist(record);
},
};
})();
|
Add extension type from RFC 5246 | package org.bouncycastle.crypto.tls;
public class ExtensionType
{
/*
* RFC 6066 1.1.
*/
public static final int server_name = 0;
public static final int max_fragment_length = 1;
public static final int client_certificate_url = 2;
public static final int trusted_ca_keys = 3;
public static final int truncated_hmac = 4;
public static final int status_request = 5;
/*
* RFC 4492 5.1.
*/
public static final int elliptic_curves = 10;
public static final int ec_point_formats = 11;
/*
* RFC 5054 2.8.1.
*/
public static final int srp = 12;
/*
* RFC 5246 7.4.1.4.
*/
public static final int signature_algorithms = 13;
/*
* RFC 5746 3.2.
*/
public static final int renegotiation_info = 0xff01;
}
| package org.bouncycastle.crypto.tls;
/**
* RFC 4366 2.3
*/
public class ExtensionType
{
public static final int server_name = 0;
public static final int max_fragment_length = 1;
public static final int client_certificate_url = 2;
public static final int trusted_ca_keys = 3;
public static final int truncated_hmac = 4;
public static final int status_request = 5;
/*
* RFC 4492
*/
public static final int elliptic_curves = 10;
public static final int ec_point_formats = 11;
/*
* RFC 5054 2.8.1
*/
public static final int srp = 12;
/*
* RFC 5746 6
*/
public static final int renegotiation_info = 0xff01;
}
|
Add typing information to Meta. | import collections
import typing
class Meta(collections.OrderedDict, typing.MutableMapping[str, float]):
def __init__(self, *args, **kwargs) -> None:
self._smallest = float('inf')
self._largest = 0
self._ordered = True
super(Meta, self).__init__(*args, **kwargs)
def __setitem__(self, key: str, value: float) -> None:
if key in self and self[key] == value:
raise AssertionError('Redundant assignment')
if value > self._smallest:
self._ordered = False
else:
self._smallest = value
if value > self._largest:
self._largest = value
super(Meta, self).__setitem__(key, value)
self._changed()
def items(self) -> typing.ItemsView[str, float]:
self._reorder()
return super(Meta, self).items()
def first(self) -> typing.Tuple[str, float]:
self._reorder()
for k, v in self.items():
return k, v
def peek(self) -> str:
self._reorder()
for first in self:
return first
def magnitude(self) -> float:
return self._largest
def _reorder(self) -> None:
if self._ordered:
return
order = sorted(super(Meta, self).items(), key=lambda x: x[1], reverse=True)
for k, v in order:
self.move_to_end(k)
self._ordered = True
def _changed(self):
pass
| import collections
class Meta(collections.OrderedDict):
def __init__(self, *args, **kwargs):
self._smallest = float('inf')
self._largest = 0
self._ordered = True
super(Meta, self).__init__(*args, **kwargs)
def __setitem__(self, key, value, *args, **kwargs):
if key in self and self[key] == value:
raise AssertionError('Redundant assignment')
if value > self._smallest:
self._ordered = False
else:
self._smallest = value
if value > self._largest:
self._largest = value
super(Meta, self).__setitem__(key, value, *args, **kwargs)
self._changed()
def items(self):
self._reorder()
return super(Meta, self).items()
def first(self):
self._reorder()
for k, v in self.items():
return k, v
def peek(self):
self._reorder()
for first in self:
return first
def magnitude(self):
return self._largest
def _reorder(self):
if self._ordered:
return
order = sorted(super(Meta, self).items(), key=lambda x: x[1], reverse=True)
for k, v in order:
self.move_to_end(k)
self._ordered = True
def _changed(self):
pass
|
palette[picker]: Use mouse wheel to control HSL lightness. | (function( window, document, undefined ) {
'use strict';
function clamp( value, min, max ) {
return Math.min( Math.max( value, min ), max );
}
var hslEl = document.createElement( 'div' );
hslEl.classList.add( 'hsl' );
document.body.appendChild( hslEl );
var h = 0,
s = 50,
l = 50;
function update() {
var hsl = 'hsl(' +
Math.round( h ) + ', ' +
Math.round( s ) + '%, ' +
Math.round( l ) + '%)';
document.body.style.backgroundColor = hsl;
hslEl.textContent = hsl;
}
window.addEventListener( 'mousemove', function( event ) {
var x = event.pageX,
y = event.pageY;
h = x / window.innerWidth * 360;
s = ( window.innerHeight - y ) / window.innerHeight * 100;
update();
});
window.addEventListener( 'wheel', function( event ) {
event.preventDefault();
l = clamp( l - event.deltaY, 0, 100 );
update();
});
update();
}) ( window, document );
| (function( window, document, undefined ) {
'use strict';
var hslEl = document.createElement( 'div' );
hslEl.classList.add( 'hsl' );
document.body.appendChild( hslEl );
window.addEventListener( 'mousemove', function( event ) {
var x = event.pageX,
y = event.pageY;
var h = x / window.innerWidth * 360,
s = ( window.innerHeight - y ) / window.innerHeight * 100,
l = 50;
var hsl = 'hsl(' +
Math.round( h ) + ', ' +
Math.round( s ) + '%, ' +
Math.round( l ) + '%)';
document.body.style.backgroundColor = hsl;
hslEl.textContent = hsl;
});
}) ( window, document );
|
Update prompt config for pysh profile. | c = get_config()
app = c.InteractiveShellApp
# This can be used at any point in a config file to load a sub config
# and merge it into the current one.
load_subconfig('ipython_config.py', profile='default')
c.PromptManager.in_template = r'{color.LightGreen}\u@\h{color.LightBlue}[{color.LightCyan}\Y1{color.LightBlue}]{color.Green}|\#> '
c.PromptManager.in2_template = r'{color.Green}|{color.LightGreen}\D{color.Green}> '
c.PromptManager.out_template = r'<\#> '
c.PromptManager.justify = True
c.InteractiveShell.separate_in = ''
c.InteractiveShell.separate_out = ''
c.InteractiveShell.separate_out2 = ''
c.PrefilterManager.multi_line_specials = True
lines = """
%rehashx
"""
# You have to make sure that attributes that are containers already
# exist before using them. Simple assigning a new list will override
# all previous values.
if hasattr(app, 'exec_lines'):
app.exec_lines.append(lines)
else:
app.exec_lines = [lines]
| c = get_config()
app = c.InteractiveShellApp
# This can be used at any point in a config file to load a sub config
# and merge it into the current one.
load_subconfig('ipython_config.py', profile='default')
c.InteractiveShell.prompt_in1 = r'\C_LightGreen\u@\h\C_LightBlue[\C_LightCyan\Y1\C_LightBlue]\C_Green|\#> '
c.InteractiveShell.prompt_in2 = r'\C_Green|\C_LightGreen\D\C_Green> '
c.InteractiveShell.prompt_out = r'<\#> '
c.InteractiveShell.prompts_pad_left = True
c.InteractiveShell.separate_in = ''
c.InteractiveShell.separate_out = ''
c.InteractiveShell.separate_out2 = ''
c.PrefilterManager.multi_line_specials = True
lines = """
%rehashx
"""
# You have to make sure that attributes that are containers already
# exist before using them. Simple assigning a new list will override
# all previous values.
if hasattr(app, 'exec_lines'):
app.exec_lines.append(lines)
else:
app.exec_lines = [lines]
|
Add version to API URL | """fantasyStocks URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from stocks import stockUrls, views
from stocksApi import urls as apiUrls
from django.views.generic import RedirectView
from django.core.urlresolvers import reverse_lazy
urlpatterns = static(settings.STATIC_URL) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + [
url(r'^admin/', include(admin.site.urls), name="admin"),
url(r"^stocks/", include(stockUrls), name="stocks"),
url(r"^api/v1/", include(apiUrls), name="api"),
url(r"^$", RedirectView.as_view(url="stocks/", permanent=True), name="redirect")
]
| """fantasyStocks URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from stocks import stockUrls, views
from stocksApi import urls as apiUrls
from django.views.generic import RedirectView
from django.core.urlresolvers import reverse_lazy
urlpatterns = static(settings.STATIC_URL) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + [
url(r'^admin/', include(admin.site.urls), name="admin"),
url(r"^stocks/", include(stockUrls), name="stocks"),
url(r"^api/1/", include(apiUrls), name="api"),
url(r"^$", RedirectView.as_view(url="stocks/", permanent=True), name="redirect")
]
|
Reset to the original content when ESCAPE key is down. | $(function() {
$("td").dblclick(function() {
var td = $(this), originalContent = td.text();
td.addClass("cellEditing");
td.data("originalContent", originalContent);
var el = document.createElement("input"), $el = $(el);
$el.attr({type: "text", value: originalContent});
td.empty();
td.append(el);
$el.focus();
$el.keypress(function(e) {
if (e.which == 13) {
var text = $(this), newContent = text.val(), td = text.parent();
td.text(newContent);
td.removeData("originalContent");
td.removeClass("cellEditing");
}
});
var resetContent = function(e) {
var td = $(e.target).parent();
td.text(td.data("originalContent"));
td.removeData("originalContent");
td.removeClass("cellEditing");
};
$el.keydown(function(e) {
if (e.which == 27) {
resetContent(e);
}
});
$el.blur(resetContent);
});
});
| $(function() {
$("td").dblclick(function() {
var td = $(this), originalContent = td.text();
td.addClass("cellEditing");
td.data("originalContent", originalContent);
var el = document.createElement("input"), $el = $(el);
$el.attr({type: "text", value: originalContent});
td.empty();
td.append(el);
$el.focus();
$el.keypress(function(e) {
if (e.which == 13) {
var text = $(this), newContent = text.val(), td = text.parent();
td.text(newContent);
td.removeData("originalContent");
td.removeClass("cellEditing");
}
});
$el.blur(function() {
var td = $(this).parent();
td.text(td.data("originalContent"));
td.removeData("originalContent");
td.removeClass("cellEditing");
});
});
});
|
Update BO for video integration | <?php
namespace Bodu\VideoBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class VideoType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', 'text', array('required' => false))
->add('description', 'textarea', array('required' => false))
->add('videoIntegration', 'textarea', array('required' => false))
->add('published', 'checkbox', array('required' => false))
->add('rank', 'hidden')
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Bodu\VideoBundle\Entity\Video'
));
}
/**
* @return string
*/
public function getName()
{
return 'bodu_videobundle_video';
}
}
| <?php
namespace Bodu\VideoBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class VideoType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', 'text', array('required' => false))
->add('description', 'textarea', array('required' => false))
->add('videoIntegration', 'text', array('required' => false))
->add('published', 'checkbox', array('required' => false))
->add('rank', 'hidden')
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Bodu\VideoBundle\Entity\Video'
));
}
/**
* @return string
*/
public function getName()
{
return 'bodu_videobundle_video';
}
}
|
Add null check for containerRef | import GeminiScrollbar from 'react-gemini-scrollbar';
let scrollbarWidth = null;
const ScrollbarUtil = {
/**
* Taken from Gemini's source code with some edits
* https://github.com/noeldelgado/gemini-scrollbar/blob/master/index.js#L22
* @param {Object} options
* @return {Number} The width of the native scrollbar
*/
getScrollbarWidth(options = {}) {
if (scrollbarWidth == null || options.forceUpdate) {
let element = global.document.createElement('div');
element.style.position = 'absolute';
element.style.top = '-9999px';
element.style.width = '100px';
element.style.height = '100px';
element.style.overflow = 'scroll';
element.style.msOverflowStyle = 'scrollbar';
global.document.body.appendChild(element);
scrollbarWidth = (element.offsetWidth - element.clientWidth);
global.document.body.removeChild(element);
}
return scrollbarWidth;
},
updateWithRef(containerRef) {
// Use the containers gemini ref if present
if (containerRef != null && containerRef.geminiRef != null) {
this.updateWithRef(containerRef.geminiRef);
return;
}
if (containerRef instanceof GeminiScrollbar) {
containerRef.scrollbar.update();
}
}
};
module.exports = ScrollbarUtil;
| import GeminiScrollbar from 'react-gemini-scrollbar';
let scrollbarWidth = null;
const ScrollbarUtil = {
/**
* Taken from Gemini's source code with some edits
* https://github.com/noeldelgado/gemini-scrollbar/blob/master/index.js#L22
* @param {Object} options
* @return {Number} The width of the native scrollbar
*/
getScrollbarWidth(options = {}) {
if (scrollbarWidth == null || options.forceUpdate) {
let element = global.document.createElement('div');
element.style.position = 'absolute';
element.style.top = '-9999px';
element.style.width = '100px';
element.style.height = '100px';
element.style.overflow = 'scroll';
element.style.msOverflowStyle = 'scrollbar';
global.document.body.appendChild(element);
scrollbarWidth = (element.offsetWidth - element.clientWidth);
global.document.body.removeChild(element);
}
return scrollbarWidth;
},
updateWithRef(containerRef) {
// Use the containers gemini ref if present
if (containerRef.geminiRef != null) {
this.updateWithRef(containerRef.geminiRef);
return;
}
if (containerRef instanceof GeminiScrollbar) {
containerRef.scrollbar.update();
}
}
};
module.exports = ScrollbarUtil;
|
Fix detection of Zookeeper in monasca-setup
The Zookeeper detection plugin was looking for zookeeper in the process
command-line. This was producing false positives in the detection
process because storm uses the zookeeper library and it shows up
the command-line for storm.
Change-Id: I764a3064003beec55f0e589272855dadfa0997e7 | import logging
import os
import yaml
import monsetup.agent_config
import monsetup.detection
log = logging.getLogger(__name__)
class Zookeeper(monsetup.detection.Plugin):
"""Detect Zookeeper daemons and setup configuration to monitor them.
"""
def _detect(self):
"""Run detection, set self.available True if the service is detected.
"""
if monsetup.detection.find_process_cmdline('org.apache.zookeeper') is not None:
self.available = True
def build_config(self):
"""Build the config as a Plugins object and return.
"""
config = monsetup.agent_config.Plugins()
# First watch the process
log.info("\tWatching the zookeeper process.")
config.merge(monsetup.detection.watch_process(['zookeeper']))
log.info("\tEnabling the zookeeper plugin")
with open(os.path.join(self.template_dir, 'conf.d/zk.yaml.example'), 'r') as zk_template:
zk_config = yaml.load(zk_template.read())
config['zk'] = zk_config
return config
def dependencies_installed(self):
# The current plugin just does a simple socket connection to zookeeper and
# parses the stat command
return True
| import logging
import os
import yaml
import monsetup.agent_config
import monsetup.detection
log = logging.getLogger(__name__)
class Zookeeper(monsetup.detection.Plugin):
"""Detect Zookeeper daemons and setup configuration to monitor them.
"""
def _detect(self):
"""Run detection, set self.available True if the service is detected.
"""
if monsetup.detection.find_process_cmdline('zookeeper') is not None:
self.available = True
def build_config(self):
"""Build the config as a Plugins object and return.
"""
config = monsetup.agent_config.Plugins()
# First watch the process
log.info("\tWatching the zookeeper process.")
config.merge(monsetup.detection.watch_process(['zookeeper']))
log.info("\tEnabling the zookeeper plugin")
with open(os.path.join(self.template_dir, 'conf.d/zk.yaml.example'), 'r') as zk_template:
zk_config = yaml.load(zk_template.read())
config['zk'] = zk_config
return config
def dependencies_installed(self):
# The current plugin just does a simple socket connection to zookeeper and
# parses the stat command
return True
|
Use Immutable-style .get instead of JS style property access on Team list page.
Fixes #35. | import React from 'react';
import Router from 'react-router';
import ControllerComponent from '../utils/ControllerComponent';
import * as edwinAPI from '../utils/edwinAPI';
import TeamStore from '../stores/TeamStore';
const {Link} = Router;
/**
* Shows a list of teams.
* @class
*/
export default class TeamList extends ControllerComponent {
get stores() {
return [TeamStore];
}
getNewState() {
return {
teams: TeamStore.getAll(),
};
}
/**
* On mounting, fetch data from APIs.
*/
componentDidMount() {
super.componentDidMount();
edwinAPI.getTeams();
}
render() {
return (
<div className="Welcome">
<h1>Teams</h1>
<ul>
{this.state.teams.map((team) => (
<li key={`team-${team.get('slug')}`}>
<Link to="timeline" params={{team: team.get('slug')}}>
{team.get('name')}
</Link>
</li>
))}
</ul>
</div>
);
}
}
| import React from 'react';
import Router from 'react-router';
import ControllerComponent from '../utils/ControllerComponent';
import * as edwinAPI from '../utils/edwinAPI';
import TeamStore from '../stores/TeamStore';
const {Link} = Router;
/**
* Shows a list of teams.
* @class
*/
export default class TeamList extends ControllerComponent {
get stores() {
return [TeamStore];
}
getNewState() {
return {
teams: TeamStore.getAll(),
};
}
/**
* On mounting, fetch data from APIs.
*/
componentDidMount() {
super.componentDidMount();
edwinAPI.getTeams();
}
render() {
return (
<div className="Welcome">
<h1>Teams</h1>
<ul>
{this.state.teams.map((team) => (
<li key={`team-${team.slug}`}>
<Link to="timeline" params={{team: team.get('slug')}}>
{team.get('name')}
</Link>
</li>
))}
</ul>
</div>
);
}
}
|
Change migration so newly added field is nullable | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-12-20 13:11
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('partner', '0042_auto_20171220_1305'),
]
operations = [
migrations.RemoveField(
model_name='partnerauditassessment',
name='link_report',
),
migrations.RemoveField(
model_name='partnerauditassessment',
name='most_recent_audit_report',
),
migrations.RemoveField(
model_name='partnerauditassessment',
name='org_audits',
),
migrations.AddField(
model_name='partnerauditreport',
name='created_by',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='audit_reports', to='account.User'),
),
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-12-20 13:11
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('partner', '0042_auto_20171220_1305'),
]
operations = [
migrations.RemoveField(
model_name='partnerauditassessment',
name='link_report',
),
migrations.RemoveField(
model_name='partnerauditassessment',
name='most_recent_audit_report',
),
migrations.RemoveField(
model_name='partnerauditassessment',
name='org_audits',
),
migrations.AddField(
model_name='partnerauditreport',
name='created_by',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='audit_reports', to='account.User'),
),
]
|
Update to use s3 package namespace | // Sparta package to support AWS S3
package s3
// EventOwnerIdentity event data
type EventOwnerIdentity struct {
PrincpalID string `json:"principalId"`
}
// Bucket event data
type Bucket struct {
Name string `json:"name"`
Arn string `json:"arn"`
OwnerIdentity EventOwnerIdentity `json:"ownerIdentity"`
}
// Object event data
type Object struct {
Key string `json:"key"`
Sequencer string `json:"sequencer"`
}
// Event event data
type S3 struct {
SchemaVersion string `json:"s3SchemaVersion"`
ConfigurationID string `json:"configurationId"`
Bucket Bucket `json:"bucket"`
Object Object `json:"object"`
}
// EventRecord event data
type EventRecord struct {
Region string `json:"awsRegion"`
EventName string `json:"eventName"`
EventTime string `json:"eventTime"`
EventSource string `json:"eventSource"`
EventVersion string `json:"eventVersion"`
S3 S3 `json:"s3"`
}
// Event event data
type Event struct {
Records []EventRecord
}
| package spartaS3
// EventOwnerIdentity event data
type EventOwnerIdentity struct {
PrincpalID string `json:"principalId"`
}
// Bucket event data
type Bucket struct {
Name string `json:"name"`
Arn string `json:"arn"`
OwnerIdentity EventOwnerIdentity `json:"ownerIdentity"`
}
// Object event data
type Object struct {
Key string `json:"key"`
Sequencer string `json:"sequencer"`
}
// Event event data
type S3 struct {
SchemaVersion string `json:"s3SchemaVersion"`
ConfigurationID string `json:"configurationId"`
Bucket Bucket `json:"bucket"`
Object Object `json:"object"`
}
// EventRecord event data
type EventRecord struct {
Region string `json:"awsRegion"`
EventName string `json:"eventName"`
EventTime string `json:"eventTime"`
EventSource string `json:"eventSource"`
EventVersion string `json:"eventVersion"`
S3 S3 `json:"s3"`
}
// Event event data
type Event struct {
Records []EventRecord
}
|
Add listening to the std out as well. | package main
import (
"bufio"
"fmt"
"log"
"os"
"os/exec"
)
func executeCmd(command string, args ...string) {
cmd := exec.Command(command, args...)
stdOut, err := cmd.StdoutPipe()
if err != nil {
log.Fatal(os.Stderr, "Error creating StdoutPipe for Cmd", err)
}
defer stdOut.Close()
scanner := bufio.NewScanner(stdOut)
go func() {
for scanner.Scan() {
fmt.Printf("%s\n", scanner.Text())
}
}()
stdErr, err := cmd.StderrPipe()
if err != nil {
log.Fatal(os.Stderr, "Error creating StderrPipe for Cmd", err)
}
defer stdErr.Close()
stdErrScanner := bufio.NewScanner(stdErr)
go func() {
for stdErrScanner.Scan() {
fmt.Printf("%s\n", stdErrScanner.Text())
}
}()
err = cmd.Start()
if err != nil {
log.Fatal(os.Stderr, "Error starting Cmd", err)
}
err = cmd.Wait()
// go generate command will fail when no generate command find.
if err != nil {
if err.Error() != "exit status 1" {
fmt.Println(err)
log.Fatal(err)
}
}
}
| package main
import (
"bufio"
"fmt"
"log"
"os"
"os/exec"
)
func executeCmd(command string, args ...string) {
cmd := exec.Command(command, args...)
cmdReader, err := cmd.StdoutPipe()
if err != nil {
log.Fatal(os.Stderr, "Error creating StdoutPipe for Cmd", err)
}
defer cmdReader.Close()
scanner := bufio.NewScanner(cmdReader)
go func() {
for scanner.Scan() {
fmt.Printf("%s\n", scanner.Text())
}
}()
err = cmd.Start()
if err != nil {
log.Fatal(os.Stderr, "Error starting Cmd", err)
}
err = cmd.Wait()
// go generate command will fail when no generate command find.
if err != nil {
if err.Error() != "exit status 1" {
fmt.Println(err)
log.Fatal(err)
}
}
}
|
Correct file name check for multimedia validator | <?php
class MultimediaFileValidatorSchema extends sfValidatorSchema
{
protected function configure($options = array(), $messages = array())
{
$this->addMessage('invalid_file_type', 'this type of extention is not allowed here');
$this->addMessage('file_not_found', "Please don't try stupid things, don't touch the uri");
}
protected function doClean($value)
{
$errorSchema = new sfValidatorErrorSchema($this);
$errorSchemaLocal = new sfValidatorErrorSchema($this);
if (!$value['referenced_relation'])
{
return array();
}
if($value['record_id'] == 0)
{
if( ! preg_match("/^[a-zA-Z0-9\.]+$/", $value['uri'])) {
$errorSchemaLocal->addError(new sfValidatorError($this, 'file_not_found'));
}
if(! file_exists(sfConfig::get('sf_upload_dir').'/multimedia/temp/'.$value['uri'])) {
$errorSchemaLocal->addError(new sfValidatorError($this, 'file_not_found'));
}
}
return $value;
}
}
| <?php
class MultimediaFileValidatorSchema extends sfValidatorSchema
{
protected function configure($options = array(), $messages = array())
{
$this->addMessage('invalid_file_type', 'this type of extention is not allowed here');
$this->addMessage('file_not_found', "Please don't try stupid things, don't touch the uri");
}
protected function doClean($value)
{
$errorSchema = new sfValidatorErrorSchema($this);
$errorSchemaLocal = new sfValidatorErrorSchema($this);
if (!$value['referenced_relation'])
{
return array();
}
if($value['record_id'] == 0)
{
//TODO replace the line below with a nice preg_replace function (instead of str_replace)
if(!file_exists(sfConfig::get('sf_upload_dir').'/multimedia/temp/'.str_replace("/","",$value['uri'])))
{
$errorSchemaLocal->addError(new sfValidatorError($this, 'file_not_found'));
}
}
return $value;
}
}
|
Transpose and Transpose180 for all Pillow versions | # coding: utf-8
from __future__ import print_function, unicode_literals, absolute_import
from PIL import Image
from .base import rpartial
from .pillow import PillowTestCase
class RotateRightCase(PillowTestCase):
def handle_args(self, name, transposition):
self.name = name
self.transposition = transposition
def runner(self, im):
for trans in self.transposition:
im = im.transpose(trans)
def readable_args(self):
return [self.name]
cases = [
rpartial(RotateRightCase, 'Flop', [Image.FLIP_LEFT_RIGHT]),
rpartial(RotateRightCase, 'Flip', [Image.FLIP_TOP_BOTTOM]),
rpartial(RotateRightCase, 'Rotate 90', [Image.ROTATE_90]),
rpartial(RotateRightCase, 'Rotate 180', [Image.ROTATE_180]),
rpartial(RotateRightCase, 'Rotate 270', [Image.ROTATE_270]),
rpartial(RotateRightCase, 'Transpose',
[Image.TRANSPOSE]
if hasattr(Image, 'TRANSPOSE')
else [Image.ROTATE_90, Image.FLIP_LEFT_RIGHT]),
rpartial(RotateRightCase, 'Transpose180',
[Image.TRANSPOSE_ROTATE_180]
if hasattr(Image, 'TRANSPOSE_ROTATE_180')
else [Image.ROTATE_270, Image.FLIP_LEFT_RIGHT]),
]
| # coding: utf-8
from __future__ import print_function, unicode_literals, absolute_import
from PIL import Image
from .base import rpartial
from .pillow import PillowTestCase
class RotateRightCase(PillowTestCase):
def handle_args(self, name, transposition):
self.name = name
self.transposition = transposition
def runner(self, im):
im.transpose(self.transposition)
def readable_args(self):
return [self.name]
cases = [
rpartial(RotateRightCase, 'Flop', Image.FLIP_LEFT_RIGHT),
rpartial(RotateRightCase, 'Flip', Image.FLIP_TOP_BOTTOM),
rpartial(RotateRightCase, 'Rotate 90', Image.ROTATE_90),
rpartial(RotateRightCase, 'Rotate 180', Image.ROTATE_180),
rpartial(RotateRightCase, 'Rotate 270', Image.ROTATE_270),
]
if hasattr(Image, 'TRANSPOSE'):
cases.append(rpartial(RotateRightCase, 'Transpose', Image.TRANSPOSE))
|
Enable cache for swagger ui web jar so that it's faster to load in test/uat envs | package org.openlmis.stockmanagement;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.CacheControl;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.util.concurrent.TimeUnit;
@Configuration
public class CustomWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {
@Value("${service.url}")
private String serviceUrl;
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/stockmanagement/docs")
.setViewName("redirect:" + serviceUrl + "/stockmanagement/docs/");
registry.addViewController("/stockmanagement/docs/")
.setViewName("forward:/stockmanagement/docs/index.html");
super.addViewControllers(registry);
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/stockmanagement/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/")
.setCacheControl(CacheControl.maxAge(7, TimeUnit.DAYS));
super.addResourceHandlers(registry);
}
}
| package org.openlmis.stockmanagement;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class CustomWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {
@Value("${service.url}")
private String serviceUrl;
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/stockmanagement/docs")
.setViewName("redirect:" + serviceUrl + "/stockmanagement/docs/");
registry.addViewController("/stockmanagement/docs/")
.setViewName("forward:/stockmanagement/docs/index.html");
super.addViewControllers(registry);
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/stockmanagement/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
super.addResourceHandlers(registry);
}
}
|
Replace extract func w/ anon func | package letter
// FreqMap records the frequency of each rune in a given text.
type FreqMap map[rune]int
// Frequency counts the frequency of each rune in a given text and returns this
// data as a FreqMap.
func Frequency(s string) FreqMap {
m := FreqMap{}
for _, r := range s {
m[r]++
}
return m
}
// ConcurrentFrequency counts the frequency of each rune in texts (concurrently)
// and returns a FreqMap.
func ConcurrentFrequency(texts []string) FreqMap {
freqMaps := make(chan FreqMap, len(texts))
for _, text := range texts {
go func(t string, c chan<- FreqMap) {
c <- Frequency(t)
}(text, freqMaps)
}
result := make(FreqMap)
// Merge freqMaps into result
for range texts {
freqMap := <-freqMaps
for r, frequency := range freqMap {
result[r] += frequency
}
}
return result
}
| package letter
// FreqMap records the frequency of each rune in a given text.
type FreqMap map[rune]int
// Frequency counts the frequency of each rune in a given text and returns this
// data as a FreqMap.
func Frequency(s string) FreqMap {
m := FreqMap{}
for _, r := range s {
m[r]++
}
return m
}
// ConcurrentFrequency counts the frequency of each rune in texts (concurrently)
// and returns a FreqMap.
func ConcurrentFrequency(texts []string) FreqMap {
freqMaps := make(chan FreqMap, len(texts))
for _, text := range texts {
go writeFrequencyToChan(text, freqMaps)
}
result := make(FreqMap)
// Merge freqMaps into result
for range texts {
freqMap := <-freqMaps
for r, frequency := range freqMap {
result[r] += frequency
}
}
return result
}
func writeFrequencyToChan(s string, c chan<- FreqMap) {
c <- Frequency(s)
}
|
[minor] Use stop instead of close, it fixes, things. | 'use strict';
/**
* Minimum viable Browserchannel server for Node.js that works through the primus
* interface.
*
* @runat server
* @api private
*/
module.exports = function server() {
var browserchannel = require('browserchannel')
, Spark = this.Spark
, primus = this.primus
, query = {};
//
// We've received a new connection, create a new Spark. The Spark will
// automatically announce it self as a new connection once it's created (after
// the next tick).
//
this.service = browserchannel.server({
base: primus.pathname
}, function connection(socket) {
var spark = new Spark(
socket.headers // HTTP request headers.
, socket.address // IP address.
, query // Query string, not allowed by browser channel.
, socket.id // Unique connection id.
);
spark.on('outgoing::end', function end() {
socket.stop();
}).on('outgoing::data', function write(data) {
socket.send(data);
});
socket.on('close', spark.emits('end'));
socket.on('message', spark.emits('data'));
});
//
// Listen to upgrade requests.
//
this.on('request', function request(req, res, next) {
//
// The browser.channel returns a middleware layer.
//
this.service(req, res, next);
});
};
| 'use strict';
/**
* Minimum viable Browserchannel server for Node.js that works through the primus
* interface.
*
* @runat server
* @api private
*/
module.exports = function server() {
var browserchannel = require('browserchannel')
, Spark = this.Spark
, primus = this.primus
, query = {};
//
// We've received a new connection, create a new Spark. The Spark will
// automatically announce it self as a new connection once it's created (after
// the next tick).
//
this.service = browserchannel.server({
base: primus.pathname
}, function connection(socket) {
var spark = new Spark(
socket.headers // HTTP request headers.
, socket.address // IP address.
, query // Query string, not allowed by browser channel.
, socket.id // Unique connection id.
);
spark.on('outgoing::end', function end() {
socket.close();
}).on('outgoing::data', function write(data) {
socket.send(data);
});
socket.on('close', spark.emits('end'));
socket.on('message', spark.emits('data'));
});
//
// Listen to upgrade requests.
//
this.on('request', function request(req, res, next) {
//
// The browser.channel returns a middleware layer.
//
this.service(req, res, next);
});
};
|
Read JSON file to be processed | #!/usr/bin/env python
"""
This script cleans and processes JSON data scraped, using Scrapy, from
workabroad.ph.
"""
import argparse
import codecs
import os
import json
import sys
def main():
parser = argparse.ArgumentParser(description="Sanitize workabroad.ph scraped data")
parser.add_argument("export", help="Export file format, 'csv' or 'json'")
parser.add_argument("inputfile", help="Text file to be parsed")
parser.add_argument("outputfile", help="Name of file to export data to")
parser.add_argument("-v", "--verbose", help="Increase output verbosity, "
"use when debugging only", action="store_true")
global args
args = parser.parse_args()
file_path = os.path.dirname(os.path.abspath(__file__)) + '/' + args.inputfile
with codecs.open(file_path, 'r', 'utf-8') as json_data:
items = json.load(json_data)
for i, item in enumerate(items):
pass
if args.export == "csv":
pass
elif args.export == "json":
pass
else:
sys.exit("Invalid export file format: " + args.export + ", only 'csv' and "
"'json' is accepted")
if __name__ == '__main__':
main()
| #!/usr/bin/env python
"""
This script cleans and processes JSON data scraped, using Scrapy, from
workabroad.ph.
"""
import argparse
import json
import sys
def main():
parser = argparse.ArgumentParser(description="Sanitize workabroad.ph scraped data")
parser.add_argument("export", help="Export file format, 'csv' or 'json'")
parser.add_argument("inputfile", help="Text file to be parsed")
parser.add_argument("outputfile", help="Name of file to export data to")
parser.add_argument("-v", "--verbose", help="Increase output verbosity, "
"use when debugging only", action="store_true")
global args
args = parser.parse_args()
if args.export == "csv":
pass
elif args.export == "json":
pass
else:
sys.exit("Invalid export file format: " + args.export + ", only 'csv' and "
"'json' is accepted")
if __name__ == '__main__':
main()
|
Add code to create bin directory if it doesn't exist. | 'use strict';
const fs = require('fs'),
config = require('./config/generator.js'),
log = require('bunyan').createLogger({name: "ProducerConsumer: index"});
const generators = config.GENERATORS;
const keys = Object.keys(generators),
path = './bin/';
var id = '',
script = '',
fileName = '',
namespace = '';
// Loop through generators
for (let generator in keys) {
namespace = keys[generator];
id = namespace.replace('node', '');
// Create a script for each generator
script = 'node run-generator.js ' + generators[namespace].port + ' ' + id;
// Create file for each generator
let fileName = 'generator' + id + '.sh';
// Create bin folder if it does not exist
if (!fs.existsSync(path)) {
fs.mkdirSync(path);
}
// Write script file
fs.writeFile(path + fileName, script, function(err) {
if (err) {
log.error('Error: ' + err);
}
// Change file permissions
fs.chmodSync(path + fileName, '777');
log.info('The file ' + fileName + ' was saved!');
});
} | 'use strict';
const fs = require('fs'),
config = require('./config/generator.js'),
log = require('bunyan').createLogger({name: "ProducerConsumer: index"});
const generators = config.GENERATORS;
const keys = Object.keys(generators),
path = './bin/';
var id = '',
script = '',
fileName = '',
namespace = '';
// Loop through generators
for (let generator in keys) {
namespace = keys[generator];
id = namespace.replace('node', '');
// Create a script for each generator
script = 'node run-generator.js ' + generators[namespace].port + ' ' + id;
// Create file for each generator
let fileName = 'generator' + id + '.sh';
// Write script file
fs.writeFile(path + fileName, script, function(err) {
if (err) {
log.error('Error: ' + err);
}
// Change file permissions
fs.chmodSync(path + fileName, '777');
log.info('The file ' + fileName + ' was saved!');
});
} |
FIX Babel reject duplicated variable name | class KeyMap {
constructor() {
this.map = new Map();
}
set(key, value) {
let list = this.map.get(key);
if (!list) {
list = new Set();
this.map.set(key, list);
}
if (value) {
list.add(value);
}
return list;
}
shift(key, value) {
let set = this.map.get(key);
if (set && set.size) {
if (set.has(value)) {
set.delete(value);
return value;
} else {
for(let result of set) {
set.delete(result);
return result;
}
}
}
return false;
}
}
export default KeyMap;
| class KeyMap {
constructor() {
this.map = new Map();
}
set(key, value) {
let set = this.map.get(key);
if (!set) {
set = new Set();
this.map.set(key, set);
}
if (value) {
set.add(value);
}
return set;
}
shift(key, value) {
let set = this.map.get(key);
if (set && set.size) {
if (set.has(value)) {
set.delete(value);
return value;
} else {
for(let result of set) {
set.delete(result);
return result;
}
}
}
return false;
}
}
export default KeyMap;
|
Set verification image height and width in html | <?php
class CaptchaField extends TextField {
function __construct($name, $title = null, $value = "", $form = null){
parent::__construct($name, $title, $value, $form);
}
function Field($properties = array()) {
$attributes = array(
'type' => 'text',
'class' => 'CaptchaField',
'id' => $this->id(),
'name' => $this->getName(),
'value' => $this->Value(),
'tabindex' => $this->getAttribute("tabindex"),
'maxlength' => 4,
'size' => 30
);
// create link to image to display code
$html = '<img src="' . _EnquiryPageBase .'/images/captcha.jpg?' . time() . '" class="customcaptcha-image" alt="CAPTCHA security code" width="60" height="24" />';
// create input field
$html .= $this->createTag('input', $attributes);
return $html;
}
// SERVER-SIDE VALIDATION (to ensure a browser with javascript disabled doesn't bypass validation)
function validate($validator){
$this->value = trim($this->value);
$SessionCaptcha = Session::get('customcaptcha');
if ( md5(trim($this->value).$_SERVER['REMOTE_ADDR']).'a4xn' != $SessionCaptcha ) {
$validator->validationError(
$this->name,
'Codes do not match, please try again',
'required'
);
}
}
} | <?php
class CaptchaField extends TextField {
function __construct($name, $title = null, $value = "", $form = null){
parent::__construct($name, $title, $value, $form);
}
function Field($properties = array()) {
$attributes = array(
'type' => 'text',
'class' => 'CaptchaField',
'id' => $this->id(),
'name' => $this->getName(),
'value' => $this->Value(),
'tabindex' => $this->getAttribute("tabindex"),
'maxlength' => 4,
'size' => 30
);
// create link to image to display code
$html = '<img src="' . _EnquiryPageBase .'/images/captcha.jpg?' . time() . '" class="customcaptcha-image" alt="CAPTCHA security code" />';
// create input field
$html .= $this->createTag('input', $attributes);
return $html;
}
// SERVER-SIDE VALIDATION (to ensure a browser with javascript disabled doesn't bypass validation)
function validate($validator){
$this->value = trim($this->value);
$SessionCaptcha = Session::get('customcaptcha');
if ( md5(trim($this->value).$_SERVER['REMOTE_ADDR']).'a4xn' != $SessionCaptcha ) {
$validator->validationError(
$this->name,
'Codes do not match, please try again',
'required'
);
}
}
} |
Remove extended default value, should pass null instead. | package com.uwetrottmann.trakt5.enums;
/**
* By default, all methods will return minimal info for movies, shows, episodes, and users. Minimal info is typically
* all you need to match locally cached items and includes the title, year, and ids. However, you can request different
* extended levels of information.
*/
public enum Extended implements TraktEnum {
/** Complete info for an item. */
FULL("full"),
/** Only works with sync watchedShows. */
NOSEASONS("noseasons"),
/** Only works with seasons/summary */
EPISODES("episodes"),
/** Only works with seasons/summary */
FULLEPISODES("full,episodes");
private final String value;
Extended(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
}
| package com.uwetrottmann.trakt5.enums;
/**
* By default, all methods will return minimal info for movies, shows, episodes, and users. Minimal info is typically
* all you need to match locally cached items and includes the title, year, and ids. However, you can request different
* extended levels of information.
*/
public enum Extended implements TraktEnum {
/** Default. Returns enough info to match locally. */
DEFAULT_MIN("min"),
/** Complete info for an item. */
FULL("full"),
/** Only works with sync watchedShows. */
NOSEASONS("noseasons"),
/** Only works with seasons/summary */
EPISODES("episodes"),
/** Only works with seasons/summary */
FULLEPISODES("full,episodes");
private final String value;
Extended(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
}
|
Use /tmp directory instead of local profiles directory | var debug = require('debug')('testbot:farm');
var spawn = require('child_process').spawn;
var path = require('path');
var qs = require('querystring');
var bots = {};
exports.start = function(id, opts, callback) {
var bot;
var args = [
'--console',
'--no-first-run',
'--use-fake-device-for-media-stream', // TODO: customize
'--use-fake-ui-for-media-stream',
'--user-data-dir=/tmp/' + id
];
var example = ((opts || {}).example || 'main');
var url = 'http://localhost:3000/examples/' + example + '.html?' + qs.stringify(opts);
var spawnOpts = {
env: {
DISPLAY: ':99'
}
};
debug('bot ' + id + ' url: ' + url);
bot = spawn('google-chrome', args.concat([ url ]), spawnOpts);
bot.on('close', function(code) {
debug('bot ' + id + ' closed, code: ' + code);
});
bot.stdout.on('data', function (data) {
console.log('stdout: ' + data);
});
bot.stderr.on('data', function (data) {
console.log('stderr: ' + data);
});
callback();
};
| var debug = require('debug')('testbot:farm');
var spawn = require('child_process').spawn;
var path = require('path');
var mkdirp = require('mkdirp');
var qs = require('querystring');
var bots = {};
exports.start = function(id, opts, callback) {
var bot;
var profiledir = path.resolve(__dirname, 'profiles', id);
var args = [
'--console',
'--no-first-run',
'--use-fake-device-for-media-stream', // TODO: customize
'--use-fake-ui-for-media-stream',
'--user-data-dir=' + profiledir
];
var example = ((opts || {}).example || 'main');
var url = 'http://localhost/examples/' + example + '.html?' + qs.stringify(opts);
var spawnOpts = {
env: {
DISPLAY: ':99'
}
};
// TODO: kill existing bot if it exists
mkdirp(profiledir, function(err) {
if (err) {
return callback(err);
}
debug('bot ' + id + ' url: ' + url);
bot = spawn('google-chrome', args.concat([ url ]), spawnOpts);
callback();
});
};
|
Fix urlconf to avoid string view arguments to url() |
__author__ = "Individual contributors (see AUTHORS file)"
__date__ = "$DATE$"
__rev__ = "$REV$"
__license__ = "AGPL v.3"
__copyright__ = """
This file is part of ArgCache.
Copyright (c) 2015 by the individual contributors
(see AUTHORS file)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
from django.conf.urls import url
from .views import view_all, flush
urlpatterns = [
url(r'^view_all/?$', view_all, name='view_all'),
url(r'^flush/([0-9]+)/?$', flush, name='flush')
]
|
__author__ = "Individual contributors (see AUTHORS file)"
__date__ = "$DATE$"
__rev__ = "$REV$"
__license__ = "AGPL v.3"
__copyright__ = """
This file is part of ArgCache.
Copyright (c) 2015 by the individual contributors
(see AUTHORS file)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
from django.conf.urls import *
urlpatterns = [
url(r'^view_all/?$', 'argcache.views.view_all', name='view_all'),
url(r'^flush/([0-9]+)/?$', 'argcache.views.flush', name='flush')
]
|
Remove report allocs from benchmark
Also add the command to run the benchmarks. | // Copyright (C) 2015 Thomas de Zeeuw.
//
// Licensed under the MIT license that can be found in the LICENSE file.
package logger
import "testing"
// go test -run none -bench . -benchmem -benchtime 10s
var (
benchmarkResultTagString string
benchmarkResultTagBytes []byte
benchmarkResultTagJSON []byte
)
func BenchmarkTags_String(b *testing.B) {
var str string
for n := 0; n < b.N; n++ {
str = Tags{"hi", "world"}.String()
}
benchmarkResultTagString = str
}
func BenchmarkTags_Bytes(b *testing.B) {
var bb []byte
for n := 0; n < b.N; n++ {
bb = Tags{"hi", "world"}.Bytes()
}
benchmarkResultTagBytes = bb
}
func BenchmarkTags_MarshalJSON(b *testing.B) {
var json []byte
for n := 0; n < b.N; n++ {
json, _ = Tags{"hi", "world"}.MarshalJSON()
}
benchmarkResultTagJSON = json
}
| // Copyright (C) 2015 Thomas de Zeeuw.
//
// Licensed under the MIT license that can be found in the LICENSE file.
package logger
import "testing"
var (
benchmarkResultTagString string
benchmarkResultTagBytes []byte
benchmarkResultTagJSON []byte
)
func BenchmarkTags_String(b *testing.B) {
b.ReportAllocs()
var str string
for n := 0; n < b.N; n++ {
str = Tags{"hi", "world"}.String()
}
benchmarkResultTagString = str
}
func BenchmarkTags_Bytes(b *testing.B) {
b.ReportAllocs()
var bb []byte
for n := 0; n < b.N; n++ {
bb = Tags{"hi", "world"}.Bytes()
}
benchmarkResultTagBytes = bb
}
func BenchmarkTags_MarshalJSON(b *testing.B) {
b.ReportAllocs()
var json []byte
for n := 0; n < b.N; n++ {
json, _ = Tags{"hi", "world"}.MarshalJSON()
}
benchmarkResultTagJSON = json
}
|
Make plugin more stable by introducing async renaming to alternative name | import sublime_plugin
from threading import Timer
DEFAULT_NAME = 'Find Results'
ALT_NAME = 'Find Results '
class OpenSearchInNewTab(sublime_plugin.EventListener):
# set a bit changed name
# so the tab won't be bothered
# during new search
def on_activated(self, view):
if self.is_search_view(view):
self.apply_alt_name(view)
# these hooks will help other plugins
# to understand that we are in search results file
def on_text_command(self, view, command_name, args):
if self.is_search_view(view):
self.apply_default_name(view)
def post_text_command(self, view, command_name, args):
if self.is_search_view(view):
self.apply_alt_name(view)
def apply_alt_name(self, view):
view.set_name(ALT_NAME)
def apply_default_name(self, view):
view.set_name(DEFAULT_NAME)
t = Timer(.1, self.apply_alt_name, (view,))
t.start()
def is_search_view(self, view):
name = view.name()
return name == ALT_NAME or name == DEFAULT_NAME
| import sublime_plugin
DEFAULT_NAME = 'Find Results'
ALT_NAME = 'Find Results '
class OpenSearchInNewTab(sublime_plugin.EventListener):
# set a bit changed name
# so the tab won't be bothered
# during new search
def on_activated(self, view):
if self.is_search_view(view):
self.apply_alt_name(view)
# these hooks will help other plugins
# to understand that we are in search results file
def on_text_command(self, view, command_name, args):
if self.is_search_view(view):
view.set_name(DEFAULT_NAME)
def post_text_command(self, view, command_name, args):
if self.is_search_view(view):
self.apply_alt_name(view)
def apply_alt_name(self, view):
view.set_name(ALT_NAME)
def is_search_view(self, view):
name = view.name()
return name == ALT_NAME or name == DEFAULT_NAME
|
Change import level of flask. | import StringIO
import base64
import signal
import flask
from quiver.plotter import FieldPlotter
app = flask.Flask(__name__)
@app.route('/')
def quiver():
'''Route for homepage'''
return flask.render_template('quiver.html')
@app.route('/plot/', methods=['GET',])
def plot():
equation_string = flask.request.args.get('equation')
diff_equation = FieldPlotter()
diff_equation.set_equation_from_string(equation_string)
diff_equation.make_plot()
# If plotting was successful, write plot out
if diff_equation.figure:
# Write output to memory and add to response object
output = StringIO.StringIO()
response = flask.make_response(base64.b64encode(diff_equation.write_data(output)))
response.mimetype = 'image/png'
return response
else:
return flask.make_response('')
@app.route('/data/', methods=['GET',])
def data():
equation_string = flask.request.args.get('equation')
plotter = FieldPlotter()
plotter.set_equation_from_string(equation_string)
plotter.make_data()
if __name__ == '__main__':
app.run(debug=True) | import StringIO
import base64
import signal
from flask import Flask, render_template, request, make_response
from quiver.plotter import FieldPlotter
app = Flask(__name__)
@app.route('/')
def quiver():
'''Route for homepage'''
return render_template('quiver.html')
@app.route('/plot/', methods=['GET',])
def plot():
equation_string = request.args.get('equation')
diff_equation = FieldPlotter()
diff_equation.set_equation_from_string(equation_string)
diff_equation.make_plot()
# If plotting was successful, write plot out
if diff_equation.figure:
# Write output to memory and add to response object
output = StringIO.StringIO()
response = make_response(base64.b64encode(diff_equation.write_data(output)))
response.mimetype = 'image/png'
return response
else:
return make_response('')
@app.route('/data/', methods=['GET',])
def data():
equation_string = request.args.get('equation')
plotter = FieldPlotter()
plotter.set_equation_from_string(equation_string)
plotter.make_data()
if __name__ == '__main__':
app.run(debug=True) |
Use TestAppCKAN in test instead of LocalCKAN | import nose
from ckanapi import TestAppCKAN, ValidationError
from ckan.tests import helpers, factories
eq_ = nose.tools.eq_
assert_true = nose.tools.assert_true
class TestValidation(helpers.FunctionalTestBase):
def test_invalid_url(self):
factories.Sysadmin(apikey="my-test-key")
app = self._get_test_app()
demo = TestAppCKAN(app, apikey="my-test-key")
try:
dataset = factories.Dataset()
demo.action.resource_create(
package_id=dataset['name'],
name='Test-File',
url='https://example.com]'
)
except ValidationError as e:
eq_(
e.error_dict['url'],
[u'Bitte eine valide URL angeben']
)
else:
raise AssertionError('ValidationError not raised')
| import nose
from ckanapi import LocalCKAN, ValidationError
from ckan.tests import helpers, factories
eq_ = nose.tools.eq_
assert_true = nose.tools.assert_true
class TestValidation(helpers.FunctionalTestBase):
def test_invalid_url(self):
lc = LocalCKAN()
try:
dataset = factories.Dataset()
lc.call_action(
'resource_create',
{
'package_id': dataset['name'],
'name': 'Test-File',
'url': 'https://example.com]'
}
)
except ValidationError as e:
eq_(
e.error_dict['url'],
[u'Please provide a valid URL']
)
else:
raise AssertionError('ValidationError not raised')
|
Call get_section from get_object for backwards compatibility | from django.core.urlresolvers import reverse
from django.views.generic import DetailView
from django.contrib.syndication.views import Feed
from django.shortcuts import get_object_or_404
from .models import Section
class SimpleSectionView(DetailView):
context_object_name = 'section'
model = Section
def get_object(self):
return self.get_section()
def get_section(self):
return get_object_or_404(self.get_queryset(),
full_slug=self.kwargs['full_slug'])
class SectionFeed(Feed):
def __init__(self, section_view, *args, **kwargs):
self.section_view = section_view
def get_object(self, request, full_slug):
return Section.objects.get(full_slug=full_slug)
def title(self, section):
return section.title
def link(self, section):
return reverse(self.section_view,
kwargs={'full_slug': section.full_slug})
def description(self, section):
return section.summary
def items(self, section):
return section.items
| from django.core.urlresolvers import reverse
from django.views.generic import DetailView
from django.contrib.syndication.views import Feed
from django.shortcuts import get_object_or_404
from .models import Section
class SimpleSectionView(DetailView):
context_object_name = 'section'
model = Section
def get_object(self, queryset=None):
return get_object_or_404(self.get_queryset(),
full_slug=self.kwargs['full_slug'])
class SectionFeed(Feed):
def __init__(self, section_view, *args, **kwargs):
self.section_view = section_view
def get_object(self, request, full_slug):
return Section.objects.get(full_slug=full_slug)
def title(self, section):
return section.title
def link(self, section):
return reverse(self.section_view,
kwargs={'full_slug': section.full_slug})
def description(self, section):
return section.summary
def items(self, section):
return section.items
|
Decrease idle time for connection pool. | var fs = require('fs')
, path = require('path')
, Sequelize = require('sequelize')
, _ = require('lodash')
, config = require('../../config/secrets')
, db = {};
var sequelize = new Sequelize('heroku_d1f5087a2a4be69', 'b3b2d36bdf806e', '9df7b11c', {
host: 'us-cdbr-iron-east-04.cleardb.net',
dialect: 'mysql',
pool: {
max: 5,
min: 0,
idle: 5000
},
});
fs
.readdirSync(__dirname)
.filter(function(file) {
return (file.indexOf('.') !== 0) && (file !== 'index.js');
})
.forEach(function(file) {
var model = sequelize.import(path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(function(modelName) {
if ('associate' in db[modelName]) {
db[modelName].associate(db);
}
});
module.exports = _.extend({
sequelize: sequelize,
Sequelize: Sequelize
}, db); | var fs = require('fs')
, path = require('path')
, Sequelize = require('sequelize')
, _ = require('lodash')
, config = require('../../config/secrets')
, db = {};
var sequelize = new Sequelize('heroku_d1f5087a2a4be69', 'b3b2d36bdf806e', '9df7b11c', {
host: 'us-cdbr-iron-east-04.cleardb.net',
dialect: 'mysql',
pool: {
max: 5,
min: 0,
idle: 10000
},
});
fs
.readdirSync(__dirname)
.filter(function(file) {
return (file.indexOf('.') !== 0) && (file !== 'index.js');
})
.forEach(function(file) {
var model = sequelize.import(path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(function(modelName) {
if ('associate' in db[modelName]) {
db[modelName].associate(db);
}
});
module.exports = _.extend({
sequelize: sequelize,
Sequelize: Sequelize
}, db); |
Use performance.now instead of Date.now | function easing(time) {
return 1 - (--time) * time * time * time;
};
/**
* Given a start/end point of a scroll and time elapsed, calculate the scroll position we should be at
* @param {Number} start - the initial value
* @param {Number} stop - the final desired value
* @param {Number} elapsed - the amount of time elapsed since we started animating
* @param {Number} - duration - the duration of the animation
* @return {Number} - The value we should use on the next tick
*/
function getValue(start, end, elapsed, duration) {
if (elapsed > duration) return end;
return start + (end - start) * easing(elapsed / duration);
};
/**
* Smoothly animate between two values
* @param {Number} fromValue - the initial value
* @param {Function} onUpdate - A function that is called on each tick
* @param {Function} onComplete - A callback that is fired once the scroll animation ends
* @param {Number} duration - the desired duration of the scroll animation
*/
export default function animate({
fromValue,
toValue,
onUpdate,
onComplete,
duration = 600,
}) {
const startTime = performance.now();
const tick = () => {
const elapsed = performance.now() - startTime;
window.requestAnimationFrame(() => onUpdate(
getValue(fromValue, toValue, elapsed, duration),
// Callback
elapsed <= duration
? tick
: onComplete
));
};
tick();
};
| function easing(time) {
return 1 - (--time) * time * time * time;
};
/**
* Given a start/end point of a scroll and time elapsed, calculate the scroll position we should be at
* @param {Number} start - the initial value
* @param {Number} stop - the final desired value
* @param {Number} elapsed - the amount of time elapsed since we started animating
* @param {Number} - duration - the duration of the animation
* @return {Number} - The value we should use on the next tick
*/
function getValue(start, end, elapsed, duration) {
if (elapsed > duration) return end;
return start + (end - start) * easing(elapsed / duration);
};
/**
* Smoothly animate between two values
* @param {Number} fromValue - the initial value
* @param {Function} onUpdate - A function that is called on each tick
* @param {Function} onComplete - A callback that is fired once the scroll animation ends
* @param {Number} duration - the desired duration of the scroll animation
*/
export default function animate({
fromValue,
toValue,
onUpdate,
onComplete,
duration = 600,
}) {
const startTime = Date.now();
const tick = () => {
const elapsed = Date.now() - startTime;
window.requestAnimationFrame(() => onUpdate(
getValue(fromValue, toValue, elapsed, duration),
// Callback
elapsed <= duration
? tick
: onComplete
));
};
tick();
};
|
Add proxy fix as in lr this will run with reverse proxy | import os
import logging
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from raven.contrib.flask import Sentry
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
from werkzeug.contrib.fixers import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app)
db = SQLAlchemy(app)
def configure_logging(obj):
logger = logging.getLogger(obj.__class__.__name__)
logger.addHandler(logging.StreamHandler())
if app.config['DEBUG']:
logger.setLevel(logging.DEBUG)
else:
logger.setLevel(logging.INFO)
return logger
# Sentry exception reporting
if 'SENTRY_DSN' in os.environ:
sentry = Sentry(app, dsn=os.environ['SENTRY_DSN'])
if not app.debug:
app.logger.addHandler(logging.StreamHandler())
app.logger.setLevel(logging.INFO)
app.logger.debug("\nConfiguration\n%s\n" % app.config)
def configure_health():
from systemofrecord.health import Health
from systemofrecord.repository import blockchain_object_repository
from systemofrecord.services import ingest_queue, chain_queue
Health(app,
checks=[blockchain_object_repository.health,
ingest_queue.health,
chain_queue.health
])
configure_health()
| import os
import logging
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from raven.contrib.flask import Sentry
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
db = SQLAlchemy(app)
def configure_logging(obj):
logger = logging.getLogger(obj.__class__.__name__)
logger.addHandler(logging.StreamHandler())
if app.config['DEBUG']:
logger.setLevel(logging.DEBUG)
else:
logger.setLevel(logging.INFO)
return logger
# Sentry exception reporting
if 'SENTRY_DSN' in os.environ:
sentry = Sentry(app, dsn=os.environ['SENTRY_DSN'])
if not app.debug:
app.logger.addHandler(logging.StreamHandler())
app.logger.setLevel(logging.INFO)
app.logger.debug("\nConfiguration\n%s\n" % app.config)
def configure_health():
from systemofrecord.health import Health
from systemofrecord.repository import blockchain_object_repository
from systemofrecord.services import ingest_queue, chain_queue
Health(app,
checks=[blockchain_object_repository.health,
ingest_queue.health,
chain_queue.health
])
configure_health()
|
Fix a typo on about page | const React = require('react');
import { PAGES } from '../constants';
const PACKAGE = require('../../../package.json');
module.exports = class PageAbout extends React.Component {
goToFeedback (e) {
e.preventDefault();
this.props.navigateTo(PAGES.FEEDBACK);
}
render() {
return (
<section>
<h3>HotS Talent Picks</h3>
<p>Hi! This is a simple app developed to bring you the invaluable data from <a href='http://www.hotslogs.com/' target='_blank'>Hotslogs.com</a> (which by the way an awesome site, please consider supporting them!).</p>
<p>You can contact me via the <a href='http://forums.overwolf.com/index.php?/user/15488-fullbarrel/' target='_blank'>Overwolf Forums</a>, <a href='mailto:dfilipidisz@gmail.com' target='_blank'>email</a>, or via the <a href='#' onClick={this.goToFeedback.bind(this)}>Feedback page</a>.</p>
<p>App version: <b>v{PACKAGE.version}</b> - <a href='https://github.com/dfilipidisz/overwolf-hots-talents/blob/master/CHANGELOG.md' target='_BLANK'>changelog</a></p>
</section>
);
}
}; | const React = require('react');
import { PAGES } from '../constants';
const PACKAGE = require('../../../package.json');
module.exports = class PageAbout extends React.Component {
goToFeedback (e) {
e.preventDefault();
this.props.navigateTo(PAGES.FEEDBACK);
}
render() {
return (
<section>
<h3>HotS Talent Picks</h3>
<p>Hi! This is a simple app developed to bring your the invaluable data from <a href='http://www.hotslogs.com/' target='_blank'>Hotslogs.com</a> (which by the way an awesome site, please consider supporting them!).</p>
<p>You can contact me via the <a href='http://forums.overwolf.com/index.php?/user/15488-fullbarrel/' target='_blank'>Overwolf Forums</a>, <a href='mailto:dfilipidisz@gmail.com' target='_blank'>email</a>, or via the <a href='#' onClick={this.goToFeedback.bind(this)}>Feedback page</a>.</p>
<p>App version: <b>v{PACKAGE.version}</b> - <a href='https://github.com/dfilipidisz/overwolf-hots-talents/blob/master/CHANGELOG.md' target='_BLANK'>changelog</a></p>
</section>
);
}
}; |
Use default port fo compiling skin | const puppeteer = require("puppeteer");
// const DATA_URI = /url\([^)]+\)/g;
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
// TODO: allow the skin to be passed in via the CLI.
try {
await page.goto(
'http://localhost:8080/#{"skinUrl":"/skins/base-2.91.wsz"}'
);
} catch (e) {
console.error(
"Error connecting to localhost:8080. Are you running the dev server?",
"\n\n",
e
);
await browser.close();
return;
}
// TODO: Wait for node to be ready
await new Promise(resolve => setTimeout(resolve, 200));
const css = await page.evaluate(
() => document.getElementById("webamp-skin").innerText
);
// TODO: Extract non-CSS stuff
// TODO: Extract data URIs and optimize
// TODO: Minify the CSS
await browser.close();
// TODO: Write to stdout
console.log(css);
})();
| const puppeteer = require("puppeteer");
// const DATA_URI = /url\([^)]+\)/g;
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
// TODO: allow the skin to be passed in via the CLI.
try {
await page.goto(
'http://localhost:8081/#{"skinUrl":"/skins/base-2.91.wsz"}'
);
} catch (e) {
console.error(
"Error connecting to localhost:8081. Are you running the dev server?",
"\n\n",
e
);
await browser.close();
return;
}
// TODO: Wait for node to be ready
await new Promise(resolve => setTimeout(resolve, 200));
const css = await page.evaluate(
() => document.getElementById("webamp-skin").innerText
);
// TODO: Extract non-CSS stuff
// TODO: Extract data URIs and optimize
// TODO: Minify the CSS
await browser.close();
// TODO: Write to stdout
console.log(css);
})();
|
Print statements updated to be compatible with Python 3. | from channels.generic.websockets import WebsocketConsumer, JsonWebsocketConsumer
from .jsonrpcwebsocketconsumer import JsonRpcWebsocketConsumer
class MyJsonRpcWebsocketConsumer(JsonRpcWebsocketConsumer):
# Set to True if you want them, else leave out
strict_ordering = False
slight_ordering = False
def connection_groups(self, **kwargs):
"""
Called to return the list of groups to automatically add/remove
this connection to/from.
"""
return ["test"]
def receive(self, content, **kwargs):
"""
Called when a message is received with decoded JSON content
"""
# Simple echo
print("received: %s" % content)
print("kwargs %s" % kwargs)
self.send(content)
def disconnect(self, message, **kwargs):
"""
Perform things on connection close
"""
print("disconnect")
@MyJsonRpcWebsocketConsumer.rpc_method()
def ping():
return "pong" | from channels.generic.websockets import WebsocketConsumer, JsonWebsocketConsumer
from .jsonrpcwebsocketconsumer import JsonRpcWebsocketConsumer
class MyJsonRpcWebsocketConsumer(JsonRpcWebsocketConsumer):
# Set to True if you want them, else leave out
strict_ordering = False
slight_ordering = False
def connection_groups(self, **kwargs):
"""
Called to return the list of groups to automatically add/remove
this connection to/from.
"""
return ["test"]
def receive(self, content, **kwargs):
"""
Called when a message is received with decoded JSON content
"""
# Simple echo
print "received: %s" % content
print "kwargs %s" % kwargs
self.send(content)
def disconnect(self, message, **kwargs):
"""
Perform things on connection close
"""
print "disconnect"
@MyJsonRpcWebsocketConsumer.rpc_method()
def ping():
return "pong" |
Move functions out of route endpoint. | var async = require('async');
var User = require('../models/user');
var BadgeInstance = require('../models/badge-instance');
exports.showFlushDbForm = function (req, res) {
return res.render('admin/flush-user-info.html', {
issuer: req.issuer,
});
};
function removeItem(item, callback) {
return item.remove(callback);
}
function removeAfterFind(callback) {
return function (err, items) {
if (err) return callback(err);
return async.map(items, removeItem, callback);
}
}
function flushUsers(callback) {
User.find(removeAfterFind(callback));
}
function flushInstances(callback) {
BadgeInstance.find(removeAfterFind(callback));
}
exports.flushDb = function flushDb(req, res) {
async.parallel([ flushUsers, flushInstances ], function (err, results) {
console.dir(err);
console.dir(results);
res.redirect(303, '/')
});
}; | var async = require('async');
var User = require('../models/user');
var BadgeInstance = require('../models/badge-instance');
exports.showFlushDbForm = function (req, res) {
return res.render('admin/flush-user-info.html', {
issuer: req.issuer,
});
};
exports.flushDb = function flushDb(req, res) {
function removeItem(item, callback) {
return item.remove(callback);
}
function removeAfterFind(callback) {
return function (err, items) {
if (err) return callback(err);
return async.map(items, removeItem, callback);
}
}
function flushUsers(callback) {
User.find(removeAfterFind(callback));
}
function flushInstances(callback) {
BadgeInstance.find(removeAfterFind(callback));
}
async.parallel([ flushUsers, flushInstances ], function (err, results) {
console.dir(err);
console.dir(results);
res.redirect(303, '/')
});
}; |
Reset changes to User controller. | /**
* UsersController
*
* @description :: Server-side logic for managing Users
* @help :: See http://links.sailsjs.org/docs/controllers
*/
module.exports = {
index: function (req, res) {
return res.json({
todo: 'index() is not implemented yet!'
});
},
create: function (req, res) {
return res.json({
todo: 'create() is not implemented yet!'
});
},
show: function (req, res) {
return res.json({
todo: 'show() is not implemented yet!'
});
},
edit: function (req, res) {
return res.json({
todo: 'edit() is not implemented yet!'
});
},
delete: function (req, res) {
return res.json({
todo: 'delete() is not implemented yet!'
});
}
};
| /**
* UsersController
*
* @description :: Server-side logic for managing Users
* @help :: See http://links.sailsjs.org/docs/controllers
*/
module.exports = {
index: function (req, res) {
return res.json({
todo: 'index() is not implemented yet!'
});
},
create: function (req, res) {
User.create({email:"test@test.com", password:"test"});
return res.json({
todo: 'create() is not implemented yet....but we still snuck in a user. ;)'
});
},
show: function (req, res) {
return res.json({
todo: 'show() is not implemented yet!'
});
},
edit: function (req, res) {
return res.json({
todo: 'edit() is not implemented yet!'
});
},
delete: function (req, res) {
return res.json({
todo: 'delete() is not implemented yet!'
});
}
};
|
Check if user is indeed using 1.9 to 1.8 protocol conversion | package us.myles.ViaVersion.protocols.protocol1_9to1_8.listeners;
import lombok.RequiredArgsConstructor;
import org.bukkit.block.Block;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockPlaceEvent;
import us.myles.ViaVersion.ViaVersionPlugin;
import us.myles.ViaVersion.api.data.UserConnection;
import us.myles.ViaVersion.api.minecraft.Position;
import us.myles.ViaVersion.protocols.base.ProtocolInfo;
import us.myles.ViaVersion.protocols.protocol1_9to1_8.Protocol1_9TO1_8;
import us.myles.ViaVersion.protocols.protocol1_9to1_8.storage.EntityTracker;
@RequiredArgsConstructor
public class BlockListener implements Listener {
private final ViaVersionPlugin plugin;
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void placeBlock(BlockPlaceEvent e) {
if(plugin.isPorted(e.getPlayer())) {
UserConnection c = plugin.getConnection(e.getPlayer());
if (!c.get(ProtocolInfo.class).getPipeline().contains(Protocol1_9TO1_8.class)) return;
Block b = e.getBlockPlaced();
plugin.getConnection(e.getPlayer()).get(EntityTracker.class).addBlockInteraction(new Position((long) b.getX(), (long) b.getY(), (long) b.getZ()));
}
}
}
| package us.myles.ViaVersion.protocols.protocol1_9to1_8.listeners;
import lombok.RequiredArgsConstructor;
import org.bukkit.block.Block;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockPlaceEvent;
import us.myles.ViaVersion.ViaVersionPlugin;
import us.myles.ViaVersion.api.minecraft.Position;
import us.myles.ViaVersion.protocols.protocol1_9to1_8.storage.EntityTracker;
@RequiredArgsConstructor
public class BlockListener implements Listener{
private final ViaVersionPlugin plugin;
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void placeBlock(BlockPlaceEvent e) {
if(plugin.isPorted(e.getPlayer())) {
Block b = e.getBlockPlaced();
plugin.getConnection(e.getPlayer()).get(EntityTracker.class).addBlockInteraction(new Position((long)b.getX(), (long)b.getY(), (long)b.getZ()));
}
}
}
|
Add coverage of __repr__ of app. | from morepath.app import App, global_app
import morepath
def setup_module(module):
morepath.disable_implicit()
def test_global_app():
assert global_app.extends == []
assert global_app.name == 'global_app'
def test_app_without_extends():
myapp = App()
assert myapp.extends == [global_app]
assert myapp.name == ''
def test_app_with_extends():
parentapp = App()
myapp = App('myapp', extends=parentapp)
assert myapp.extends == [parentapp]
assert myapp.name == 'myapp'
def test_app_caching_lookup():
class MockClassLookup(object):
called = 0
def all(self, key, classes):
self.called += 1
return ["answer"]
class MockApp(MockClassLookup, App):
pass
myapp = MockApp()
lookup = myapp.lookup
answer = lookup.component('foo', [])
assert answer == 'answer'
assert myapp.called == 1
# after this the answer will be cached for those parameters
answer = lookup.component('foo', [])
assert myapp.called == 1
answer = myapp.lookup.component('foo', [])
assert myapp.called == 1
# but different parameters does trigger another call
lookup.component('bar', [])
assert myapp.called == 2
def test_app_name():
app = morepath.App(name='foo')
assert repr(app) == "<morepath.App 'foo'>"
| from morepath.app import App, global_app
import morepath
def setup_module(module):
morepath.disable_implicit()
def test_global_app():
assert global_app.extends == []
assert global_app.name == 'global_app'
def test_app_without_extends():
myapp = App()
assert myapp.extends == [global_app]
assert myapp.name == ''
def test_app_with_extends():
parentapp = App()
myapp = App('myapp', extends=parentapp)
assert myapp.extends == [parentapp]
assert myapp.name == 'myapp'
def test_app_caching_lookup():
class MockClassLookup(object):
called = 0
def all(self, key, classes):
self.called += 1
return ["answer"]
class MockApp(MockClassLookup, App):
pass
myapp = MockApp()
lookup = myapp.lookup
answer = lookup.component('foo', [])
assert answer == 'answer'
assert myapp.called == 1
# after this the answer will be cached for those parameters
answer = lookup.component('foo', [])
assert myapp.called == 1
answer = myapp.lookup.component('foo', [])
assert myapp.called == 1
# but different parameters does trigger another call
lookup.component('bar', [])
assert myapp.called == 2
|
Update relative path, add ./ :metal: | var gulp = require('gulp');
var browserSync = require('browser-sync');
var sass = require('gulp-sass');
var prefix = require('gulp-autoprefixer');
// Start Static Server with browserSync
gulp.task('server', function() {
browserSync({
server: {
baseDir: "./"
}
});
});
// Watch SCSS files for changes, recompile, compress, autoprefixed
gulp.task('sass', function () {
return gulp.src('./_sass/main.scss')
.pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError))
.pipe(prefix(['last 2 versions'], { cascade: true }))
.pipe(gulp.dest('./assets/css'))
.pipe(browserSync.reload({stream:true}));
});
// Watch SCSS & HTML files, run reload BrowserSync
gulp.task('watch', function () {
gulp.watch('./_sass/*/*.scss', ['sass']);
gulp.watch("./*.html").on('change', browserSync.reload);
});
// Default task, running just `gulp`
gulp.task('default', ['server', 'watch']);
| var gulp = require('gulp');
var browserSync = require('browser-sync');
var sass = require('gulp-sass');
var prefix = require('gulp-autoprefixer');
// Start Static Server with browserSync
gulp.task('browser-sync', ['sass', 'watch'], function() {
browserSync({
server: {
baseDir: "./"
}
});
});
// Watch SCSS files for changes, recompile, compress, autoprefixed
gulp.task('sass', function () {
return gulp.src('_sass/main.scss')
.pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError))
.pipe(prefix(['last 2 versions'], { cascade: true }))
.pipe(gulp.dest('assets/css'))
.pipe(browserSync.reload({stream:true}));
});
// Watch SCSS & HTML files, run reload BrowserSync
gulp.task('watch', function () {
gulp.watch('_sass/*/*.scss', ['sass']);
gulp.watch("*.html").on('change', browserSync.reload);
});
// Default task, running just `gulp`
gulp.task('default', ['browser-sync', 'watch']);
|
Test getting properties as well | var jQuery = require('jquery');
var VIE = require('../vie.js');
// Until https://github.com/tmpvar/jsdom/issues/issue/81 is fixed
VIE.RDFa.predicateSelector = '[property]';
exports['test inheriting subject'] = function(test) {
var html = jQuery('<div about="http://dbpedia.org/resource/Albert_Einstein"><span property="foaf:name">Albert Einstein</span><span property="dbp:dateOfBirth" datatype="xsd:date">1879-03-14</span><div rel="dbp:birthPlace" resource="http://dbpedia.org/resource/Germany" /><span about="http://dbpedia.org/resource/Germany" property="dbp:conventionalLongName">Federal Republic of Germany</span></div>');
var jsonldEntities = VIE.RDFa.readEntities(html);
test.equal(jsonldEntities.length, 2, "This RDFa defines two entities but they don't get parsed to JSON");
test.equal(jsonldEntities[1]['foaf:name'], 'Albert Einstein');
test.equal(jsonldEntities[0]['dbp:conventionalLongName'], 'Federal Republic of Germany');
var backboneEntities = VIE.RDFaEntities.getInstances(html);
test.equal(backboneEntities.length, 2, "This RDFa defines two entities but they don't get to Backbone");
test.equal(backboneEntities[1].get('foaf:name'), 'Albert Einstein');
test.equal(backboneEntities[0].get('dbp:conventionalLongName'), 'Federal Republic of Germany');
test.done();
};
| var jQuery = require('jquery');
var VIE = require('../vie.js');
// Until https://github.com/tmpvar/jsdom/issues/issue/81 is fixed
VIE.RDFa.predicateSelector = '[property]';
exports['test inheriting subject'] = function(test) {
var html = jQuery('<div about="http://dbpedia.org/resource/Albert_Einstein"><span property="foaf:name">Albert Einstein<span><span property="dbp:dateOfBirth" datatype="xsd:date">1879-03-14</span><div rel="dbp:birthPlace" resource="http://dbpedia.org/resource/Germany" /><span about="http://dbpedia.org/resource/Germany" property="dbp:conventionalLongName">Federal Republic of Germany</span></div>');
var entities = VIE.RDFa.readEntities(html);
test.equal(entities.length, 2, "This RDFa defines two entities but they don't get parsed to JSON");
var entities = VIE.RDFaEntities.getInstances(html);
test.equal(entities.length, 2, "This RDFa defines two entities but they don't get to Backbone");
test.done();
};
|
Fix test command, esp. wrt. coverage | from runcommands import command
from runcommands.commands import local as _local
@command
def format_code(check=False):
_local(f"black . {'--check' if check else ''}")
@command
def lint():
_local("flake8 .")
@command
def test(with_coverage=True, check=True):
if with_coverage:
_local(
"coverage run "
"--source src/local_settings "
"-m unittest discover "
"-t . -s tests "
"&& coverage report"
)
else:
_local("python -m unittest discover -t . -s tests")
if check:
format_code(check=True)
lint()
@command
def tox(clean=False):
_local(f"tox {'-r' if clean else ''}")
| from runcommands import command
from runcommands.commands import local as _local
@command
def format_code(check=False):
_local(f"black . {'--check' if check else ''}")
@command
def lint():
_local("flake8 .")
@command
def test(with_coverage=True, check=True):
if with_coverage:
_local(
"coverage run --source local_settings -m unittest discover "
"&& coverage report"
)
else:
_local("python -m unittest discover")
if check:
format_code(check=True)
lint()
@command
def tox(clean=False):
_local(f"tox {'-r' if clean else ''}")
|
Set default taking access for GradingProjectSurvey to org.
This will allow Mentors and Org Admins to take GradingProjectSurveys in case that an Org Admin has no Mentor roles. | #!/usr/bin/python2.5
#
# Copyright 2009 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This module contains the GradingProjectSurvey model.
"""
__authors__ = [
'"Daniel Diniz" <ajaksu@gmail.com>',
'"Lennard de Rijk" <ljvderijk@gmail.com>',
]
from soc.models.project_survey import ProjectSurvey
class GradingProjectSurvey(ProjectSurvey):
"""Survey for Mentors for each of their StudentProjects.
"""
def __init__(self, *args, **kwargs):
super(GradingProjectSurvey, self).__init__(*args, **kwargs)
self.taking_access = 'org'
| #!/usr/bin/python2.5
#
# Copyright 2009 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This module contains the GradingProjectSurvey model.
"""
__authors__ = [
'"Daniel Diniz" <ajaksu@gmail.com>',
'"Lennard de Rijk" <ljvderijk@gmail.com>',
]
from soc.models.project_survey import ProjectSurvey
class GradingProjectSurvey(ProjectSurvey):
"""Survey for Mentors for each of their StudentProjects.
"""
def __init__(self, *args, **kwargs):
super(GradingProjectSurvey, self).__init__(*args, **kwargs)
self.taking_access = 'mentor'
|
Feature: Add Pinry plugin config to local_settings.py | import os
# Please don't change following settings unless you know what you are doing
STATIC_ROOT = '/data/static'
MEDIA_ROOT = os.path.join(STATIC_ROOT, 'media')
# SECURITY WARNING: keep the secret key used in production secret!
# Or just write your own secret-key here instead of using a env-variable
SECRET_KEY = "secret_key_place_holder"
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
TEMPLATE_DEBUG = DEBUG
# SECURITY WARNING: use your actual domain name in production!
ALLOWED_HOSTS = ['*']
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': '/data/production.db',
}
}
# Allow users to register by themselves
ALLOW_NEW_REGISTRATIONS = True
# Delete image files once you remove your pin
IMAGE_AUTO_DELETE = True
# thumbnail size control
IMAGE_SIZES = {
'thumbnail': {'size': [240, 0]},
'standard': {'size': [600, 0]},
'square': {'crop': True, 'size': [125, 125]},
}
# Whether people can view pins without login
PUBLIC = True
ENABLED_PLUGINS = [
'pinry_plugins.batteries.plugin_example.Plugin',
]
| import os
# Please don't change following settings unless you know what you are doing
STATIC_ROOT = '/data/static'
MEDIA_ROOT = os.path.join(STATIC_ROOT, 'media')
# SECURITY WARNING: keep the secret key used in production secret!
# Or just write your own secret-key here instead of using a env-variable
SECRET_KEY = "secret_key_place_holder"
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
TEMPLATE_DEBUG = DEBUG
# SECURITY WARNING: use your actual domain name in production!
ALLOWED_HOSTS = ['*']
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': '/data/production.db',
}
}
# Allow users to register by themselves
ALLOW_NEW_REGISTRATIONS = True
# Delete image files once you remove your pin
IMAGE_AUTO_DELETE = True
# thumbnail size control
IMAGE_SIZES = {
'thumbnail': {'size': [240, 0]},
'standard': {'size': [600, 0]},
'square': {'crop': True, 'size': [125, 125]},
}
# Whether people can view pins without login
PUBLIC = True
|
Add FileSender to top level | # This relies on each of the submodules having an __all__ variable.
__version__ = '0.22.0a0'
import multidict # noqa
from multidict import * # noqa
from . import hdrs # noqa
from .protocol import * # noqa
from .connector import * # noqa
from .client import * # noqa
from .client_reqrep import * # noqa
from .errors import * # noqa
from .helpers import * # noqa
from .parsers import * # noqa
from .streams import * # noqa
from .multipart import * # noqa
from .websocket_client import * # noqa
from .file_sender import FileSender # noqa
__all__ = (client.__all__ + # noqa
client_reqrep.__all__ + # noqa
errors.__all__ + # noqa
helpers.__all__ + # noqa
parsers.__all__ + # noqa
protocol.__all__ + # noqa
connector.__all__ + # noqa
streams.__all__ + # noqa
multidict.__all__ + # noqa
multipart.__all__ + # noqa
websocket_client.__all__ + # noqa
('hdrs', '__version__', 'FileSender'))
| # This relies on each of the submodules having an __all__ variable.
__version__ = '0.22.0a0'
import multidict # noqa
from multidict import * # noqa
from . import hdrs # noqa
from .protocol import * # noqa
from .connector import * # noqa
from .client import * # noqa
from .client_reqrep import * # noqa
from .errors import * # noqa
from .helpers import * # noqa
from .parsers import * # noqa
from .streams import * # noqa
from .multipart import * # noqa
from .websocket_client import * # noqa
__all__ = (client.__all__ + # noqa
client_reqrep.__all__ + # noqa
errors.__all__ + # noqa
helpers.__all__ + # noqa
parsers.__all__ + # noqa
protocol.__all__ + # noqa
connector.__all__ + # noqa
streams.__all__ + # noqa
multidict.__all__ + # noqa
multipart.__all__ + # noqa
websocket_client.__all__ + # noqa
('hdrs', '__version__'))
|
Fix collaborators field of placeholderObj to be an array. | import React from 'react';
import SaveTripModal from './save-trip-modal.js'
/**
* Component corresponding to add trips modal.
*
* @param {Object} props These are the props for this component:
* - db: Firestore database instance.
* - show: Boolean that determines if the add trips modal should be displayed.
* - handleClose: The function that handles closing the add trips modal.
* - refreshTripsContainer: Function that handles refreshing the TripsContainer
* component upon trip creation (Remove when fix Issue #62).
* - key: Special React attribute that ensures a new AddTripModal instance is
* created whenever this key is updated
*
* @extends React.Component
*/
const AddTripModal = (props) => {
const placeholderObj =
{
name: 'Enter Trip Name',
description: 'Enter Trip Description',
destination: 'Enter Trip Destination',
startDate: '',
endDate: '',
collaborators: ['person@email.xyz']
};
return (
<SaveTripModal
db={props.db}
show={props.show}
handleClose={props.handleClose}
refreshTripsContainer={props.refreshTripsContainer}
key={props.key}
placeholderObj={placeholderObj}
/>
);
};
export default AddTripModal;
| import React from 'react';
import SaveTripModal from './save-trip-modal.js'
/**
* Component corresponding to add trips modal.
*
* @param {Object} props These are the props for this component:
* - db: Firestore database instance.
* - show: Boolean that determines if the add trips modal should be displayed.
* - handleClose: The function that handles closing the add trips modal.
* - refreshTripsContainer: Function that handles refreshing the TripsContainer
* component upon trip creation (Remove when fix Issue #62).
* - key: Special React attribute that ensures a new AddTripModal instance is
* created whenever this key is updated
*
* @extends React.Component
*/
const AddTripModal = (props) => {
const placeholderObj =
{
name: 'Enter Trip Name',
description: 'Enter Trip Description',
destination: 'Enter Trip Destination',
startDate: '',
endDate: '',
collaborators: 'person@email.xyz'
};
return (
<SaveTripModal
db={props.db}
show={props.show}
handleClose={props.handleClose}
refreshTripsContainer={props.refreshTripsContainer}
key={props.key}
placeholderObj={placeholderObj}
/>
);
};
export default AddTripModal;
|
Use morphable command to create polymorphic columns on events table | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateNewEventsTableSchema extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('events', function (Blueprint $table) {
$table->increments('id');
$table->morphs('eventable');
$table->string('content');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('events');
}
}
| <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateNewEventsTableSchema extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('events', function (Blueprint $table) {
$table->increments('id');
$table->integer('eventable_id');
$table->string('eventable_type');
$table->string('content');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('events');
}
}
|
[Backend][Model] Add date to CrashLog model | /*
* Author: Alexandre Havrileck (Oxyno-zeta)
* Date: 08/07/16
* Licence: See Readme
*/
/* ************************************* */
/* ******** REQUIRE ******** */
/* ************************************* */
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const crashLogSchema = new Schema({
ver: String,
platform: String,
process_type: String,
guid: String,
_version: String,
_productName: String,
prod: String,
_companyName: String,
upload_file_minidump: String,
extra: {},
project: Schema.Types.ObjectId,
date: { type: Date, default: Date.now }
});
const CrashLog = mongoose.model('CrashLog', crashLogSchema);
/* ************************************* */
/* ******** EXPORTS ******** */
/* ************************************* */
module.exports = {
CrashLog: CrashLog
};
/* ************************************* */
/* ******** PRIVATE FUNCTIONS ******** */
/* ************************************* */
/* ************************************* */
/* ******** PUBLIC FUNCTIONS ******** */
/* ************************************* */
| /*
* Author: Alexandre Havrileck (Oxyno-zeta)
* Date: 08/07/16
* Licence: See Readme
*/
/* ************************************* */
/* ******** REQUIRE ******** */
/* ************************************* */
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const crashLogSchema = new Schema({
ver: String,
platform: String,
process_type: String,
guid: String,
_version: String,
_productName: String,
prod: String,
_companyName: String,
upload_file_minidump: String,
extra: {},
project: Schema.Types.ObjectId
});
const CrashLog = mongoose.model('CrashLog', crashLogSchema);
/* ************************************* */
/* ******** EXPORTS ******** */
/* ************************************* */
module.exports = {
CrashLog: CrashLog
};
/* ************************************* */
/* ******** PRIVATE FUNCTIONS ******** */
/* ************************************* */
/* ************************************* */
/* ******** PUBLIC FUNCTIONS ******** */
/* ************************************* */
|
Fix service error filter tests due to error message refactoring | package io.spacedog.test;
import org.junit.Test;
import io.spacedog.client.SpaceDog;
import io.spacedog.client.http.SpaceRequest;
public class ServiceErrorFilterTest extends SpaceTest {
@Test
public void catchesFluentResourceErrors() {
prepareTest();
SpaceDog superadmin = clearServer();
// should fail to access invalid route
SpaceRequest.get("/1/toto")//
.backend(superadmin.backend())//
.go(404)//
.assertEquals("[path][/1/toto] not found", "error.message");
// should fail to use this method for this valid route
superadmin.put("/1/login").go(405)//
.assertEquals("[PUT][/1/login] is not supported", "error.message");
}
@Test
public void notifySuperdogsForInternalServerErrors() {
// prepare
prepareTest();
// this fails and send notification to superdogs with error details
SpaceRequest.post("/1/admin/_return_500").go(500);
}
}
| package io.spacedog.test;
import org.junit.Test;
import io.spacedog.client.SpaceDog;
import io.spacedog.client.http.SpaceRequest;
public class ServiceErrorFilterTest extends SpaceTest {
@Test
public void catchesFluentResourceErrors() {
prepareTest();
SpaceDog superadmin = clearServer();
// should fail to access invalid route
SpaceRequest.get("/1/toto")//
.backend(superadmin.backend())//
.go(404)//
.assertEquals("path [/1/toto] invalid", "error.message");
// should fail to use this method for this valid route
superadmin.put("/1/login").go(405)//
.assertEquals("method [PUT] invalid for path [/1/login]", "error.message");
}
@Test
public void notifySuperdogsForInternalServerErrors() {
// prepare
prepareTest();
// this fails and send notification to superdogs with error details
SpaceRequest.post("/1/admin/_return_500").go(500);
}
}
|
Allow the editor to load on slow computers and connections
# Require.js will abandon loading any module that takes more than 7 seconds
# to load. For editors with slow connections and computers, this limit may
# be reached. Since this isn't a production app, long load times are ok! | require.config({
baseUrl: 'js/lib',
waitSeconds : 0,
paths: {
"app": '../app',
"jquery": '../../bower_components/jquery/dist/jquery',
"foundation": '../../bower_components/foundation/js/foundation',
"angular": '../../bower_components/angular/angular',
"angular-route": '../../bower_components/angular-route/angular-route',
"react": '../../bower_components/react/react-with-addons',
"JSXTransformer": '../../bower_components/react/JSXTransformer',
"angulartics": '../../bower_components/angulartics/src/angulartics',
"angulartics-ga": '../../bower_components/angulartics/src/angulartics-ga',
"mathjax": 'https://cdn.isaacphysics.org/vendor/mathjax/2.7.5/MathJax.js?delayStartupUntil=configured',
},
shim: {
"foundation": ['jquery'],
"angular-route": ['angular'],
"angular": ['jquery'],
"angulartics-ga": ["angulartics"],
"angulartics": ["angular"],
"showdown/extensions/table": ["showdown/showdown"],
}
});
var app = {}
require(["app/app"]); | require.config({
baseUrl: 'js/lib',
paths: {
"app": '../app',
"jquery": '../../bower_components/jquery/dist/jquery',
"foundation": '../../bower_components/foundation/js/foundation',
"angular": '../../bower_components/angular/angular',
"angular-route": '../../bower_components/angular-route/angular-route',
"react": '../../bower_components/react/react-with-addons',
"JSXTransformer": '../../bower_components/react/JSXTransformer',
"angulartics": '../../bower_components/angulartics/src/angulartics',
"angulartics-ga": '../../bower_components/angulartics/src/angulartics-ga',
"mathjax": 'https://cdn.isaacphysics.org/vendor/mathjax/2.7.5/MathJax.js?delayStartupUntil=configured',
},
shim: {
"foundation": ['jquery'],
"angular-route": ['angular'],
"angular": ['jquery'],
"angulartics-ga": ["angulartics"],
"angulartics": ["angular"],
"showdown/extensions/table": ["showdown/showdown"],
}
});
var app = {}
require(["app/app"]); |
Exclude a few more locations | module.exports = {
verbose: true,
testPathIgnorePatterns: [
'<rootDir>/node_modules/',
'<rootDir>/public/',
'<rootDir>/extensions/',
],
testMatch: ['<rootDir>/src/**/*.test.js'],
//
collectCoverage: false,
collectCoverageFrom: [
'**/*.{js,jsx}',
'!**/node_modules/**',
'!<rootDir>/public/**',
'!<rootDir>/extensions/**',
'!<rootDir>/dist/**',
],
reporters: ['default', 'jest-junit'],
//
moduleNameMapper: {
'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
'<rootDir>/src/__mocks__/fileMock.js',
'\\.(css|less)$': 'identity-obj-proxy',
},
setupFiles: ['<rootDir>/node_modules/jest-canvas-mock/lib/index.js'],
setupTestFrameworkScriptFile: '<rootDir>/src/__tests__/globalSetup.js',
}
| module.exports = {
verbose: true,
testPathIgnorePatterns: ['<rootDir>/node_modules/', '<rootDir>/extensions/'],
testMatch: ['<rootDir>/src/**/*.test.js'],
//
collectCoverage: false,
collectCoverageFrom: [
'**/*.{js,jsx}',
'!**/node_modules/**',
'!<rootDir>/dist/**',
],
reporters: ['default', 'jest-junit'],
//
moduleNameMapper: {
'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
'<rootDir>/src/__mocks__/fileMock.js',
'\\.(css|less)$': 'identity-obj-proxy',
},
setupFiles: ['<rootDir>/node_modules/jest-canvas-mock/lib/index.js'],
setupTestFrameworkScriptFile: '<rootDir>/src/__tests__/globalSetup.js',
}
|
Add 100% coverage for response.php
While already at https://github.com/nextcloud/server/pull/2911 I thought I can as well finish that one as well...
Signed-off-by: Lukas Reschke <65adda4326914576405c9e3a62f4904d96573863@statuscode.ch> | <?php
/**
* Copyright (c) 2015 Lukas Reschke <lukas@owncloud.com>
* This file is licensed under the Affero General Public License version 3 or
* later.
* See the COPYING-README file.
*/
namespace Test\Http\Client;
use GuzzleHttp\Stream\Stream;
use GuzzleHttp\Message\Response as GuzzleResponse;
use OC\Http\Client\Response;
/**
* Class ResponseTest
*/
class ResponseTest extends \Test\TestCase {
/** @var Response */
private $response;
/** @var GuzzleResponse */
private $guzzleResponse;
public function setUp() {
parent::setUp();
$this->guzzleResponse = new GuzzleResponse(1337);
$this->response = new Response($this->guzzleResponse);
}
public function testGetBody() {
$this->guzzleResponse->setBody(Stream::factory('MyResponse'));
$this->assertSame('MyResponse', $this->response->getBody());
}
public function testGetStatusCode() {
$this->assertSame(1337, $this->response->getStatusCode());
}
public function testGetHeader() {
$this->guzzleResponse->setHeader('bar', 'foo');
$this->assertSame('foo', $this->response->getHeader('bar'));
}
public function testGetHeaders() {
$this->guzzleResponse->setHeader('bar', 'foo');
$this->guzzleResponse->setHeader('x-awesome', 'yes');
$expected = [
'bar' => [
0 => 'foo',
],
'x-awesome' => [
0 => 'yes',
],
];
$this->assertSame($expected, $this->response->getHeaders());
$this->assertSame('yes', $this->response->getHeader('x-awesome'));
}
}
| <?php
/**
* Copyright (c) 2015 Lukas Reschke <lukas@owncloud.com>
* This file is licensed under the Affero General Public License version 3 or
* later.
* See the COPYING-README file.
*/
namespace Test\Http\Client;
use Guzzle\Stream\Stream;
use GuzzleHttp\Message\Response as GuzzleResponse;
use OC\Http\Client\Response;
/**
* Class ResponseTest
*/
class ResponseTest extends \Test\TestCase {
/** @var Response */
private $response;
/** @var GuzzleResponse */
private $guzzleResponse;
public function setUp() {
parent::setUp();
$this->guzzleResponse = new GuzzleResponse(1337);
$this->response = new Response($this->guzzleResponse);
}
public function testGetStatusCode() {
$this->assertEquals(1337, $this->response->getStatusCode());
}
public function testGetHeader() {
$this->guzzleResponse->setHeader('bar', 'foo');
$this->assertEquals('foo', $this->response->getHeader('bar'));
}
}
|
Add point to execute program | import json
import re
import requests
import socket
import settings
def get_responsible_user(full_url):
members = settings.TEAM_MEMBERS
response = requests.get(
full_url,
auth=(
settings.JENKINS_USERNAME,
settings.JENKINS_PASSWORD
)
)
for each in members:
if ('Started by GitHub push by ' + each in response.content or \
'Started by user ' + each in response.content):
return each
def wait_for_event():
return True
def jenkins_wait_for_event():
sock = socket.socket(settings.AF_INET, settings.SOCK_DGRAM)
sock.bind(('', settings.JENKINS_NOTIFICATION_UDP_PORT))
while wait_for_event():
data, _ = sock.recvfrom(8 * 1024)
notification_data = json.loads(data)
status = notification_data['build']['status'].upper()
phase = notification_data['build']['phase'].upper()
if phase == 'COMPLETED' and status.startswith('FAIL'):
target = get_responsible_user(
notification_data['build']['full_url']
)
if __name__ == '__main__':
jenkins_wait_for_event()
| import json
import re
import requests
import socket
import settings
def get_responsible_user(full_url):
members = settings.TEAM_MEMBERS
response = requests.get(
full_url,
auth=(
settings.JENKINS_USERNAME,
settings.JENKINS_PASSWORD
)
)
for each in members:
if ('Started by GitHub push by ' + each in response.content or \
'Started by user ' + each in response.content):
return each
def wait_for_event():
return True
def jenkins_wait_for_event():
sock = socket.socket(settings.AF_INET, settings.SOCK_DGRAM)
sock.bind(('', settings.JENKINS_NOTIFICATION_UDP_PORT))
while wait_for_event():
data, _ = sock.recvfrom(8 * 1024)
notification_data = json.loads(data)
status = notification_data['build']['status'].upper()
phase = notification_data['build']['phase'].upper()
if phase == 'COMPLETED' and status.startswith('FAIL'):
target = get_responsible_user(
notification_data['build']['full_url']
)
|
Fix the issue that volume page breaks | import Mixin from '@ember/object/mixin';
import { get, set, computed } from '@ember/object';
export default Mixin.create({
// Inputs from component caller
volume: null,
editing: null,
sourceStore: null, // set to clusterStore for cluster volumes
// From the volume plugin
field: null, // the name of the field on the volume
config: computed('field', function() {
const volume = get(this, 'volume');
const field = get(this, 'field');
let config = get(volume, field);
if ( !config ) {
config = this.configForNew();
set(volume, field, config);
}
return config;
}),
configForNew() {
// Override to provide a custom empty config
const store = get(this, 'sourceStore') || get(this, 'store');
const index = get(this, 'volume.type').lastIndexOf('/') + 1
const voluemType = get(this, 'volume.type').substr(index).toLowerCase();
const volumeSchema = store.getById('schema', voluemType);
const type = get(volumeSchema, `resourceFields.${ get(this, 'field') }.type`).toLowerCase();
const config = store.createRecord({ type });
const schema = store.getById('schema', type);
if ( schema && schema.typeifyFields ) {
if ( (schema.typeifyFields || []).indexOf('secretRef') > -1 ) {
get(config, 'secretRef') || set(config, 'secretRef', {});
}
}
return config;
},
});
| import Mixin from '@ember/object/mixin';
import { get, set, computed } from '@ember/object';
export default Mixin.create({
// Inputs from component caller
volume: null,
editing: null,
sourceStore: null, // set to clusterStore for cluster volumes
// From the volume plugin
field: null, // the name of the field on the volume
config: computed('field', function() {
const volume = get(this, 'volume');
const field = get(this, 'field');
let config = get(volume, field);
if ( !config ) {
config = this.configForNew();
set(volume, field, config);
}
return config;
}),
configForNew() {
// Override to provide a custom empty config
const store = get(this, 'sourceStore') || get(this, 'store');
const index = get(this, 'volume.type').lastIndexOf('/') + 1
const voluemType = get(this, 'volume.type').substr(index);
const volumeSchema = store.getById('schema', voluemType);
const type = get(volumeSchema, `resourceFields.${ get(this, 'field') }.type`);
const config = store.createRecord({ type });
const schema = store.getById('schema', type.toLowerCase());
if ( schema && schema.typeifyFields ) {
if ( (schema.typeifyFields || []).indexOf('secretRef') > -1 ) {
get(config, 'secretRef') || set(config, 'secretRef', {});
}
}
return config;
},
});
|
[Android] Refactor buildbot tests so that they can be used downstream.
I refactored in the wrong way in r211209 (https://chromiumcodereview.appspot.com/18325030/). This CL fixes that. Note that r211209 is not broken; it is just not usable downstream.
BUG=249997
NOTRY=True
Review URL: https://chromiumcodereview.appspot.com/18202005
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@211454 0039d316-1c4b-4281-b951-d872f2087c98 | #!/usr/bin/env python
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import subprocess
import sys
BUILDBOT_DIR = os.path.join(os.path.dirname(__file__), '..')
sys.path.append(BUILDBOT_DIR)
import bb_run_bot
def RunBotProcesses(bot_process_map):
code = 0
for bot, proc in bot_process_map:
_, err = proc.communicate()
code |= proc.returncode
if proc.returncode != 0:
print 'Error running the bot script with id="%s"' % bot, err
return code
def main():
procs = [
(bot, subprocess.Popen(
[os.path.join(BUILDBOT_DIR, 'bb_run_bot.py'), '--bot-id', bot,
'--testing'], stdout=subprocess.PIPE, stderr=subprocess.PIPE))
for bot in bb_run_bot.GetBotStepMap()]
return RunBotProcesses(procs)
if __name__ == '__main__':
sys.exit(main())
| #!/usr/bin/env python
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import subprocess
import sys
BUILDBOT_DIR = os.path.join(os.path.dirname(__file__), '..')
sys.path.append(BUILDBOT_DIR)
import bb_run_bot
def RunBotsWithTesting(bot_step_map):
code = 0
procs = [
(bot, subprocess.Popen(
[os.path.join(BUILDBOT_DIR, 'bb_run_bot.py'), '--bot-id', bot,
'--testing'], stdout=subprocess.PIPE, stderr=subprocess.PIPE))
for bot in bot_step_map]
for bot, proc in procs:
_, err = proc.communicate()
code |= proc.returncode
if proc.returncode != 0:
print 'Error running bb_run_bot with id="%s"' % bot, err
return code
def main():
return RunBotsWithTesting(bb_run_bot.GetBotStepMap())
if __name__ == '__main__':
sys.exit(main())
|
FIX numerical issues in test on travis-ci | import unittest
from autosklearn.pipeline.components.regression.liblinear_svr import \
LibLinear_SVR
from autosklearn.pipeline.util import _test_regressor
import sklearn.metrics
class SupportVectorComponentTest(unittest.TestCase):
def test_default_configuration(self):
for i in range(10):
predictions, targets = _test_regressor(LibLinear_SVR,
dataset='boston')
# Lenient test because of travis-ci which gets quite different
# results here!
self.assertAlmostEqual(0.68,
sklearn.metrics.r2_score(y_true=targets,
y_pred=predictions),
places=2)
| import unittest
from autosklearn.pipeline.components.regression.liblinear_svr import \
LibLinear_SVR
from autosklearn.pipeline.util import _test_regressor
import sklearn.metrics
class SupportVectorComponentTest(unittest.TestCase):
def test_default_configuration(self):
for i in range(10):
predictions, targets = _test_regressor(LibLinear_SVR,
dataset='boston')
self.assertAlmostEqual(0.67714499792824023,
sklearn.metrics.r2_score(y_true=targets,
y_pred=predictions))
|
Debug test classes after refactoring | <?php
namespace Wilson\tests;
use Wilson\Ranking;
use PHPUnit_Framework_TestCase;
class RankingTest extends PHPUnit_Framework_TestCase
{
/**
*test that rank() method in Ranking class returns an array
* @return array
*/
public function testRank()
{
$sampleSentence = "The house is really really beautiful.";
$expectedArray = ["really"=>2, "beautiful"=>1, "is"=>1, "house"=>1, "The"=>1];
$this->assertInternalType('array', Ranking::rank($sampleSentence));
$this->assertEquals($expectedArray, Ranking::rank($sampleSentence));
}
/**
* test that countOccurrence() method in ranking class returns the correct type and value
* @return integer
*/
public function testCountOccurrence()
{
$sampleArray = ["one", "two", "three", "three"];
$this->assertInternalType('integer', Ranking::countOccurrence($sampleArray, "three"));
$this->assertEquals(2, Ranking::countOccurrence($sampleArray, "three"));
}
} | <?php
namespace Wilson\tests;
use Wilson\Ranking;
use PHPUnit_Framework_TestCase;
class RankingTest extends PHPUnit_Framework_TestCase
{
/**
*test that rank() method in Ranking class returns an array
* @return array
*/
public function testRank()
{
$this->assertInternalType('array', Ranking::rank("a test string"));
}
/**
* test that countOccurrence() method in ranking class returns the correct type and value
* @return integer
*/
// public function testCountOccurrence()
// {
// $sampleArray = ["one", "two", "three", "three"];
// $this->assertInternalType('integer', Ranking::countOccurrence($sampleArray, "three"));
// $this->assertEquals(2, Ranking::countOccurrence($sampleArray, "three"));
// }
} |
Add example of date type in Python | # Many built-in types have built-in names
assert(type(5) == int)
assert(type(True) == bool)
assert(type(5.7) == float)
assert(type(9 + 5j) == complex)
assert(type((8, 'dog', False)) == tuple)
assert(type('hello') == str)
assert(type(b'hello') == bytes)
assert(type([1, '', False]) == list)
assert(type(range(1,10)) == range)
assert(type({1, 2, 3}) == set)
assert(type(frozenset([1, 2, 3])) == frozenset)
assert(type({'x': 1, 'y': 2}) == dict)
assert(type(slice([1, 2, 3])) == slice)
# Some do not, but we can still "see" them
assert(str(type(None)) == "<class 'NoneType'>")
assert(str(type(NotImplemented)) == "<class 'NotImplementedType'>")
# Built-in vs. User-defined functions
def plus_two(x):
return x + 2
assert(str(type(plus_two)) == "<class 'function'>")
assert(str(type(max)) == "<class 'builtin_function_or_method'>")
# Even modules are types!
import math
assert(str(type(math)) == "<class 'module'>")
# Many built-in modules define their own types
from datetime import date
assert(type(date(1969,7,20)) == date) | # Many built-in types have built-in names
assert(type(5) == int)
assert(type(True) == bool)
assert(type(5.7) == float)
assert(type(9 + 5j) == complex)
assert(type((8, 'dog', False)) == tuple)
assert(type('hello') == str)
assert(type(b'hello') == bytes)
assert(type([1, '', False]) == list)
assert(type(range(1,10)) == range)
assert(type({1, 2, 3}) == set)
assert(type(frozenset([1, 2, 3])) == frozenset)
assert(type({'x': 1, 'y': 2}) == dict)
assert(type(slice([1, 2, 3])) == slice)
# Some do not, but we can still "see" them
assert(str(type(None)) == "<class 'NoneType'>")
assert(str(type(NotImplemented)) == "<class 'NotImplementedType'>")
# Built-in vs. User-defined functions
def plus_two(x):
return x + 2
assert(str(type(plus_two)) == "<class 'function'>")
assert(str(type(max)) == "<class 'builtin_function_or_method'>")
# Even modules are types!
import math
assert(str(type(math)) == "<class 'module'>")
|
feat(logger): Add date/time stamp to log output
The `"%d{DATE}"` in the log pattern adds a date and time stamp to log
lines.
So you get output like this from karma's logging:
```
30 06 2015 15:19:56.562:DEBUG [temp-dir]: Creating temp dir at /tmp/karma-43808925
```
The date and time are handy for figuring out if karma is running slowly. | var fs = require('fs')
var pkg = JSON.parse(fs.readFileSync(__dirname + '/../package.json').toString())
exports.VERSION = pkg.version
exports.DEFAULT_PORT = process.env.PORT || 9876
exports.DEFAULT_HOSTNAME = process.env.IP || 'localhost'
// log levels
exports.LOG_DISABLE = 'OFF'
exports.LOG_ERROR = 'ERROR'
exports.LOG_WARN = 'WARN'
exports.LOG_INFO = 'INFO'
exports.LOG_DEBUG = 'DEBUG'
// Default patterns for the pattern layout.
exports.COLOR_PATTERN = '%[%d{DATE}:%p [%c]: %]%m'
exports.NO_COLOR_PATTERN = '%d{DATE}:%p [%c]: %m'
// Default console appender
exports.CONSOLE_APPENDER = {
type: 'console',
layout: {
type: 'pattern',
pattern: exports.COLOR_PATTERN
}
}
exports.EXIT_CODE = '\x1FEXIT'
| var fs = require('fs')
var pkg = JSON.parse(fs.readFileSync(__dirname + '/../package.json').toString())
exports.VERSION = pkg.version
exports.DEFAULT_PORT = process.env.PORT || 9876
exports.DEFAULT_HOSTNAME = process.env.IP || 'localhost'
// log levels
exports.LOG_DISABLE = 'OFF'
exports.LOG_ERROR = 'ERROR'
exports.LOG_WARN = 'WARN'
exports.LOG_INFO = 'INFO'
exports.LOG_DEBUG = 'DEBUG'
// Default patterns for the pattern layout.
exports.COLOR_PATTERN = '%[%p [%c]: %]%m'
exports.NO_COLOR_PATTERN = '%p [%c]: %m'
// Default console appender
exports.CONSOLE_APPENDER = {
type: 'console',
layout: {
type: 'pattern',
pattern: exports.COLOR_PATTERN
}
}
exports.EXIT_CODE = '\x1FEXIT'
|
Remove the Customize icon from the customizer.php view. Redundant. | <?php
function shoestrap_footer_css() {
$bg = get_theme_mod( 'footer_bg' );
$cl = get_theme_mod( 'footer_color' );
echo '<style>';
echo 'footer.content-info{background:' . $bg . '; color:' . $cl . ';}';
echo '</style>';
}
add_action( 'wp_head', 'shoestrap_footer_css' );
/*
* Creates the customizer icon on the bottom-left corner of our site
* (visible only by admins)
*/
function footer_icon() {
global $wp_customize;
?>
<?php if (current_user_can( 'edit_theme_options' ) && !isset( $wp_customize ) ){ ?>
<style>
</style>
<div id="shoestrap_icon">
<?php
$current_url = ( is_ssl() ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$href = add_query_arg( 'url', urlencode( $current_url ), wp_customize_url() ); ?>
<a href="<?php echo $href; ?>"><i class="glyphicon glyphicon-cogs"></i></a>
</div>
<?php } ?>
</div>
<?php }
add_action( 'shoestrap_after_footer', 'footer_icon' );
| <?php
function shoestrap_footer_css() {
$bg = get_theme_mod( 'footer_bg' );
$cl = get_theme_mod( 'footer_color' );
echo '<style>';
echo 'footer.content-info{background:' . $bg . '; color:' . $cl . ';}';
echo '</style>';
}
add_action( 'wp_head', 'shoestrap_footer_css' );
/*
* Creates the customizer icon on the bottom-left corner of our site
* (visible only by admins)
*/
function footer_icon() { ?>
<?php if (current_user_can( 'edit_theme_options' )){ ?>
<style>
</style>
<div id="shoestrap_icon">
<?php
$current_url = ( is_ssl() ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$href = add_query_arg( 'url', urlencode( $current_url ), wp_customize_url() ); ?>
<a href="<?php echo $href; ?>"><i class="glyphicon glyphicon-cogs"></i></a>
</div>
<?php } ?>
</div>
<?php }
add_action( 'shoestrap_after_footer', 'footer_icon' );
|
Fix bug in date format | <?php
namespace App\View;
class Helper extends \PHPixie\View\Helper
{
public function has_active_page(\PHPixie\Request $request, $controller, $action = null, $append = false)
{
$controllerName = $request->param('controller');
$actionName = $request->param('action');
if (($controller == $controllerName && empty($action)) ||
($controller == $controllerName && $action == $actionName)
) {
echo(!$append ? 'class="active"' : 'active');
}
}
public function has_smstools_var($name)
{
$config = $this->pixie->config->get('smstools3.config');
return (isset($config[$name]) && !empty($config[$name]));
}
public function date_format($timestamp, $format = 'd-m-Y H:i:s')
{
return (date($format, $timestamp));
}
} | <?php
namespace App\View;
class Helper extends \PHPixie\View\Helper
{
public function has_active_page(\PHPixie\Request $request, $controller, $action = null, $append = false)
{
$controllerName = $request->param('controller');
$actionName = $request->param('action');
if (($controller == $controllerName && empty($action)) ||
($controller == $controllerName && $action == $actionName)
) {
echo(!$append ? 'class="active"' : 'active');
}
}
public function has_smstools_var($name)
{
$config = $this->pixie->config->get('smstools3.config');
return (isset($config[$name]) && !empty($config[$name]));
}
public function date_format($timestamp, $format = 'd-m-Y H:m:i')
{
return (date($format, $timestamp));
}
} |
Set the hmac.update encoding to utf-8 to support UTF-8 chars | 'use strict';
var crypto = require('crypto');
var _ = require("underscore");
var signature = function(xhub, options){
this.xhub = xhub;
options = options || {};
this.algorithm = options.algorithm || 'sha1';
this.secret = options.secret;
};
_.extend(signature.prototype, {
attach: function(req, buffer){
var isValid = _.bind(this.isValid, this);
req.isXHubValid = function(){
return isValid(buffer);
};
},
isValid: function(buffer){
if(!this.secret) { throw new Error('No Secret Found'); }
var hmac = crypto.createHmac(this.algorithm, this.secret);
hmac.update(buffer, 'utf-8');
var expected = this.algorithm + '=' + hmac.digest('hex');
return this.xhub === expected;
}
});
module.exports = signature;
| 'use strict';
var crypto = require('crypto');
var _ = require("underscore");
var signature = function(xhub, options){
this.xhub = xhub;
options = options || {};
this.algorithm = options.algorithm || 'sha1';
this.secret = options.secret;
};
_.extend(signature.prototype, {
attach: function(req, buffer){
var isValid = _.bind(this.isValid, this);
req.isXHubValid = function(){
return isValid(buffer);
};
},
isValid: function(buffer){
if(!this.secret) { throw new Error('No Secret Found'); }
var hmac = crypto.createHmac(this.algorithm, this.secret);
hmac.update(buffer);
var expected = this.algorithm + '=' + hmac.digest('hex');
return this.xhub === expected;
}
});
module.exports = signature;
|
Update script to use Lo-Dash | // Thank you Rob Dodson
'use strict';
var path = require('path')
, request = require('request')
, fs = require('fs')
, _ = require('lodash');
module.exports = function(grunt) {
grunt.registerMultiTask('toHTML', 'Render Express routes to flat HTML files', function() {
var done = this.async()
, routes = _.keys(this.data)
, taskData = this.data
, total = routes.length
, counter = 0;
routes.forEach(function(route) {
var dest = taskData[route];
request('http://localhost:3000' + route, function(err, res, body) {
if (!err && res.statusCode == 200) {
grunt.file.mkdir(path.dirname(dest));
fs.writeFileSync(dest, body);
counter += 1; // hack, replace with promises
if (counter === total) {
done(true);
}
} else {
done(false);
}
});
});
});
};
| // Thank you Rob Dodson
'use strict';
var path = require('path')
, request = require('request')
, fs = require('fs')
, _ = require('underscore');
module.exports = function(grunt) {
grunt.registerMultiTask('toHTML', 'Render Express routes to flat HTML files', function() {
var done = this.async()
, routes = _.keys(this.data)
, taskData = this.data
, total = routes.length
, counter = 0;
routes.forEach(function(route) {
var dest = taskData[route];
request('http://localhost:3000' + route, function(err, res, body) {
if (!err && res.statusCode == 200) {
grunt.file.mkdir(path.dirname(dest));
fs.writeFileSync(dest, body);
counter += 1; // hack, replace with promises
if (counter === total) {
done(true);
}
} else {
done(false);
}
});
});
});
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.