text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Check for view function in objects. | var solarflare = function (rays) {
var $element = document.createElement('div');
if (Array.isArray(rays)) {
rays.forEach(function (e, i) {
if (i === 0 && typeof e === 'string') {
if (e.length > 0) {
$element = document.createElement(e);
}
return;
}
if (typeof e === 'string') {
$element.innerHTML += e;
}
if (e.nodeType) {
$element.appendChild(e);
}
if (typeof e === 'object') {
if (Array.isArray(e)) {
$element.appendChild(solarflare(e));
} else if (e.view && typeof e.view === 'function') {
$element.appendChild(e.view());
} else {
Object.keys(e).filter(function (key) {
$element.setAttribute(key, e[key]);
});
}
}
});
}
return $element;
};
module.exports = solarflare;
| var solarflare = function (rays) {
var $element = document.createElement('div');
if (Array.isArray(rays)) {
rays.forEach(function (e, i) {
if (i === 0 && typeof e === 'string') {
if (e.length > 0) {
$element = document.createElement(e);
}
return;
}
if (typeof e === 'string') {
$element.innerHTML += e;
}
if (e.nodeType) {
$element.appendChild(e);
}
if (typeof e === 'object') {
if (Array.isArray(e)) {
$element.appendChild(solarflare(e));
} else {
Object.keys(e).filter(function (key) {
$element.setAttribute(key, e[key]);
});
}
}
});
}
return $element;
};
module.exports = solarflare;
|
Check if token is an error | const Boom = require('boom');
const bookshelf = require('../lib/bookshelf');
exports.register = function (server, pluginOptions, next) {
server.auth.scheme('email_token', (server, schemeOptions) => {
return {
async authenticate(request, reply) {
try {
var token = await schemeOptions.findToken(request.query.token);
if (token.name === 'TypeError') {
reply(Boom.forbidden())
}
var user = token ? await schemeOptions.findUser(token.get('user_id')) : null;
} catch(e) {
reply(e);
}
if (token && user) {
reply.continue({
credentials: {
user,
token,
}
});
} else {
reply(Boom.forbidden());
}
}
};
});
next();
};
exports.register.attributes = {
name: 'email-token-scheme',
version: '1.0.0'
};
| const Boom = require('boom');
const bookshelf = require('../lib/bookshelf');
exports.register = function (server, pluginOptions, next) {
server.auth.scheme('email_token', (server, schemeOptions) => {
return {
async authenticate(request, reply) {
try {
var token = await schemeOptions.findToken(request.query.token);
var user = token ? await schemeOptions.findUser(token.get('user_id')) : null;
} catch(e) {
reply(e);
}
if (token && user) {
reply.continue({
credentials: {
user,
token,
}
});
} else {
reply(Boom.forbidden());
}
}
};
});
next();
};
exports.register.attributes = {
name: 'email-token-scheme',
version: '1.0.0'
};
|
Write set values to log file | var express = require('express'),
Memcached = require('memcached'),
fs = require('fs');
// Constants
var port = 3000;
var env = process.env.NODE_ENV || 'production';
var mc = new Memcached(process.env.MC_PORT.replace('tcp://', ''));
// App
var app = express();
app.use(express.urlencoded());
app.get('/', function (req, res) {
res.send('Hello World!!\n');
});
app.post('/test', function (req, res) {
fs.appendFile('/var/log/app/values.log', req.body.value + '\n', function (err) {});
mc.set('foo', req.body.value, 3600, function (err) {
if(err) {
res.send('Could not set value\n', 500);
} else {
res.send('Value set!\n')
}
});
});
app.get('/test', function (req, res) {
mc.get('foo', function (err, data) {
if(err) {
res.send('Could not get value\n', 500);
} else {
res.send('Value = ' + data + '\n');
}
});
});
app.listen(port)
console.log('Running in ' + env + ' on http://localhost:' + port);
| var express = require('express'),
Memcached = require('memcached');
// Constants
var port = 3000;
var env = process.env.NODE_ENV || 'production';
var mc = new Memcached(process.env.MC_PORT.replace('tcp://', ''));
// App
var app = express();
app.use(express.urlencoded());
app.get('/', function (req, res) {
res.send('Hello World!!\n');
});
app.post('/test', function (req, res) {
mc.set('foo', req.body.value, 3600, function (err) {
if(err) {
res.send('Could not set value\n', 500);
} else {
res.send('Value set!\n')
}
});
});
app.get('/test', function (req, res) {
mc.get('foo', function (err, data) {
if(err) {
res.send('Could not get value\n', 500);
} else {
res.send('Value = ' + data + '\n');
}
});
});
app.listen(port)
console.log('Running in ' + env + ' on http://localhost:' + port);
|
Add eval command for JS scripting | var find_common_pkg = function(pkglist) {
var common = [pkglist[0].split(/\./)];
pkglist.forEach(function(pkg) {
var spl = pkg.split(/\./);
var fnd = false;
common.forEach(function(com, ind) {
if (spl[0] === com[0]) {
common[ind] = spl.filter(function(n) {
return com.indexOf(n) != -1;
});
fnd = true;
}
});
if (!fnd) common.push(spl);
});
var strjoin = [];
common.forEach(function(arg) {
strjoin.push(arg.join("."));
});
return strjoin;
};
var arr_to_vector = function(arr) {
var vec = $('java.util.Vector');
var vector = new vec();
arr.forEach(function(thing) {
vector.add(thing);
});
return vector;
};
$.command("eval", function() {
var fcmd = [].slice.call(arguments).join(" ");
eval(fcmd);
}); | var find_common_pkg = function(pkglist) {
var common = [pkglist[0].split(/\./)];
pkglist.forEach(function(pkg) {
var spl = pkg.split(/\./);
var fnd = false;
common.forEach(function(com, ind) {
if (spl[0] === com[0]) {
common[ind] = spl.filter(function(n) {
return com.indexOf(n) != -1;
});
fnd = true;
}
});
if (!fnd) common.push(spl);
});
var strjoin = [];
common.forEach(function(arg) {
strjoin.push(arg.join("."));
});
return strjoin;
};
var arr_to_vector = function(arr) {
var vec = $('java.util.Vector');
var vector = new vec();
arr.forEach(function(thing) {
vector.add(thing);
});
return vector;
}; |
Add benchmark for geocode function. | package main
import (
"testing"
"github.com/kellydunn/golang-geo"
)
func TestGeocode(t *testing.T) {
query := "1600 amphitheatre parkway"
expectedAddress := "1600 Amphitheatre Parkway, Mountain View, CA 94043, USA"
expectedLatitude, expectedLongitude := 37.4219998, -122.0839596
result, err := geocode(query, new(geo.GoogleGeocoder))
if err != nil {
t.Error(err)
}
if expectedAddress != result.Address {
t.Errorf("Address doesn't match. Expected %s, got %s", expectedAddress,
result.Address)
}
if expectedLatitude != result.Point.Lat() {
t.Errorf("Latitude doesn't match. Expected %s, got %s", expectedLatitude,
result.Point.Lat())
}
if expectedLongitude != result.Point.Lng() {
t.Errorf("Longitude doesn't match. Expected %s, got %s", expectedLongitude,
result.Point.Lng())
}
}
func BenchmarkGeocode(b *testing.B) {
for i := 0; i < b.N; i++ {
geocode("1600 amphitheatre parkway", new(geo.GoogleGeocoder))
}
}
| package main
import (
"testing"
"github.com/kellydunn/golang-geo"
)
func TestGeocode(t *testing.T) {
query := "1600 amphitheatre parkway"
expectedAddress := "1600 Amphitheatre Parkway, Mountain View, CA 94043, USA"
expectedLatitude, expectedLongitude := 37.4219998, -122.0839596
result, err := geocode(query, new(geo.GoogleGeocoder))
if err != nil {
t.Error(err)
}
if expectedAddress != result.Address {
t.Errorf("Address doesn't match. Expected %s, got %s", expectedAddress,
result.Address)
}
if expectedLatitude != result.Point.Lat() {
t.Errorf("Latitude doesn't match. Expected %s, got %s", expectedLatitude,
result.Point.Lat())
}
if expectedLongitude != result.Point.Lng() {
t.Errorf("Longitude doesn't match. Expected %s, got %s", expectedLongitude,
result.Point.Lng())
}
}
|
Remove newline at beginning of file | /**
* Copyright 2013-2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @emails react-core
*/
'use strict';
describe('ReactDOMIframe', function() {
var React;
var ReactTestUtils;
beforeEach(function() {
React = require('React');
ReactTestUtils = require('ReactTestUtils');
});
it('should trigger load events', function() {
var onLoadSpy = jasmine.createSpy();
var iframe = React.createElement('iframe', {onLoad: onLoadSpy});
iframe = ReactTestUtils.renderIntoDocument(iframe);
var loadEvent = document.createEvent('Event');
loadEvent.initEvent('load', false, false);
iframe.getDOMNode().dispatchEvent(loadEvent);
expect(onLoadSpy).toHaveBeenCalled();
});
});
|
/**
* Copyright 2013-2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @emails react-core
*/
'use strict';
describe('ReactDOMIframe', function() {
var React;
var ReactTestUtils;
beforeEach(function() {
React = require('React');
ReactTestUtils = require('ReactTestUtils');
});
it('should trigger load events', function() {
var onLoadSpy = jasmine.createSpy();
var iframe = React.createElement('iframe', {onLoad: onLoadSpy});
iframe = ReactTestUtils.renderIntoDocument(iframe);
var loadEvent = document.createEvent('Event');
loadEvent.initEvent('load', false, false);
iframe.getDOMNode().dispatchEvent(loadEvent);
expect(onLoadSpy).toHaveBeenCalled();
});
});
|
Add jQuery load to master template | <!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>@yield('title')</title>
{{ HTML::style('css/cnq.css') }}
<script type="text/javascript" src="//use.typekit.net/fky8rov.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
@yield('head')
</head>
<body>
<div id="content">
@if (Session::has('msg'))
<div class="alert">
{{ Session::get('msg') }}
</div>
@endif
@if (Session::has('error'))
<div class="alert error">
@foreach (Session::get('error')->all() as $err)
{{ $err }}<br>
@endforeach
</div>
@endif
@yield('content')
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
{{ HTML::script('js/cnq.js') }}
</body>
</html>
| <!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>@yield('title')</title>
{{ HTML::style('css/cnq.css') }}
<script type="text/javascript" src="//use.typekit.net/fky8rov.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
@yield('head')
</head>
<body>
<div id="content">
@if (Session::has('msg'))
<div class="alert">
{{ Session::get('msg') }}
</div>
@endif
@if (Session::has('error'))
<div class="alert error">
@foreach (Session::get('error')->all() as $err)
{{ $err }}<br>
@endforeach
</div>
@endif
@yield('content')
</div>
{{ HTML::script('js/cnq.js') }}
</body>
</html>
|
Add note to gcp session utils method | """Session management utilities for Google Cloud Platform (GCP)."""
from typing import Optional, Any
try:
import google.auth
from google.auth.transport import requests as google_requests
except ImportError:
raise ImportError(
'The `dicomweb-client` package needs to be installed with the '
'"gcp" extra requirements to use this module, as follows: '
'`pip install dicomweb-client[gcp]`')
import requests
def create_session_from_gcp_credentials(
google_credentials: Optional[Any] = None
) -> requests.Session:
"""Creates an authorized session for Google Cloud Platform.
Parameters
----------
google_credentials: Any
Google Cloud credentials.
(see https://cloud.google.com/docs/authentication/production
for more information on Google Cloud authentication).
If not set, will be initialized to ``google.auth.default()``.
Returns
-------
requests.Session
Google Cloud authorized session.
Note
----
Credentials will be read from environment variable
``GOOGLE_APPLICATION_CREDENTIALS`` if set.
"""
if google_credentials is None:
google_credentials, _ = google.auth.default(
scopes=['https://www.googleapis.com/auth/cloud-platform']
)
return google_requests.AuthorizedSession(google_credentials)
| """Session management utilities for Google Cloud Platform (GCP)."""
from typing import Optional, Any
try:
import google.auth
from google.auth.transport import requests as google_requests
except ImportError:
raise ImportError(
'The `dicomweb-client` package needs to be installed with the '
'"gcp" extra requirements to use this module, as follows: '
'`pip install dicomweb-client[gcp]`')
import requests
def create_session_from_gcp_credentials(
google_credentials: Optional[Any] = None
) -> requests.Session:
"""Creates an authorized session for Google Cloud Platform.
Parameters
----------
google_credentials: Any
Google Cloud credentials.
(see https://cloud.google.com/docs/authentication/production
for more information on Google Cloud authentication).
If not set, will be initialized to ``google.auth.default()``.
Returns
-------
requests.Session
Google Cloud authorized session.
"""
if google_credentials is None:
google_credentials, _ = google.auth.default(
scopes=['https://www.googleapis.com/auth/cloud-platform']
)
return google_requests.AuthorizedSession(google_credentials)
|
Remove create button in collection header when endpoint is database. | <h3 class="panel-title">
<span class="text-left"><?php echo ucwords(str_replace('_', ' ', ($this->response->meta->collection))); ?></span>
<?php
if ($this->m_users->get_user_permission('', $this->response->meta->collection, 'c') and $this->response->meta->collection != 'configuration' and $this->response->meta->collection != 'database') { ?>
<span class="pull-right" style="padding-left:10px;" >
<a class="btn btn-xs btn-primary" href="<?php echo $this->response->meta->collection; ?>/create" role="button"><?php echo __('Create'); ?></a>
</span>
<?php } ?>
<span class="pull-right">
<?php echo $this->response->meta->filtered . ' of ' . $this->response->meta->total . ' results'; ?>
</span>
</h3> | <h3 class="panel-title">
<span class="text-left"><?php echo ucwords(str_replace('_', ' ', ($this->response->meta->collection))); ?></span>
<?php
if ($this->m_users->get_user_permission('', $this->response->meta->collection, 'c') and $this->response->meta->collection != 'configuration') { ?>
<span class="pull-right" style="padding-left:10px;" >
<a class="btn btn-xs btn-primary" href="<?php echo $this->response->meta->collection; ?>/create" role="button"><?php echo __('Create'); ?></a>
</span>
<?php } ?>
<span class="pull-right">
<?php echo $this->response->meta->filtered . ' of ' . $this->response->meta->total . ' results'; ?>
</span>
</h3> |
Comment for the competition settings did not make sense. | # competition_settings.py
# This file contains settings for the current competition.
# This include start and end dates along with round information.
import datetime # Only used to dynamically set the round dates.
# The start and end date of the competition.
COMPETITION_START = (datetime.date.today() - datetime.timedelta(days=3)).strftime("%Y-%m-%d")
COMPETITION_END = (datetime.date.today() + datetime.timedelta(days=6)).strftime("%Y-%m-%d")
# The rounds of the competition. Specify dates using "yyyy-mm-dd".
# Start means the competition will start at midnight on that date.
# End means the competition will end at midnight of that date.
# This means that a round that ends on "2010-08-02" will end at 11:59pm of August 1st.
COMPETITION_ROUNDS = {
"Round 1" : {
"start": (datetime.date.today() - datetime.timedelta(days=3)).strftime("%Y-%m-%d"),
"end": (datetime.date.today() + datetime.timedelta(days=3)).strftime("%Y-%m-%d"),
},
}
# When enabled, users who try to access the site before or after the competition ends are blocked.
# Admin users are able to log in at any time.
CAN_ACCESS_OUTSIDE_COMPETITION = False
| # competition_settings.py
# This file contains settings for the current competition.
# This include start and end dates along with round information.
import datetime # Only used to dynamically set the round dates.
# The start and end date of the competition.
COMPETITION_START = (datetime.date.today() - datetime.timedelta(days=3)).strftime("%Y-%m-%d")
COMPETITION_END = (datetime.date.today() + datetime.timedelta(days=6)).strftime("%Y-%m-%d")
# The rounds of the competition. Specify dates using "yyyy-mm-dd".
# Start means the competition will start at midnight on that date.
# End means the competition will end at midnight of that date.
# This means that a round that ends on "2010-08-02" will end at 11:59pm of August 2nd.
COMPETITION_ROUNDS = {
"Round 1" : {
"start": (datetime.date.today() - datetime.timedelta(days=3)).strftime("%Y-%m-%d"),
"end": (datetime.date.today() + datetime.timedelta(days=3)).strftime("%Y-%m-%d"),
},
}
# When enabled, users who try to access the site before or after the competition ends are blocked.
# Admin users are able to log in at any time.
CAN_ACCESS_OUTSIDE_COMPETITION = False
|
Test france compatibility with the new API | # -*- coding: utf-8 -*-
import subprocess
import time
from unittest import TestCase
from nose.tools import assert_equal
class TestOldApi(TestCase):
def setUp(self):
self.process = subprocess.Popen("openfisca-serve")
def tearDown(self):
self.process.terminate()
def test_response(self):
try:
subprocess.check_call(['wget', '--quiet', '--retry-connrefused', '--waitretry=1', '--tries=10', 'http://localhost:2000', '--output-document=/dev/null'])
except subprocess.CalledProcessError:
raise subprocess.CalledProcessError("Could not reach OpenFisca Web API at localhost:2000 after 10s")
class TestNewApi(TestCase):
def setUp(self):
self.process = subprocess.Popen(['openfisca', 'serve'])
def tearDown(self):
self.process.terminate()
def test_response(self):
try:
subprocess.check_call(['wget', '--quiet', '--retry-connrefused', '--waitretry=1', '--tries=10', 'http://localhost:6000/parameters', '--output-document=/dev/null'])
except subprocess.CalledProcessError:
raise subprocess.CalledProcessError("Could not reach OpenFisca Web API at localhost:6000 after 10s")
| # -*- coding: utf-8 -*-
import subprocess
import time
from unittest import TestCase
from nose.tools import assert_equal
class TestOldApi(TestCase):
def setUp(self):
self.process = subprocess.Popen("openfisca-serve")
def tearDown(self):
self.process.terminate()
def test_response(self):
try:
subprocess.check_call(['wget', '--quiet', '--retry-connrefused', '--waitretry=1', '--tries=10', 'http://localhost:2000', '--output-document=/dev/null'])
except subprocess.CalledProcessError:
raise subprocess.CalledProcessError("Could not reach OpenFisca Web API at localhost:2000 after 10s")
|
Fix case of filename keyboardShortcuts.json | 'use strict';
var App = require('../app');
var Backbone = require('backbone');
var Marionette = require('backbone.marionette');
var _ = require('underscore');
var keyboardShortcuts = require('./keyboardShortcuts.json');
var marked = require('marked');
var controller = {
showHelp: function () {
var HelpView = require('./views/HelpView');
_.each(keyboardShortcuts, function (category) {
_.each(category.shortcuts, function (shortcut) {
shortcut.description = marked(shortcut.description);
});
});
var helpModel = new Backbone.Model({keyboardShortcuts: keyboardShortcuts});
App.mainRegion.show(new HelpView({model: helpModel}));
App.navigationRegion.currentView.options.collection.deselect();
}
};
App.addInitializer(function () {
new Marionette.AppRouter({
controller: controller,
appRoutes: {
'help': 'showHelp'
}
});
});
| 'use strict';
var App = require('../app');
var Backbone = require('backbone');
var Marionette = require('backbone.marionette');
var _ = require('underscore');
var keyboardShortcuts = require('./keyboardshortcuts.json');
var marked = require('marked');
var controller = {
showHelp: function () {
var HelpView = require('./views/HelpView');
_.each(keyboardShortcuts, function (category) {
_.each(category.shortcuts, function (shortcut) {
shortcut.description = marked(shortcut.description);
});
});
var helpModel = new Backbone.Model({keyboardShortcuts: keyboardShortcuts});
App.mainRegion.show(new HelpView({model: helpModel}));
App.navigationRegion.currentView.options.collection.deselect();
}
};
App.addInitializer(function () {
new Marionette.AppRouter({
controller: controller,
appRoutes: {
'help': 'showHelp'
}
});
});
|
Set correct type of cache map | /*
* This file is part of Bisq.
*
* Bisq 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.
*
* Bisq 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 Bisq. If not, see <http://www.gnu.org/licenses/>.
*/
package bisq.desktop.common.view;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.HashMap;
import java.util.Map;
@Singleton
public class CachingViewLoader implements ViewLoader {
private final Map<Class<? extends View>, View> cache = new HashMap<>();
private final ViewLoader viewLoader;
@Inject
public CachingViewLoader(ViewLoader viewLoader) {
this.viewLoader = viewLoader;
}
@Override
public View load(Class<? extends View> viewClass) {
if (cache.containsKey(viewClass))
return cache.get(viewClass);
View view = viewLoader.load(viewClass);
cache.put(viewClass, view);
return view;
}
}
| /*
* This file is part of Bisq.
*
* Bisq 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.
*
* Bisq 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 Bisq. If not, see <http://www.gnu.org/licenses/>.
*/
package bisq.desktop.common.view;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.HashMap;
@Singleton
public class CachingViewLoader implements ViewLoader {
private final HashMap<Object, View> cache = new HashMap<>();
private final ViewLoader viewLoader;
@Inject
public CachingViewLoader(ViewLoader viewLoader) {
this.viewLoader = viewLoader;
}
@Override
public View load(Class<? extends View> viewClass) {
if (cache.containsKey(viewClass))
return cache.get(viewClass);
View view = viewLoader.load(viewClass);
cache.put(viewClass, view);
return view;
}
}
|
Add renaming of nextTab -> switchTab | /* eslint-disable import/no-named-as-default */
/* eslint-disable react/forbid-prop-types */
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Stepper } from './Stepper';
import { TabNavigator } from './TabNavigator';
import DataTablePageView from './DataTablePageView';
import { WizardActions } from '../actions/WizardActions';
import { selectCurrentTab } from '../selectors/wizard';
/**
* Layout component for a Tracker and TabNavigator, displaying steps
* to completion for completion. See TabNavigator and StepsTracker
* for individual component implementation.
*/
const WizardComponent = ({ tabs, titles, currentTab, switchTab }) => (
<DataTablePageView>
<Stepper
numberOfSteps={tabs.length}
currentStep={currentTab}
onPress={switchTab}
titles={titles}
/>
<TabNavigator tabs={tabs} currentTabIndex={currentTab} />
</DataTablePageView>
);
WizardComponent.propTypes = {
tabs: PropTypes.array.isRequired,
titles: PropTypes.array.isRequired,
switchTab: PropTypes.func.isRequired,
currentTab: PropTypes.number.isRequired,
};
const mapStateToProps = state => {
const currentTab = selectCurrentTab(state);
return { currentTab };
};
const mapDispatchToProps = dispatch => ({
switchTab: tab => dispatch(WizardActions.switchTab(tab)),
});
export const Wizard = connect(mapStateToProps, mapDispatchToProps)(WizardComponent);
| /* eslint-disable import/no-named-as-default */
/* eslint-disable react/forbid-prop-types */
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Stepper } from './Stepper';
import { TabNavigator } from './TabNavigator';
import DataTablePageView from './DataTablePageView';
import { WizardActions } from '../actions/WizardActions';
import { selectCurrentTab } from '../selectors/wizard';
/**
* Layout component for a Tracker and TabNavigator, displaying steps
* to completion for completion. See TabNavigator and StepsTracker
* for individual component implementation.
*/
const WizardComponent = ({ tabs, titles, currentTab, nextTab }) => (
<DataTablePageView>
<Stepper
numberOfSteps={tabs.length}
currentStep={currentTab}
onPress={nextTab}
titles={titles}
/>
<TabNavigator tabs={tabs} currentTabIndex={currentTab} />
</DataTablePageView>
);
WizardComponent.propTypes = {
tabs: PropTypes.array.isRequired,
titles: PropTypes.array.isRequired,
nextTab: PropTypes.func.isRequired,
currentTab: PropTypes.number.isRequired,
};
const mapStateToProps = state => {
const currentTab = selectCurrentTab(state);
return { currentTab };
};
const mapDispatchToProps = dispatch => ({
nextTab: tab => dispatch(WizardActions.switchTab(tab)),
});
export const Wizard = connect(mapStateToProps, mapDispatchToProps)(WizardComponent);
|
Fix float type flag definition | import functools
import tensorflow as tf
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string("batch-size", 64, "")
tf.app.flags.DEFINE_float("dropout-prob", 0, "")
tf.app.flags.DEFINE_string("word-file", None, "")
tf.app.flags.DEFINE_integer("num-threads-per-queue", 2, "")
tf.app.flags.DEFINE_integer("queue-capacity", 2, "")
tf.app.flags.DEFINE_string("length-boundaries", "", "")
tf.app.flags.DEFINE_string("rnn-cell", "ln_lstm", "Default RNN cell")
tf.app.flags.DEFINE_string("float-type", "float32", "")
@functools.lru_cache()
def words():
with open(tf.app.flags.FLAGS.word_file) as file_:
return sorted([line.strip() for line in file_.readlines()])
@functools.lru_cache()
def word_indices():
# 0 -> null, 1 -> unknown
return { word: index + 2 for index, word in enumerate(flags.words()) }
@functools.lru_cache()
def word_space_size():
return len(words())
def rnn_cell():
from .rnn import cell
return getattr(cell, FLAGS.rnn_cell)
def float_type():
return getattr(tf, FLAGS.float_type)
| import functools
import tensorflow as tf
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string("batch-size", 64, "")
tf.app.flags.DEFINE_float("dropout-prob", 0, "")
tf.app.flags.DEFINE_string("word-file", None, "")
tf.app.flags.DEFINE_integer("num-threads-per-queue", 2, "")
tf.app.flags.DEFINE_integer("queue-capacity", 2, "")
tf.app.flags.DEFINE_string("length-boundaries", "", "")
tf.app.flags.DEFINE_string("rnn-cell", "ln_lstm", "Default RNN cell")
tf.app.flags.DEFINE_string("float32", "", "")
@functools.lru_cache()
def words():
with open(tf.app.flags.FLAGS.word_file) as file_:
return sorted([line.strip() for line in file_.readlines()])
@functools.lru_cache()
def word_indices():
# 0 -> null, 1 -> unknown
return { word: index + 2 for index, word in enumerate(flags.words()) }
@functools.lru_cache()
def word_space_size():
return len(words())
def rnn_cell():
from .rnn import cell
return getattr(cell, FLAGS.rnn_cell)
def float_type():
return getattr(tf, FLAGS.float_type)
|
Add test to check excplicitly if the attribute is set | #!/usr/bin/env
# Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
from nose.tools import assert_equals
from botocore import exceptions
def test_client_error_can_handle_missing_code_or_message():
response = {'Error': {}}
expect = 'An error occurred (Unknown) when calling the blackhole operation: Unknown'
assert_equals(str(exceptions.ClientError(response, 'blackhole')), expect)
def test_client_error_has_operation_name_set():
response = {'Error': {}}
exception = exceptions.ClientError(response, 'blackhole')
assert(hasattr(exception, 'operation_name'))
def test_client_error_set_correct_operation_name():
response = {'Error': {}}
exception = exceptions.ClientError(response, 'blackhole')
assert_equals(exception.operation_name, 'blackhole')
| #!/usr/bin/env
# Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
from nose.tools import assert_equals
from botocore import exceptions
def test_client_error_can_handle_missing_code_or_message():
response = {'Error': {}}
expect = 'An error occurred (Unknown) when calling the blackhole operation: Unknown'
assert_equals(str(exceptions.ClientError(response, 'blackhole')), expect)
def test_client_error_has_operation_name_set():
response = {'Error': {}}
exception = exceptions.ClientError(response, 'blackhole')
assert_equals(exception.operation_name, 'blackhole')
|
Add test case without output file for expand.go
Signed-off-by: Sergey <95b6115869faa4e182a269b2ddf6435382b0fe53@gmail.com> | package commands
import (
"os"
"path/filepath"
"testing"
flags "github.com/jessevdk/go-flags"
"github.com/stretchr/testify/assert"
)
// Commands requires at least one arg
func TestCmd_Expand(t *testing.T) {
v := &ExpandSpec{}
testRequireParam(t, v)
}
func TestCmd_Expand_NoError(t *testing.T) {
specDoc := filepath.Join(fixtureBase, "bugs", "1536", "fixture-1536.yaml")
outDir, output := getOutput(t, specDoc, "flatten", "fixture-1536-flat-expand.json")
defer os.RemoveAll(outDir)
v := &ExpandSpec{
Format: "json",
Compact: false,
Output: flags.Filename(output),
}
testProduceOutput(t, v, specDoc, output)
}
func TestCmd_Expand_NoOutputFile(t *testing.T) {
specDoc := filepath.Join(fixtureBase, "bugs", "1536", "fixture-1536.yaml")
v := &ExpandSpec{
Format: "json",
Compact: false,
Output: "",
}
result := v.Execute([]string{specDoc})
assert.Nil(t, result)
}
func TestCmd_Expand_Error(t *testing.T) {
v := &ExpandSpec{}
testValidRefs(t, v)
}
| package commands
import (
"os"
"path/filepath"
"testing"
flags "github.com/jessevdk/go-flags"
)
// Commands requires at least one arg
func TestCmd_Expand(t *testing.T) {
v := &ExpandSpec{}
testRequireParam(t, v)
}
func TestCmd_Expand_NoError(t *testing.T) {
specDoc := filepath.Join(fixtureBase, "bugs", "1536", "fixture-1536.yaml")
outDir, output := getOutput(t, specDoc, "flatten", "fixture-1536-flat-expand.json")
defer os.RemoveAll(outDir)
v := &ExpandSpec{
Format: "json",
Compact: false,
Output: flags.Filename(output),
}
testProduceOutput(t, v, specDoc, output)
}
func TestCmd_Expand_Error(t *testing.T) {
v := &ExpandSpec{}
testValidRefs(t, v)
}
|
Fix cookie options parser for php 5.4 | <?php
namespace SimplyTestable\WebClientBundle\Services\TestOptions\Adapter\Request\FeatureParser;
class CookieOptionsParser extends OptionsParser {
private $requiredNonBlankFields = [
'name',
'value'
];
public function getOptions() {
$options = parent::getOptions();
if (isset($options['cookies'])) {
$cookies = $options['cookies'];
foreach ($cookies as $index => $cookie) {
if (!$this->containsRequiredNonBlankFields($cookie)) {
unset($cookies[$index]);
}
}
$options['cookies'] = $cookies;
}
return $options;
}
/**
* @param $cookie
* @return bool
*/
private function containsRequiredNonBlankFields($cookie) {
foreach ($this->requiredNonBlankFields as $fieldName) {
if (!isset($cookie[$fieldName])) {
return false;
}
return trim($cookie[$fieldName]) !== '';
}
}
} | <?php
namespace SimplyTestable\WebClientBundle\Services\TestOptions\Adapter\Request\FeatureParser;
class CookieOptionsParser extends OptionsParser {
private $requiredNonBlankFields = [
'name',
'value'
];
public function getOptions() {
$options = parent::getOptions();
if (isset($options['cookies'])) {
$cookies = $options['cookies'];
foreach ($cookies as $index => $cookie) {
if (!$this->containsRequiredNonBlankFields($cookie)) {
unset($cookies[$index]);
}
}
$options['cookies'] = $cookies;
}
return $options;
}
/**
* @param $cookie
* @return bool
*/
private function containsRequiredNonBlankFields($cookie) {
foreach ($this->requiredNonBlankFields as $fieldName) {
if (!isset($cookie[$fieldName])) {
return false;
}
return !empty(trim($cookie[$fieldName]));
}
}
} |
Remove specs from suite (separate) | <?php
require_once(dirname(__FILE__).'/../vendor/simpletest/autorun.php');
require_once(dirname(__FILE__).'/../Mustache.php');
class MustacheTestSuite extends TestSuite {
function MustacheTestSuite() {
$this->TestSuite('All Mustache tests');
$this->addFile(dirname(__FILE__)."/testStringScanner.php");
$this->addFile(dirname(__FILE__)."/testHelpers.php");
$this->addFile(dirname(__FILE__)."/testMustache.php");
$this->addFile(dirname(__FILE__)."/testContext.php");
$this->addFile(dirname(__FILE__)."/testParser.php");
$this->addFile(dirname(__FILE__)."/testGenerator.php");
// $this->addFile(dirname(__FILE__)."/testSpec.php");
}
};
?> | <?php
require_once(dirname(__FILE__).'/../vendor/simpletest/autorun.php');
require_once(dirname(__FILE__).'/../Mustache.php');
class MustacheTestSuite extends TestSuite {
function MustacheTestSuite() {
$this->TestSuite('All Mustache tests');
$this->addFile(dirname(__FILE__)."/testStringScanner.php");
$this->addFile(dirname(__FILE__)."/testHelpers.php");
$this->addFile(dirname(__FILE__)."/testMustache.php");
$this->addFile(dirname(__FILE__)."/testContext.php");
$this->addFile(dirname(__FILE__)."/testParser.php");
$this->addFile(dirname(__FILE__)."/testGenerator.php");
$this->addFile(dirname(__FILE__)."/testSpec.php");
}
};
?> |
Switch node sortkey on Workload page.
The node sortkey was displayname instead of node.sortName which
caused sorting to behave strangely.
I switched the sortkeys and added more to the sortkey array to
help provide a more stable sort.
rancher/rancher#21218 | import Component from '@ember/component';
import ManageLabels from 'shared/mixins/manage-labels';
import layout from './template';
export default Component.extend(ManageLabels, {
layout,
model: null,
expandOnInit: true,
sortBy: 'displayState',
showKind: true,
descending: true,
initExpand: true,
headers: [
{
name: 'displayState',
sort: ['displayState', 'sortName', 'id'],
translationKey: 'generic.state',
width: 120
},
{
name: 'name',
sort: ['sortName', 'id'],
translationKey: 'generic.name',
width: 350
},
{
name: 'displayImage',
sort: ['displayImage', 'displayIp', 'created'],
translationKey: 'generic.image',
},
{
name: 'node',
sort: ['node.sortName', 'node.ipAddress', 'node.id'],
translationKey: 'generic.node',
},
],
});
| import Component from '@ember/component';
import ManageLabels from 'shared/mixins/manage-labels';
import layout from './template';
export default Component.extend(ManageLabels, {
layout,
model: null,
expandOnInit: true,
sortBy: 'displayState',
showKind: true,
descending: true,
initExpand: true,
headers: [
{
name: 'displayState',
sort: ['displayState'],
translationKey: 'generic.state',
width: 120
},
{
name: 'name',
sort: ['name'],
translationKey: 'generic.name',
width: 350
},
{
name: 'displayImage',
sort: ['displayImage'],
translationKey: 'generic.image',
},
{
name: 'node',
sort: ['displayName'],
translationKey: 'generic.node',
},
],
});
|
Remove num_members as it's not exposed anymore | package slack
// Conversation is the foundation for IM and BaseGroupConversation
type conversation struct {
ID string `json:"id"`
Created JSONTime `json:"created"`
IsOpen bool `json:"is_open"`
LastRead string `json:"last_read,omitempty"`
Latest *Message `json:"latest,omitempty"`
UnreadCount int `json:"unread_count,omitempty"`
UnreadCountDisplay int `json:"unread_count_display,omitempty"`
}
// GroupConversation is the foundation for Group and Channel
type groupConversation struct {
conversation
Name string `json:"name"`
Creator string `json:"creator"`
IsArchived bool `json:"is_archived"`
Members []string `json:"members"`
Topic Topic `json:"topic"`
Purpose Purpose `json:"purpose"`
}
// Topic contains information about the topic
type Topic struct {
Value string `json:"value"`
Creator string `json:"creator"`
LastSet JSONTime `json:"last_set"`
}
// Purpose contains information about the purpose
type Purpose struct {
Value string `json:"value"`
Creator string `json:"creator"`
LastSet JSONTime `json:"last_set"`
}
| package slack
// Conversation is the foundation for IM and BaseGroupConversation
type conversation struct {
ID string `json:"id"`
Created JSONTime `json:"created"`
IsOpen bool `json:"is_open"`
LastRead string `json:"last_read,omitempty"`
Latest *Message `json:"latest,omitempty"`
UnreadCount int `json:"unread_count,omitempty"`
UnreadCountDisplay int `json:"unread_count_display,omitempty"`
}
// GroupConversation is the foundation for Group and Channel
type groupConversation struct {
conversation
Name string `json:"name"`
Creator string `json:"creator"`
IsArchived bool `json:"is_archived"`
Members []string `json:"members"`
NumMembers int `json:"num_members,omitempty"`
Topic Topic `json:"topic"`
Purpose Purpose `json:"purpose"`
}
// Topic contains information about the topic
type Topic struct {
Value string `json:"value"`
Creator string `json:"creator"`
LastSet JSONTime `json:"last_set"`
}
// Purpose contains information about the purpose
type Purpose struct {
Value string `json:"value"`
Creator string `json:"creator"`
LastSet JSONTime `json:"last_set"`
}
|
Use a fast password hasher for tests.
Speed is obviously more important than security in tests. | from __future__ import unicode_literals
AUTHENTICATION_BACKENDS = [
"django.contrib.auth.backends.ModelBackend",
"sesame.backends.ModelBackend",
]
CACHES = {"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}}
DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3"}}
INSTALLED_APPS = [
"django.contrib.auth",
"django.contrib.contenttypes",
"sesame",
"sesame.test_app",
]
LOGGING_CONFIG = None
MIDDLEWARE = [
"django.contrib.sessions.middleware.SessionMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
]
PASSWORD_HASHERS = ["django.contrib.auth.hashers.SHA1PasswordHasher"]
ROOT_URLCONF = "sesame.test_urls"
SECRET_KEY = "Anyone who finds an URL will be able to log in. Seriously."
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
TEMPLATES = [{"BACKEND": "django.template.backends.django.DjangoTemplates"}]
| from __future__ import unicode_literals
AUTHENTICATION_BACKENDS = [
"django.contrib.auth.backends.ModelBackend",
"sesame.backends.ModelBackend",
]
CACHES = {"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}}
DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3"}}
INSTALLED_APPS = [
"django.contrib.auth",
"django.contrib.contenttypes",
"sesame",
"sesame.test_app",
]
LOGGING_CONFIG = None
MIDDLEWARE = [
"django.contrib.sessions.middleware.SessionMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
]
ROOT_URLCONF = "sesame.test_urls"
SECRET_KEY = "Anyone who finds an URL will be able to log in. Seriously."
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
TEMPLATES = [{"BACKEND": "django.template.backends.django.DjangoTemplates"}]
|
Fix error in callback on login post | /**
* Module dependencies.
*/
var passport = require('passport'),
login = require('connect-ensure-login'),
router = require('express').Router(),
oauth2 = require('./oauth2'),
user = require('./user');
router.get('/dialog/authorize', oauth2.authorization);
//router.post('/dialog/authorize/decision', oauth2.decision);
router.post('/oauth/token', oauth2.token);
router.get('/api/userinfo', user.info);
router.get('/', function(req, res) {
res.send('OAuth 2.0 Server');
});
router.get('/login', function(req, res) {
return res.render('login');
});
router.post('/login', passport.authenticate('local', { successReturnToOrRedirect: '/', failureRedirect: '/login' }));
router.get('/register', function(req, res) {
console.log(req.query);
var callback = req.query.callback;
return res.render('register', {callback});
});
router.post('/register', function(req, res) {
user.create(req, res);
});
router.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
router.get('/account', login.ensureLoggedIn(), function(req, res) {
res.render('account', { user: req.user });
});
module.exports = router;
| /**
* Module dependencies.
*/
var passport = require('passport'),
login = require('connect-ensure-login'),
router = require('express').Router(),
oauth2 = require('./oauth2'),
user = require('./user');
router.get('/dialog/authorize', oauth2.authorization);
//router.post('/dialog/authorize/decision', oauth2.decision);
router.post('/oauth/token', oauth2.token);
router.get('/api/userinfo', user.info);
router.get('/', function(req, res) {
res.send('OAuth 2.0 Server');
});
router.get('/login', function(req, res) {
return res.render('login');
});
router.post('/login', passport.authenticate('local', { successReturnToOrRedirect: process.env.NODEBB, failureRedirect: '/login' }));
router.get('/register', function(req, res) {
console.log(req.query);
var callback = req.query.callback;
return res.render('register', {callback});
});
router.post('/register', function(req, res) {
user.create(req, res);
});
router.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
router.get('/account', login.ensureLoggedIn(), function(req, res) {
res.render('account', { user: req.user });
});
module.exports = router;
|
Add test case to check inOrder when tree is empty. Throws NoSuchElement exception | package binary_search_tree;
import java.util.NoSuchElementException;
import binary_search_tree.Bst; // My implementation of Binary Search Tree in package binary_search_tree
/*
Class to test class Bst. (Binary Search Tree)
*/
class TestBst{
// Tests Insertion
public static void testInsertion(){
// Create a bst object
Bst bst = new Bst();
// Test inorder when tree is empty. Should throw exception
try{
bst.inOrder();
}
catch(NoSuchElementException e){
System.out.println(e);
}
// Create array of integers to insert
int[] values = {10, 7, 9, 8, 2, 15, 13, 17};
// Insert values into bst
for(int v: values){
bst.insert(v);
}
// Print In Order traversal
System.out.print("Inorder Traversal:\t ");
bst.inOrder();
System.out.println();
System.out.println("Should be:\t\t 2 7 8 9 10 13 15 17");
}
public static void main(String args[]){
// Test Insertion
testInsertion();
}
}
| package binary_search_tree;
import binary_search_tree.Bst; // My implementation of Binary Search Tree in package binary_search_tree
/*
Class to test class Bst. (Binary Search Tree)
*/
class TestBst{
// Tests Insertion
public static void testInsertion(){
// Create a bst object
Bst bst = new Bst();
// Create array of integers to insert
int[] values = {10, 7, 9, 8, 2, 15, 13, 17};
// Insert values into bst
for(int v: values){
bst.insert(v);
}
// Print In Order traversal
System.out.print("Inorder Traversal:\t ");
bst.inOrder();
System.out.println();
System.out.println("Should be:\t\t 2 7 8 9 10 13 15 17");
}
public static void main(String args[]){
// Test Insertion
testInsertion();
}
}
|
Tweak documentation for order in order book reconstruction | package org.jvirtanen.parity.top;
/**
* An order in an order book.
*/
public class Order {
private Level parent;
private long remainingQuantity;
Order(Level parent, long size) {
this.parent = parent;
this.remainingQuantity = size;
}
OrderBook getOrderBook() {
return parent.getParent().getParent();
}
/**
* Get the instrument.
*
* @return the instrument
*/
public long getInstrument() {
return getOrderBook().getInstrument();
}
/**
* Get the price.
*
* @return the price
*/
public long getPrice() {
return parent.getPrice();
}
/**
* Get the side.
*
* @return the side
*/
public Side getSide() {
return parent.getParent().getSide();
}
/**
* Get the remaining quantity.
*
* @return the remaining quantity
*/
public long getRemainingQuantity() {
return remainingQuantity;
}
boolean isOnBestLevel() {
return parent.isBestLevel();
}
void reduce(long quantity) {
remainingQuantity -= quantity;
}
void delete() {
parent.delete(this);
}
}
| package org.jvirtanen.parity.top;
/**
* <code>Order</code> represents an order in an order book.
*/
public class Order {
private Level parent;
private long remainingQuantity;
Order(Level parent, long size) {
this.parent = parent;
this.remainingQuantity = size;
}
OrderBook getOrderBook() {
return parent.getParent().getParent();
}
/**
* Get the instrument.
*
* @return the instrument
*/
public long getInstrument() {
return getOrderBook().getInstrument();
}
/**
* Get the price.
*
* @return the price
*/
public long getPrice() {
return parent.getPrice();
}
/**
* Get the side.
*
* @return the side
*/
public Side getSide() {
return parent.getParent().getSide();
}
/**
* Get the remaining quantity.
*
* @return the remaining quantity
*/
public long getRemainingQuantity() {
return remainingQuantity;
}
boolean isOnBestLevel() {
return parent.isBestLevel();
}
void reduce(long quantity) {
remainingQuantity -= quantity;
}
void delete() {
parent.delete(this);
}
}
|
Load JS data now that there is a first data set available | var fs = require('fs'),
path = require('path'),
extend = require('extend');
function load() {
// Recursively load one or more directories passed as arguments.
var dir, result = {};
function processFilename(fn) {
var fp = path.join(dir, fn),
// If the given filename is a directory, recursively load it.
extra = fs.statSync(fp).isDirectory() ? load(fp) : require(fp);
// The JSON data is independent of the actual file
// hierarchy, so it is essential to extend "deeply".
result = extend(true, result, extra);
}
for (dir of arguments) {
dir = path.resolve(__dirname, dir);
fs.readdirSync(dir).forEach(processFilename);
}
return result;
}
module.exports = load(
// 'api',
'css',
// 'http',
'javascript',
'webextensions'
);
| var fs = require('fs'),
path = require('path'),
extend = require('extend');
function load() {
// Recursively load one or more directories passed as arguments.
var dir, result = {};
function processFilename(fn) {
var fp = path.join(dir, fn),
// If the given filename is a directory, recursively load it.
extra = fs.statSync(fp).isDirectory() ? load(fp) : require(fp);
// The JSON data is independent of the actual file
// hierarchy, so it is essential to extend "deeply".
result = extend(true, result, extra);
}
for (dir of arguments) {
dir = path.resolve(__dirname, dir);
fs.readdirSync(dir).forEach(processFilename);
}
return result;
}
module.exports = load(
// 'api',
'css',
// 'http',
// 'javascript',
'webextensions'
);
|
fix: Fix global name and add preact to the list of externals.
#1150 | const browsers = require('./test/browsers');
module.exports = {
type: 'web-module',
npm: {
cjs: false,
esModules: true,
umd: {
externals: { preact: 'preact' },
global: 'skate'
}
},
karma: process.argv.indexOf('--ci') === -1 ? {
browsers: [require('karma-chrome-launcher')]
} : {
browsers: Object.keys(browsers),
plugins: ['karma-sauce-launcher'],
reporters: ['saucelabs'],
extra: {
sauceLabs: {},
customLaunchers: browsers,
retryLimit: 3,
autoWatch: false,
concurrency: 4,
browserDisconnectTimeout: 10000,
browserDisconnectTolerance: 5,
captureTimeout: 120000
}
},
babel: {
plugins: ['transform-react-jsx']
}
};
| const browsers = require('./test/browsers');
module.exports = {
type: 'web-module',
npm: {
cjs: false,
esModules: true,
umd: true
},
karma: process.argv.indexOf('--ci') === -1 ? {
browsers: [require('karma-chrome-launcher')]
} : {
browsers: Object.keys(browsers),
plugins: ['karma-sauce-launcher'],
reporters: ['saucelabs'],
extra: {
sauceLabs: {},
customLaunchers: browsers,
retryLimit: 3,
autoWatch: false,
concurrency: 4,
browserDisconnectTimeout: 10000,
browserDisconnectTolerance: 5,
captureTimeout: 120000
}
},
babel: {
plugins: ['transform-react-jsx']
}
};
|
Add a test case for very large sparse matrix | /*
* Copyright 2011-2013, by Vladimir Kostyukov and Contributors.
*
* This file is part of la4j project (http://la4j.org)
*
* 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.
*
* Contributor(s): -
*
*/
package org.la4j.matrix.sparse;
import org.la4j.matrix.AbstractMatrixTest;
public abstract class SparseMatrixTest extends AbstractMatrixTest {
public void testCardinality() {
double array[][] = new double[][] {
{ 1.0, 0.0, 0.0 },
{ 0.0, 5.0, 0.0 },
{ 0.0, 0.0, 9.0 }
};
SparseMatrix a = (SparseMatrix) factory().createMatrix(array);
assertEquals(3, a.cardinality());
}
public void testLargeMatrix()
{
SparseMatrix a = (SparseMatrix) factory().createMatrix(1000000, 1000000);
}
}
| /*
* Copyright 2011-2013, by Vladimir Kostyukov and Contributors.
*
* This file is part of la4j project (http://la4j.org)
*
* 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.
*
* Contributor(s): -
*
*/
package org.la4j.matrix.sparse;
import org.la4j.matrix.AbstractMatrixTest;
public abstract class SparseMatrixTest extends AbstractMatrixTest {
public void testCardinality() {
double array[][] = new double[][] {
{ 1.0, 0.0, 0.0 },
{ 0.0, 5.0, 0.0 },
{ 0.0, 0.0, 9.0 }
};
SparseMatrix a = (SparseMatrix) factory().createMatrix(array);
assertEquals(3, a.cardinality());
}
}
|
Resolve packages relative to the package.json file instead of to the root
Fixes #47 | 'use strict';
const path = require('path');
const pkgUp = require('pkg-up');
const multimatch = require('multimatch');
const arrify = require('arrify');
const resolvePkg = require('resolve-pkg');
module.exports = (grunt, options = {}) => {
const pattern = arrify(options.pattern || ['grunt-*', '@*/grunt-*']);
const scope = arrify(options.scope || ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies']);
let cwd = process.cwd();
let config = options.config || pkgUp.sync();
if (typeof config === 'string') {
const configPath = path.resolve(config);
cwd = path.dirname(configPath);
config = require(configPath);
}
pattern.push('!grunt', '!grunt-cli');
const names = scope.reduce((result, prop) => {
const deps = config[prop] || [];
return result.concat(Array.isArray(deps) ? deps : Object.keys(deps));
}, []);
for (const packageName of multimatch(names, pattern)) {
if (options.requireResolution === true) {
try {
grunt.loadTasks(resolvePkg(path.join(packageName, 'tasks'), {cwd}));
} catch (err) {
grunt.log.error(`npm package \`${packageName}\` not found. Is it installed?`);
}
} else {
grunt.loadNpmTasks(packageName);
}
}
};
| 'use strict';
const path = require('path');
const pkgUp = require('pkg-up');
const multimatch = require('multimatch');
const arrify = require('arrify');
const resolvePkg = require('resolve-pkg');
module.exports = (grunt, options = {}) => {
const pattern = arrify(options.pattern || ['grunt-*', '@*/grunt-*']);
const scope = arrify(options.scope || ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies']);
let config = options.config || pkgUp.sync();
if (typeof config === 'string') {
config = require(path.resolve(config));
}
pattern.push('!grunt', '!grunt-cli');
const names = scope.reduce((result, prop) => {
const deps = config[prop] || [];
return result.concat(Array.isArray(deps) ? deps : Object.keys(deps));
}, []);
for (const packageName of multimatch(names, pattern)) {
if (options.requireResolution === true) {
try {
grunt.loadTasks(resolvePkg(path.join(packageName, 'tasks')));
} catch (err) {
grunt.log.error(`npm package \`${packageName}\` not found. Is it installed?`);
}
} else {
grunt.loadNpmTasks(packageName);
}
}
};
|
Use new column for score. | import sqlite3
def main():
conn = sqlite3.connect("database")
cursor = conn.cursor()
# I claim this gives the current score. Another formulation is
# select trackid, score, max(scoreid) from scores group by trackid;
# cursor.execute("""select trackid, score from scores
# group by trackid order by scoreid""")
# cursor.execute("""select scores.trackid, score, path from scores, tracks
# where scores.trackid = tracks.trackid
# group by scores.trackid order by scoreid""")
cursor.execute("""select score, path from tracks
where score is not null""")
results = cursor.fetchall()
for result in results:
print str(result[0]) + "\t" + result[1]
if __name__ == '__main__':
main()
| import sqlite3
def main():
conn = sqlite3.connect("database")
cursor = conn.cursor()
# I claim this gives the current score. Another formulation is
# select trackid, score, max(scoreid) from scores group by trackid;
# cursor.execute("""select trackid, score from scores
# group by trackid order by scoreid""")
cursor.execute("""select scores.trackid, score, path from scores, tracks
where scores.trackid = tracks.trackid
group by scores.trackid order by scoreid""")
results = cursor.fetchall()
for result in results:
print str(result[1]) + "\t" + result[2]
if __name__ == '__main__':
main()
|
Include base version for msgpack, because 0.3 doesn't work
If I import neovim with less than version 0.4 of msgpack installed, I get this stack trace:
```
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/chartdev/venvs/chartio/local/lib/python2.7/site-packages/neovim/__init__.py", line 8, in <module>
from .api import DecodeHook, Nvim, SessionHook
File "/home/chartdev/venvs/chartio/local/lib/python2.7/site-packages/neovim/api/__init__.py", line 9, in <module>
from .nvim import Nvim, NvimError
File "/home/chartdev/venvs/chartio/local/lib/python2.7/site-packages/neovim/api/nvim.py", line 4, in <module>
from msgpack import ExtType
ImportError: cannot import name ExtType
```
0.4.0 seems to work. | import platform
import sys
from setuptools import setup
install_requires = [
'msgpack-python>=0.4.0',
]
if sys.version_info < (3, 4):
# trollius is just a backport of 3.4 asyncio module
install_requires.append('trollius')
if not platform.python_implementation() == 'PyPy':
# pypy already includes an implementation of the greenlet module
install_requires.append('greenlet')
setup(name='neovim',
version='0.0.23',
description='Python client to neovim',
url='http://github.com/neovim/python-client',
download_url='https://github.com/neovim/python-client/archive/0.0.23.tar.gz',
author='Thiago de Arruda',
author_email='tpadilha84@gmail.com',
license='MIT',
packages=['neovim', 'neovim.api', 'neovim.msgpack_rpc',
'neovim.msgpack_rpc.event_loop', 'neovim.plugins'],
install_requires=install_requires,
zip_safe=False)
| import platform
import sys
from setuptools import setup
install_requires = [
'msgpack-python',
]
if sys.version_info < (3, 4):
# trollius is just a backport of 3.4 asyncio module
install_requires.append('trollius')
if not platform.python_implementation() == 'PyPy':
# pypy already includes an implementation of the greenlet module
install_requires.append('greenlet')
setup(name='neovim',
version='0.0.23',
description='Python client to neovim',
url='http://github.com/neovim/python-client',
download_url='https://github.com/neovim/python-client/archive/0.0.23.tar.gz',
author='Thiago de Arruda',
author_email='tpadilha84@gmail.com',
license='MIT',
packages=['neovim', 'neovim.api', 'neovim.msgpack_rpc',
'neovim.msgpack_rpc.event_loop', 'neovim.plugins'],
install_requires=install_requires,
zip_safe=False)
|
Change dividend for all benchmark tests to 1024 | package main
import (
"testing"
)
func BenchmarkDivisionMod(b *testing.B) {
d := NewDivisionMod(1024)
// run the dividable check function b.N times
for n := 0; n < b.N; n++ {
d.IsRestlessDividable(uint64(n))
}
}
func BenchmarkDivisionPow2(b *testing.B) {
d := NewDivisionPow2(1024)
// run the dividable check function b.N times
for n := 0; n < b.N; n++ {
d.IsRestlessDividable(uint64(n))
}
}
func BenchmarkZeroremainderUint32(b *testing.B) {
d := NewZeroremainderUint32(1024)
// run the dividable check function b.N times
for n := 0; n < b.N; n++ {
d.IsRestlessDividable(uint64(n))
}
}
func BenchmarkZeroremainderUint64(b *testing.B) {
d := NewZeroremainderUint64(1024)
// run the dividable check function b.N times
for n := 0; n < b.N; n++ {
d.IsRestlessDividable(uint64(n))
}
}
| package main
import (
"testing"
)
func BenchmarkDivisionMod(b *testing.B) {
d := NewDivisionMod(1000)
// run the dividable check function b.N times
for n := 0; n < b.N; n++ {
d.IsRestlessDividable(uint64(n))
}
}
func BenchmarkDivisionPow2(b *testing.B) {
d := NewDivisionPow2(1024)
// run the dividable check function b.N times
for n := 0; n < b.N; n++ {
d.IsRestlessDividable(uint64(n))
}
}
func BenchmarkZeroremainderUint32(b *testing.B) {
d := NewZeroremainderUint32(1000)
// run the dividable check function b.N times
for n := 0; n < b.N; n++ {
d.IsRestlessDividable(uint64(n))
}
}
func BenchmarkZeroremainderUint64(b *testing.B) {
d := NewZeroremainderUint64(1000)
// run the dividable check function b.N times
for n := 0; n < b.N; n++ {
d.IsRestlessDividable(uint64(n))
}
}
|
/jserror: Refactor to handle errors better | 'use strict';
const log4js = require('log4js');
const clientLogger = log4js.getLogger('client');
const formidable = require('formidable');
const apiHandler = require('../../handler/APIHandler');
exports.expressCreateServer = (hookName, args, cb) => {
// The Etherpad client side sends information about how a disconnect happened
args.app.post('/ep/pad/connection-diagnostic-info', (req, res) => {
new formidable.IncomingForm().parse(req, (err, fields, files) => {
clientLogger.info(`DIAGNOSTIC-INFO: ${fields.diagnosticInfo}`);
res.end('OK');
});
});
const parseJserrorForm = async (req) => await new Promise((resolve, reject) => {
const form = new formidable.IncomingForm();
form.on('error', (err) => reject(err));
form.parse(req, (err, fields) => err != null ? reject(err) : resolve(fields.errorInfo));
});
// The Etherpad client side sends information about client side javscript errors
args.app.post('/jserror', (req, res, next) => {
(async () => {
const data = JSON.parse(await parseJserrorForm(req));
clientLogger.warn(`${data.msg} --`, data);
res.end('OK');
})().catch((err) => next(err || new Error(err)));
});
// Provide a possibility to query the latest available API version
args.app.get('/api', (req, res) => {
res.json({currentVersion: apiHandler.latestApiVersion});
});
return cb();
};
| 'use strict';
const log4js = require('log4js');
const clientLogger = log4js.getLogger('client');
const formidable = require('formidable');
const apiHandler = require('../../handler/APIHandler');
exports.expressCreateServer = (hookName, args, cb) => {
// The Etherpad client side sends information about how a disconnect happened
args.app.post('/ep/pad/connection-diagnostic-info', (req, res) => {
new formidable.IncomingForm().parse(req, (err, fields, files) => {
clientLogger.info(`DIAGNOSTIC-INFO: ${fields.diagnosticInfo}`);
res.end('OK');
});
});
// The Etherpad client side sends information about client side javscript errors
args.app.post('/jserror', (req, res) => {
new formidable.IncomingForm().parse(req, (err, fields, files) => {
let data;
try {
data = JSON.parse(fields.errorInfo);
} catch (e) {
return res.end();
}
clientLogger.warn(`${data.msg} --`, data);
res.end('OK');
});
});
// Provide a possibility to query the latest available API version
args.app.get('/api', (req, res) => {
res.json({currentVersion: apiHandler.latestApiVersion});
});
return cb();
};
|
Add a specific test for the updatesfromdict hard coded foreignkey fields | from django.test import TestCase
from django.db import models as djangomodels
from opal.models import UpdatesFromDictMixin
class UpdatesFromDictMixinTest(TestCase):
class TestDiagnosis(UpdatesFromDictMixin, djangomodels.Model):
condition = djangomodels.CharField(max_length=255, blank=True, null=True)
provisional = djangomodels.BooleanField()
details = djangomodels.CharField(max_length=255, blank=True)
date_of_diagnosis = djangomodels.DateField(blank=True, null=True)
def test_get_fieldnames_to_serialise(self):
names = self.TestDiagnosis._get_fieldnames_to_serialize()
expected = ['id', 'condition', 'provisional', 'details', 'date_of_diagnosis']
self.assertEqual(expected, names)
def test_get_named_foreign_key_fields(self):
for name in ['patient_id', 'episode_id', 'gp_id', 'nurse_id']:
self.assertEqual(djangomodels.ForeignKey,
self.TestDiagnosis._get_field_type(name))
| from django.test import TestCase
from django.db import models as djangomodels
from opal.models import UpdatesFromDictMixin
class UpdatesFromDictMixinTest(TestCase):
class TestDiagnosis(UpdatesFromDictMixin, djangomodels.Model):
condition = djangomodels.CharField(max_length=255, blank=True, null=True)
provisional = djangomodels.BooleanField()
details = djangomodels.CharField(max_length=255, blank=True)
date_of_diagnosis = djangomodels.DateField(blank=True, null=True)
def test_get_fieldnames_to_serialise(self):
names = self.TestDiagnosis._get_fieldnames_to_serialize()
expected = ['id', 'condition', 'provisional', 'details', 'date_of_diagnosis']
self.assertEqual(expected, names)
|
Use database number from redis url if available. | import json
import urlparse
from flask import Flask, make_response
from flask.ext.restful import Api
from flask_peewee.db import Database
import redis
from redash import settings, utils
__version__ = '0.3.2'
app = Flask(__name__,
template_folder=settings.STATIC_ASSETS_PATH,
static_folder=settings.STATIC_ASSETS_PATH,
static_path='/static')
api = Api(app)
# configure our database
settings.DATABASE_CONFIG.update({'threadlocals': True})
app.config['DATABASE'] = settings.DATABASE_CONFIG
db = Database(app)
from redash.authentication import setup_authentication
auth = setup_authentication(app)
@api.representation('application/json')
def json_representation(data, code, headers=None):
resp = make_response(json.dumps(data, cls=utils.JSONEncoder), code)
resp.headers.extend(headers or {})
return resp
redis_url = urlparse.urlparse(settings.REDIS_URL)
if redis_url.path:
redis_db = redis_url.path[1]
else:
redis_db = 0
redis_connection = redis.StrictRedis(host=redis_url.hostname, port=redis_url.port, db=redis_db, password=redis_url.password)
from redash import data
data_manager = data.Manager(redis_connection, db)
from redash import controllers | import json
import urlparse
from flask import Flask, make_response
from flask.ext.restful import Api
from flask_peewee.db import Database
import redis
from redash import settings, utils
__version__ = '0.3.2'
app = Flask(__name__,
template_folder=settings.STATIC_ASSETS_PATH,
static_folder=settings.STATIC_ASSETS_PATH,
static_path='/static')
api = Api(app)
# configure our database
settings.DATABASE_CONFIG.update({'threadlocals': True})
app.config['DATABASE'] = settings.DATABASE_CONFIG
db = Database(app)
from redash.authentication import setup_authentication
auth = setup_authentication(app)
@api.representation('application/json')
def json_representation(data, code, headers=None):
resp = make_response(json.dumps(data, cls=utils.JSONEncoder), code)
resp.headers.extend(headers or {})
return resp
redis_url = urlparse.urlparse(settings.REDIS_URL)
redis_connection = redis.StrictRedis(host=redis_url.hostname, port=redis_url.port, db=0, password=redis_url.password)
from redash import data
data_manager = data.Manager(redis_connection, db)
from redash import controllers |
Revert "Temporarily removed the first line from the survey-complete page"
This reverts commit 803aa203 | <?php if ($valid_token) { ?>
<?=heading('Hartelijk dank voor het invullen van deze vragenlijst.', 2); ?>
<p>
Hartelijk dank voor het invullen van de vragenlijst <em><?=$test_name; ?></em>.
Uw antwoorden zijn opgeslagen en worden met de grootste zorg behandeld.
</p>
<p>
Als u verder nog vragen heeft over de vragenlijst, neem dan contact op met het Babylab Utrecht via <?=mailto(BABYLAB_MANAGER_EMAIL); ?>.
</p>
<p>
U kunt het scherm nu afsluiten of doorklikken naar onze website:
<?=anchor('https://babylab.wp.hum.uu.nl', 'https://babylab.wp.hum.uu.nl'); ?>.
</p>
<?php
}
else
{
show_404();
}
?>
| <?php if ($valid_token) { ?>
<?=heading('Hartelijk dank voor het invullen van deze vragenlijst.', 2); ?>
<p>
<!-- Hartelijk dank voor het invullen van de vragenlijst <em>--><?//=$test_name; ?><!--</em>. -->
Uw antwoorden zijn opgeslagen en worden met de grootste zorg behandeld.
</p>
<p>
Als u verder nog vragen heeft over de vragenlijst, neem dan contact op met het Babylab Utrecht via <?=mailto(BABYLAB_MANAGER_EMAIL); ?>.
</p>
<p>
U kunt het scherm nu afsluiten of doorklikken naar onze website:
<?=anchor('https://babylab.wp.hum.uu.nl', 'https://babylab.wp.hum.uu.nl'); ?>.
</p>
<?php
}
else
{
show_404();
}
?>
|
Add back a newline to have two rows between class definitions. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Flask application default config:
# http://flask.pocoo.org/docs/config/#configuring-from-files
# https://github.com/mbr/flask-appconfig
project_name = u'Ninhursag'
class Default(object):
APP_NAME = project_name
DEBUG = False
TESTING = False
# Servers and URLs
SERVER_NAME = 'localhost:5000'
# Authentication etc
# To generate: import os; os.urandom(24)
SECRET_KEY = 'some-secret-key'
CSRF_ENABLED = True
# API
API_SERVER = SERVER_NAME
API_TOKEN = 'some-api-token'
# Flat pages
FLATPAGES_ROOT = 'pages/flat'
FLATPAGES_EXTENSION = '.md'
FLATPAGES_MARKDOWN_EXTENSIONS = []
class Dev(Default):
APP_NAME = project_name + ' (dev)'
DEBUG = True
SERVER_NAME = '0.0.0.0:5000'
API_SERVER = SERVER_NAME
class Testing(Default):
TESTING = True
CSRF_ENABLED = False
class Production(Default):
pass
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Flask application default config:
# http://flask.pocoo.org/docs/config/#configuring-from-files
# https://github.com/mbr/flask-appconfig
project_name = u'Ninhursag'
class Default(object):
APP_NAME = project_name
DEBUG = False
TESTING = False
# Servers and URLs
SERVER_NAME = 'localhost:5000'
# Authentication etc
# To generate: import os; os.urandom(24)
SECRET_KEY = 'some-secret-key'
CSRF_ENABLED = True
# API
API_SERVER = SERVER_NAME
API_TOKEN = 'some-api-token'
# Flat pages
FLATPAGES_ROOT = 'pages/flat'
FLATPAGES_EXTENSION = '.md'
FLATPAGES_MARKDOWN_EXTENSIONS = []
class Dev(Default):
APP_NAME = project_name + ' (dev)'
DEBUG = True
SERVER_NAME = '0.0.0.0:5000'
API_SERVER = SERVER_NAME
class Testing(Default):
TESTING = True
CSRF_ENABLED = False
class Production(Default):
pass
|
Optimize only main.js, skip all other files
The directory does not need to be optimized because only main.js is
loaded by the end user. This saves compilation time for JS/CSS. | ({
appDir: './app',
baseUrl: 'scripts',
mainConfigFile: './app/scripts/main.js',
dir: './build',
pragmasOnSave: {
excludeCoffeeScript: true,
excludeTpl: true
},
excludeShallow: [
'css-builder',
'less-builder',
'lessc-server'
],
findNestedDependencies: true,
optimize: 'uglify',
optimizeCss: 'standard.keepLines',
fileExclusionRegExp: /^\.|spec|tests/,
generateSourceMaps: false,
preserveLicenseComments: false,
skipDirOptimize: true,
modules: [
{
name: 'main',
include: [
'styles'
],
excludeShallow: [
'spec_runner'
]
},
{
name: 'styles'
}
],
uglify: {
beautify: false
}
})
| ({
appDir: './app',
baseUrl: 'scripts',
mainConfigFile: './app/scripts/main.js',
dir: './build',
pragmasOnSave: {
excludeCoffeeScript: true,
excludeTpl: true
},
excludeShallow: [
'css-builder',
'less-builder',
'lessc-server'
],
findNestedDependencies: true,
optimize: 'uglify',
optimizeCss: 'standard.keepLines',
fileExclusionRegExp: /^\.|spec|tests/,
generateSourceMaps: false,
preserveLicenseComments: false,
modules: [
{
name: 'main',
include: [
'styles'
],
excludeShallow: [
'spec_runner'
]
},
{
name: 'styles'
}
],
uglify: {
beautify: false
}
})
|
Fix build process on linux | var isWindows = /^win/.test(process.platform)
if(isWindows){
spawn = require('child_process').exec
spawn(__dirname + "/node_modules/.bin/cjsx.cmd -o build -cw source")
spawn(__dirname + "/node_modules/.bin/cjsx.cmd -cw test/index.cjsx")
spawn(__dirname + "/node_modules/.bin/watchify.cmd test/index.js -o test/bundle.js")
}
else{
spawn = require('child_process').spawn
spawn("./node_modules/.bin/cjsx", ["-o", "build", "-cw", "source"], {stdio:'inherit', stderr:'inherit'})
spawn("./node_modules/.bin/cjsx", ["-cw", "test/index.cjsx"], {stdio:'inherit', stderr:'inherit'})
spawn("./node_modules/.bin/watchify", ["test/index.js", "-o", "test/bundle.js"], {stdio:'inherit', stderr:'inherit'})
}
| var isWindows = /^win/.test(process.platform)
if(isWindows){
spawn = require('child_process').exec
spawn(__dirname + "/node_modules/.bin/cjsx.cmd -o build -cw source")
spawn(__dirname + "/node_modules/.bin/cjsx.cmd -cw test/index.cjsx")
spawn(__dirname + "/node_modules/.bin/watchify.cmd test/index.js -o test/bundle.js")
}
else{
spawn = require('child_process').spawn
spawn(__dirname + "/node_modules/.bin/cjsx -o build -cw source", {stdio:'inherit', stderr:'inherit'})
spawn(__dirname + "/node_modules/.bin/cjsx -cw test/index.cjsx", {stdio:'inherit', stderr:'inherit'})
spawn(__dirname + "/node_modules/.bin/watchify test/index.js -o test/bundle.js", {stdio:'inherit', stderr:'inherit'})
}
|
Rename fqdn to fqname in DialogEditorHttpService
https://bugzilla.redhat.com/show_bug.cgi?id=1553846 | ManageIQ.angular.app.service('DialogEditorHttp', ['$http', 'API', function($http, API) {
this.loadDialog = function(id) {
return API.get('/api/service_dialogs/' + id + '?attributes=content,buttons,label');
};
this.saveDialog = function(id, action, data) {
return API.post('/api/service_dialogs' + id, {
action: action,
resource: data,
}, {
skipErrors: [400],
});
};
this.treeSelectorLoadData = function(fqname) {
var url = '/tree/automate_entrypoint' + (fqname ? '?fqname=' + encodeURIComponent(fqname) : '');
return $http.get(url).then(function(response) {
return response.data;
});
};
this.treeSelectorLazyLoadData = function(node) {
return $http.get('/tree/automate_entrypoint?id=' + encodeURIComponent(node.key)).then(function(response) {
return response.data;
});
};
// Load categories data from API.
this.loadCategories = function() {
return API.get('/api/categories' +
'?expand=resources' +
'&attributes=id,name,description,single_value,children');
};
}]);
| ManageIQ.angular.app.service('DialogEditorHttp', ['$http', 'API', function($http, API) {
this.loadDialog = function(id) {
return API.get('/api/service_dialogs/' + id + '?attributes=content,buttons,label');
};
this.saveDialog = function(id, action, data) {
return API.post('/api/service_dialogs' + id, {
action: action,
resource: data,
}, {
skipErrors: [400],
});
};
this.treeSelectorLoadData = function(fqdn) {
var url = '/tree/automate_entrypoint' + (fqdn ? '?fqdn=' + encodeURIComponent(fqdn) : '');
return $http.get(url).then(function(response) {
return response.data;
});
};
this.treeSelectorLazyLoadData = function(node) {
return $http.get('/tree/automate_entrypoint?id=' + encodeURIComponent(node.key)).then(function(response) {
return response.data;
});
};
// Load categories data from API.
this.loadCategories = function() {
return API.get('/api/categories' +
'?expand=resources' +
'&attributes=id,name,description,single_value,children');
};
}]);
|
Move get user out of loop
It's good practice to get not changing data before loop | <?php
class Kwc_Editable_ComponentsModel extends Kwf_Model_Data_Abstract
{
public function __construct(array $config = array())
{
$data = array();
$components = Kwf_Component_Data_Root::getInstance()
->getComponentsByClass(array('Kwc_Editable_Component', 'Kwc_Editable_Trl_Component'));
$user = Kwf_Registry::get('userModel')->getAuthedUser();
foreach ($components as $c) {
if (Kwf_Registry::get('acl')->getComponentAcl()->isAllowed($user, $c)) {
$data[] = array(
'id' => $c->dbId,
'name' => $c->getComponent()->getNameForEdit(),
'content_component_class' => $c->getChildComponent('-content')->componentClass,
);
}
}
$this->_data = $data;
parent::__construct($config);
}
}
| <?php
class Kwc_Editable_ComponentsModel extends Kwf_Model_Data_Abstract
{
public function __construct(array $config = array())
{
$data = array();
$components = Kwf_Component_Data_Root::getInstance()
->getComponentsByClass(array('Kwc_Editable_Component', 'Kwc_Editable_Trl_Component'));
foreach ($components as $c) {
$user = Kwf_Registry::get('userModel')->getAuthedUser();
if (Kwf_Registry::get('acl')->getComponentAcl()->isAllowed($user, $c)) {
$data[] = array(
'id' => $c->dbId,
'name' => $c->getComponent()->getNameForEdit(),
'content_component_class' => $c->getChildComponent('-content')->componentClass,
);
}
}
$this->_data = $data;
parent::__construct($config);
}
}
|
Minor: Update errors for other versions of Pyro
git-svn-id: 033d166fe8e629f6cbcd3c0e2b9ad0cffc79b88b@775 3a63a0ee-37fe-0310-a504-e92b6e0a3ba7 | #!/usr/bin/env python
import sys
import Pyro
import Tkinter, tkMessageBox
from VisionEgg.PyroApps.UberClientGUI import client_list, AppWindow
# You can add your own controllers and GUIs to client_list
try:
app_window = AppWindow(client_list=client_list)
except Pyro.errors.PyroError, x:
uber_server_error = 0
if isinstance(x, Pyro.errors.ProtocolError) and str(x) == 'connection failed': # Can't find UberServer running on network
uber_server_error = 1
if isinstance(x, Pyro.errors.NamingError) and str(x) == 'name not found': # Can't find UberServer running on network
uber_server_error = 1
if uber_server_error:
tkMessageBox.showerror("Can't find UberServer","Can't find UberServer running on Pyro network.")
sys.exit(1)
elif str(x) in ["Name Server not responding","connection failed"]:
try:
tkMessageBox.showerror("Can't find Pyro Name Server","Can't find Pyro Name Server on network.")
sys.exit(1)
except:
raise # Can't find Pyro Name Server on network
else:
raise
app_window.winfo_toplevel().wm_iconbitmap()
app_window.pack(expand=1,fill=Tkinter.BOTH)
app_window.winfo_toplevel().title("Vision Egg")
app_window.winfo_toplevel().minsize(1,1)
app_window.mainloop()
| #!/usr/bin/env python
import sys
import Pyro
import Tkinter, tkMessageBox
from VisionEgg.PyroApps.UberClientGUI import client_list, AppWindow
# You can add your own controllers and GUIs to client_list
try:
app_window = AppWindow(client_list=client_list)
except Pyro.errors.ProtocolError, x:
if str(x) == 'connection failed': # Can't find UberServer running on network
try:
tkMessageBox.showerror("Can't find UberServer","Can't find UberServer running on Pyro network.")
sys.exit(1)
except:
raise # Can't find UberServer running on network
else:
raise
except Pyro.errors.PyroError, x:
if str(x) in ["Name Server not responding","connection failed"]:
try:
tkMessageBox.showerror("Can't find Pyro Name Server","Can't find Pyro Name Server on network.")
sys.exit(1)
except:
raise # Can't find Pyro Name Server on network
else:
raise
app_window.winfo_toplevel().wm_iconbitmap()
app_window.pack(expand=1,fill=Tkinter.BOTH)
app_window.winfo_toplevel().title("Vision Egg")
app_window.winfo_toplevel().minsize(1,1)
app_window.mainloop()
|
Split gulp build into parts | var gulp = require("gulp"),
jade = require("gulp-jade"),
minCSS = require("gulp-minify-css"),
minHTML = require("gulp-minify-html"),
react = require("gulp-react"),
uglify = require("gulp-uglify");
gulp.task("build:jade", function () {
gulp.src("src/public/index.jade")
.pipe(jade())
.pipe(minHTML())
.pipe(gulp.dest("dist/public/"));
});
gulp.task("build:jsx", function () {
gulp.src("src/public/jsx/**.jsx")
.pipe(react())
.pipe(uglify({ mangle: false }))
.pipe(gulp.dest("dist/public/js/"));
});
gulp.task("build:css", function () {
gulp.src("src/public/css/**.css")
.pipe(minCSS())
.pipe(gulp.dest("dist/public/css/"));
});
gulp.task("build:serv", function () {
gulp.src("src/app.js")
.pipe(uglify({ mangle: false }))
.pipe(gulp.dest("dist/"));
});
gulp.task("watch", function () {
gulp.watch("src/public/index.jade", ["build:jade"]);
gulp.watch("src/public/jsx/**.jsx", ["build:jsx"]);
gulp.watch("src/public/css/**.css", ["build:css"]);
gulp.watch("src/app.js", ["build:serv"]);
}); | var gulp = require("gulp"),
jade = require("gulp-jade"),
minCSS = require("gulp-minify-css"),
minHTML = require("gulp-minify-html"),
react = require("gulp-react"),
uglify = require("gulp-uglify");
gulp.task("build", function () {
gulp.src("src/public/index.jade")
.pipe(jade())
.pipe(minHTML())
.pipe(gulp.dest("dist/public/"));
gulp.src("src/public/jsx/**.jsx")
.pipe(react())
.pipe(uglify({ mangle: false }))
.pipe(gulp.dest("dist/public/js/"));
gulp.src("src/public/css/**.css")
.pipe(minCSS())
.pipe(gulp.dest("dist/public/css/"));
gulp.src("src/app.js")
.pipe(uglify({ mangle: false }))
.pipe(gulp.dest("dist/"));
});
gulp.task("watch", function () {
gulp.watch("src/public/index.jade", ["build"]);
gulp.watch("src/public/jsx/**.jsx", ["build"]);
gulp.watch("src/public/css/**.css", ["build"]);
gulp.watch("src/app.js", ["build"]);
}); |
Add missing authorization in some places
Missed the headers count check. | <?php
$authorization = '';
if ($route['authenticated']) {
$authorization .= ' -H "Authorization: Bearer {{token}}"';
if(count($route['headers']) > 0) {
$authorization .= ' \\';
}
}
?>
```bash
curl -X {{$route['methods'][0]}} {{$route['methods'][0] == 'GET' ? '-G ' : ''}}"{{ trim(config('app.docs_url') ?: config('app.url'), '/')}}/{{ ltrim($route['boundUri'], '/') }}" @if(count($route['headers']) || $authorization !== '')\
{!! $authorization !!}
@foreach($route['headers'] as $header => $value)
-H "{{$header}}: {{$value}}"@if(! ($loop->last) || ($loop->last && count($route['bodyParameters']))) \
@endif
@endforeach
@endif
@if(count($route['cleanBodyParameters']))
-d '{!! json_encode($route['cleanBodyParameters']) !!}'
@endif
```
| <?php
$authorization = '';
if ($route['authenticated']) {
$authorization .= ' -H "Authorization: Bearer {{token}}"';
if(count($route['headers']) > 0) {
$authorization .= ' \\';
}
}
?>
```bash
curl -X {{$route['methods'][0]}} {{$route['methods'][0] == 'GET' ? '-G ' : ''}}"{{ trim(config('app.docs_url') ?: config('app.url'), '/')}}/{{ ltrim($route['boundUri'], '/') }}" @if(count($route['headers']))\
{!! $authorization !!}
@foreach($route['headers'] as $header => $value)
-H "{{$header}}: {{$value}}"@if(! ($loop->last) || ($loop->last && count($route['bodyParameters']))) \
@endif
@endforeach
@endif
@if(count($route['cleanBodyParameters']))
-d '{!! json_encode($route['cleanBodyParameters']) !!}'
@endif
```
|
Add Seven Hour mock data. | const CurrentData = {
display_location: {
full: 'Den'
},
temp_f: 70
};
const ForecastData = {
txt_forecast: {
forecastday:[{
title: 'Monday',
fcttext: 'Clear all day',
}]
},
simpleforecast: {
forecastday:[{
conditions: 'Clear',
high: {
fahrenheit: 70,
},
low: {
fahrenheit: 32,
}
}]
}
};
const TenDay = {
simpleforecast: {
forecastday: [{
date: {
weekday_short: 'Tue'
},
high: {
fahrenheit: 65
},
low: {
fahrenheit: 28
}
},
{
date: {
weekday_short: 'Wed'
},
high: {
fahrenheit: 58
},
low: {
fahrenheit: 20
}
}]
}
};
const SevenHour = [{
FCTTIME: {
civil:"5:00PM"
},
temp: {
english: "42"
}
}]
export default { CurrentData, ForecastData, TenDay, SevenHour };
| const CurrentData = {
display_location: {
full: 'Den'
},
temp_f: 70
};
const ForecastData = {
txt_forecast: {
forecastday:[{
title: 'Monday',
fcttext: 'Clear all day',
}]
},
simpleforecast: {
forecastday:[{
conditions: 'Clear',
high: {
fahrenheit: 70,
},
low: {
fahrenheit: 32,
}
}]
}
};
const TenDay = {
simpleforecast: {
forecastday: [{
date: {
weekday_short: 'Tue'
},
high: {
fahrenheit: 65
},
low: {
fahrenheit: 28
}
},
{
date: {
weekday_short: 'Wed'
},
high: {
fahrenheit: 58
},
low: {
fahrenheit: 20
}
}]
}
};
export default { CurrentData, ForecastData, TenDay };
|
Fix to validate schema function | from jsonschema import validate, ValidationError
from flask import current_app
import json
import os
def validate_schema(data, schema_name):
"""
Validate the provided data against the provided JSON schema.
:param data: JSON data to be validated
:param schema_name: Name of the schema
:return: Boolean
"""
with open(os.path.join(current_app.config['JSON_SCHEMA_DIRECTORY'], schema_name + '.schema'), 'r') as fp:
schema = json.load(fp)
try:
validate(data, schema)
return True
except ValidationError as e:
current_app.logger.info("Failed to validate {}\n{}".format(json.dumps(data), e))
return False
| from jsonschema import validate, ValidationError
from flask import current_app
import json
import os
def validate_schema(data, schema_name):
"""
Validate the provided data against the provided JSON schema.
:param data: JSON data to be validated
:param schema_name: Name of the schema
:return: Boolean
"""
with open(os.path.join(current_app.config['JSON_SCHEMA_DIRECTORY'], schema_name, '.json'), 'r') as fp:
schema = json.load(fp)
try:
validate(data, schema)
return True
except ValidationError as e:
current_app.logger.info("Failed to validate {}\n{}".format(json.dumps(data), e))
return False
|
Disable SQLALCHEMY_TRACK_MODIFICATIONS to fix deprecation warning and meet recommendation | from flask import Flask
from flask_talisman import Talisman
from flask_seasurf import SeaSurf
from redditflair.redditflair import redditflair, limiter
from redissession import RedisSessionInterface
from database import db, User, Specials
import os.path
content_security_policy = {
'script-src': '\'unsafe-inline\'',
'style-src': '\'self\''
}
def setupApp():
app = Flask(__name__)
# HTTP security headers
Talisman(app, content_security_policy=content_security_policy)
# CSRF library
SeaSurf(app)
# Limiter
limiter.init_app(app)
# SQLAlchemy
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///cowserver.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)
# Blueprints
app.register_blueprint(redditflair)
# Redis Session Interface
app.session_interface = RedisSessionInterface()
return app
def setupDatabase():
if not os.path.isfile('cowserver.db'):
with app.app_context():
db.create_all()
app = setupApp()
setupDatabase()
if __name__ == "__main__":
app.run(host='0.0.0.0')
| from flask import Flask
from flask_talisman import Talisman
from flask_seasurf import SeaSurf
from redditflair.redditflair import redditflair, limiter
from redissession import RedisSessionInterface
from database import db, User, Specials
import os.path
content_security_policy = {
'script-src': '\'unsafe-inline\'',
'style-src': '\'self\''
}
def setupApp():
app = Flask(__name__)
# HTTP security headers
Talisman(app, content_security_policy=content_security_policy)
# CSRF library
SeaSurf(app)
# Limiter
limiter.init_app(app)
# SQLAlchemy
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///cowserver.db'
db.init_app(app)
# Blueprints
app.register_blueprint(redditflair)
# Redis Session Interface
app.session_interface = RedisSessionInterface()
return app
def setupDatabase():
if not os.path.isfile('cowserver.db'):
with app.app_context():
db.create_all()
app = setupApp()
setupDatabase()
if __name__ == "__main__":
app.run(host='0.0.0.0')
|
Fix getting category's descendants before save | from django import forms
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _
from mptt.forms import TreeNodeChoiceField
from unidecode import unidecode
from ...product.models import Category
class CategoryForm(forms.ModelForm):
parent = TreeNodeChoiceField(queryset=Category.objects.all(),
required=False)
class Meta:
model = Category
exclude = ['slug']
def clean_parent(self):
parent = self.cleaned_data['parent']
if parent:
if parent == self.instance:
raise forms.ValidationError(_('A category may not be made a child of itself'))
if self.instance in parent.get_ancestors():
raise forms.ValidationError(_('A category may not be made a child of any of its descendants.'))
return parent
def save(self, commit=True):
self.instance.slug = slugify(unidecode(self.instance.name))
super(CategoryForm, self).save(commit=commit)
self.instance.set_hidden_descendants(self.cleaned_data['hidden'])
return self.instance
| from django import forms
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _
from mptt.forms import TreeNodeChoiceField
from unidecode import unidecode
from ...product.models import Category
class CategoryForm(forms.ModelForm):
parent = TreeNodeChoiceField(queryset=Category.objects.all(),
required=False)
class Meta:
model = Category
exclude = ['slug']
def clean_parent(self):
parent = self.cleaned_data['parent']
if parent:
if parent == self.instance:
raise forms.ValidationError(_('A category may not be made a child of itself'))
if self.instance in parent.get_ancestors():
raise forms.ValidationError(_('A category may not be made a child of any of its descendants.'))
return parent
def save(self, commit=True):
self.instance.slug = slugify(unidecode(self.instance.name))
self.instance.set_hidden_descendants(self.cleaned_data['hidden'])
return super(CategoryForm, self).save(commit=commit)
|
Fix mixin error
Add an empty string alternative to avoid mixin error when a form field is left empty during submission | import Ember from 'ember';
export default Ember.Component.extend({
// Hide the form
addNewQuestion: false,
actions: {
// Show the form
showQuestionForm() {
this.set('addNewQuestion', true)
},
saveQuestion() {
// Get the user input and store them
var params = {
authorQuestion: this.get('authorQuestion') ? this.get('authorQuestion') : "",
questionTitle: this.get('questionTitle') ? this.get('questionTitle') : "",
contentQuestion: this.get('contentQuestion') ? this.get('contentQuestion') : "",
};
// Hide the form
this.set('addNewQuestion', false);
// Send action to route handler to create and save the new question
this.sendAction('saveQuestion', params);
},
}
});
| import Ember from 'ember';
export default Ember.Component.extend({
// Hide the form
addNewQuestion: false,
actions: {
// Show the form
showQuestionForm() {
this.set('addNewQuestion', true)
},
saveQuestion() {
// Get the user input and store them
var params = {
authorQuestion: this.get('authorQuestion'),
questionTitle: this.get('questionTitle'),
contentQuestion: this.get('contentQuestion')
};
// Hide the form
this.set('addNewQuestion', false);
// Send action to route handler to create and save the new question
this.sendAction('saveQuestion', params);
},
}
});
|
Replace extra deps with sync packages | from setuptools import setup, find_packages
classifiers = [
'License :: OSI Approved :: BSD License',
'Intended Audience :: Developers',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Environment :: Web Environment',
'Development Status :: 4 - Beta',
]
extras_require = {'sa': ['sqlalchemy>=0.9']}
extras_require['postgres'] = ['psycopg2>=2.5.2', *extras_require['sa']]
extras_require['mysql'] = ['PyMySQL>=0.7.5', *extras_require['sa']]
setup(name='aio_manager',
use_scm_version=True,
description='Script manager for aiohttp.',
long_description=('Script manager for aiohttp.\n'
'Inspired by Flask-script. Allows to write external scripts. '),
classifiers=classifiers,
platforms=['POSIX'],
author='Roman Rader',
author_email='antigluk@gmail.com',
url='https://github.com/rrader/aio_manager',
license='BSD',
packages=find_packages(),
install_requires=['aiohttp', 'colorama'],
extras_require=extras_require,
setup_requires=['setuptools_scm'],
provides=['aio_manager'],
include_package_data=True,
test_suite='tests.test_manager')
| from setuptools import setup, find_packages
classifiers = [
'License :: OSI Approved :: BSD License',
'Intended Audience :: Developers',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Environment :: Web Environment',
'Development Status :: 4 - Beta',
]
extras_require = {'sa': ['sqlalchemy>=0.9']}
extras_require['postgres'] = ['aiopg', *extras_require['sa']]
extras_require['mysql'] = ['aiomysql', *extras_require['sa']]
setup(name='aio_manager',
use_scm_version=True,
description='Script manager for aiohttp.',
long_description=('Script manager for aiohttp.\n'
'Inspired by Flask-script. Allows to write external scripts. '),
classifiers=classifiers,
platforms=['POSIX'],
author='Roman Rader',
author_email='antigluk@gmail.com',
url='https://github.com/rrader/aio_manager',
license='BSD',
packages=find_packages(),
install_requires=['aiohttp', 'colorama'],
extras_require=extras_require,
setup_requires=['setuptools_scm'],
provides=['aio_manager'],
include_package_data=True,
test_suite='tests.test_manager')
|
[FIX] website_product_supplier: Add images key in manifest file | # -*- coding: utf-8 -*-
# (c) 2015 Antiun Ingeniería S.L. - Sergio Teruel
# (c) 2015 Antiun Ingeniería S.L. - Carlos Dauden
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
'name': "Website Product Supplier",
'category': 'Website',
'version': '8.0.1.0.0',
'depends': [
'website_sale',
'website_portal_purchase',
],
'data': [
'security/ir.model.access.csv',
'views/product_supplier_view.xml',
'views/website_portal.xml',
'views/assets.xml',
'security/website_product_supplier_security.xml',
],
'images': [],
'qweb': ['static/src/xml/*.xml'],
'author': 'Antiun Ingeniería S.L., '
'Incaser Informatica S.L., '
'Odoo Community Association (OCA)',
'website': 'http://www.antiun.com',
'license': 'AGPL-3',
'installable': True,
}
| # -*- coding: utf-8 -*-
# (c) 2015 Antiun Ingeniería S.L. - Sergio Teruel
# (c) 2015 Antiun Ingeniería S.L. - Carlos Dauden
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
'name': "Website Product Supplier",
'category': 'Website',
'version': '8.0.1.0.0',
'depends': [
'website_sale',
'website_portal_purchase',
],
'data': [
'security/ir.model.access.csv',
'views/product_supplier_view.xml',
'views/website_portal.xml',
'views/assets.xml',
'security/website_product_supplier_security.xml',
],
'qweb': ['static/src/xml/*.xml'],
'author': 'Antiun Ingeniería S.L., '
'Incaser Informatica S.L., '
'Odoo Community Association (OCA)',
'website': 'http://www.antiun.com',
'license': 'AGPL-3',
'installable': True,
}
|
Make DataFrame available to module user | #! /usr/bin/env python2.7
"""Avoid some boilerplate rpy2 usage code with helpers.
Mostly I wrote this so that I can use xyplot without having
to remember a lot of details.
"""
import click
from rpy2.robjects import DataFrame, Formula, globalenv
from rpy2.robjects.packages import importr
grdevices = importr('grDevices')
lattice = importr('lattice')
rprint = globalenv.get("print")
def xyplot(formula, data, **kwargs):
if not isinstance(formula, Formula):
formula = Formula(formula)
plot = lattice.xyplot(
formula, data, **kwargs)
rprint(plot)
@click.command()
def main():
import numpy as np
from rpy2.robjects import numpy2ri
numpy2ri.activate()
x = np.random.random_integers(0, 100, 100)
x.sort()
y = np.square(x)
xyplot('y ~ x', DataFrame({'x': x, 'y': y}))
raw_input('Hit enter to exit.')
grdevices.dev_off()
if __name__ == '__main__':
main()
| #! /usr/bin/env python2.7
"""Avoid some boilerplate rpy2 usage code with helpers.
Mostly I wrote this so that I can use xyplot without having
to remember a lot of details.
"""
import click
from rpy2.robjects import Formula, globalenv
from rpy2.robjects.packages import importr
grdevices = importr('grDevices')
lattice = importr('lattice')
rprint = globalenv.get("print")
def xyplot(formula, data, **kwargs):
if not isinstance(formula, Formula):
formula = Formula(formula)
plot = lattice.xyplot(
formula, data, **kwargs)
rprint(plot)
@click.command()
def main():
import numpy as np
from rpy2.robjects import numpy2ri
numpy2ri.activate()
from rpy2.robjects import DataFrame
x = np.random.random_integers(0, 100, 100)
x.sort()
y = np.square(x)
xyplot('y ~ x', DataFrame({'x': x, 'y': y}))
raw_input('Hit enter to exit.')
grdevices.dev_off()
if __name__ == '__main__':
main()
|
Use getDeclaredField to access Unsafe
getField() only gets public fields :( | package net.md_5.bungee.event;
import sun.misc.Unsafe;
import java.lang.reflect.Field;
public class UnsafeUtils {
private UnsafeUtils() {}
private static final Unsafe UNSAFE;
static {
Unsafe unsafe;
try {
Class c = Class.forName("sun.misc.Unsafe");
Field f = c.getDeclaredField("theUnsafe");
f.setAccessible(true);
unsafe = (Unsafe) f.get(null);
} catch (ClassNotFoundException | NoSuchFieldException | SecurityException e) {
unsafe = null;
} catch (IllegalAccessException e) {
throw new AssertionError(e);
}
UNSAFE = unsafe;
}
public static boolean isUnsafeSupported() {
return UNSAFE != null;
}
public static Unsafe getUnsafe() {
return UNSAFE;
}
}
| package net.md_5.bungee.event;
import sun.misc.Unsafe;
import java.lang.reflect.Field;
public class UnsafeUtils {
private UnsafeUtils() {}
private static final Unsafe UNSAFE;
static {
Unsafe unsafe;
try {
Class c = Class.forName("sun.misc.Unsafe");
Field f = c.getField("theUnsafe");
f.setAccessible(true);
unsafe = (Unsafe) f.get(null);
} catch (ClassNotFoundException | NoSuchFieldException | SecurityException e) {
unsafe = null;
} catch (IllegalAccessException e) {
throw new AssertionError(e);
}
UNSAFE = unsafe;
}
public static boolean isUnsafeSupported() {
return UNSAFE != null;
}
public static Unsafe getUnsafe() {
return UNSAFE;
}
}
|
Modify camera angle from 105 to 115 degrees. | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.stuy.subsystems;
import edu.stuy.RobotMap;
import edu.wpi.first.wpilibj.Servo;
import edu.wpi.first.wpilibj.command.Subsystem;
/**
*
* @author Yulli
*/
public class Camera extends Subsystem {
// Put methods for controlling this subsystem
// here. Call these from Commands.
private static final int LOWER_ANGLE = 115;
private static final int UPPER_ANGLE = 180;
Servo camServo;
public Camera(){
camServo = new Servo(RobotMap.CAMERA_SERVO);
}
public void initDefaultCommand() {
// Set the default command for a subsystem here.
//setDefaultCommand(new MySpecialCommand());
}
public void switchView(boolean down){
if(down){
camServo.setAngle(LOWER_ANGLE);
}
else {
camServo.setAngle(UPPER_ANGLE);
}
}
}
| /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.stuy.subsystems;
import edu.stuy.RobotMap;
import edu.wpi.first.wpilibj.Servo;
import edu.wpi.first.wpilibj.command.Subsystem;
/**
*
* @author Yulli
*/
public class Camera extends Subsystem {
// Put methods for controlling this subsystem
// here. Call these from Commands.
private static final int LOWER_ANGLE = 105;
private static final int UPPER_ANGLE = 180;
Servo camServo;
public Camera(){
camServo = new Servo(RobotMap.CAMERA_SERVO);
}
public void initDefaultCommand() {
// Set the default command for a subsystem here.
//setDefaultCommand(new MySpecialCommand());
}
public void switchView(boolean down){
if(down){
camServo.setAngle(LOWER_ANGLE);
}
else {
camServo.setAngle(UPPER_ANGLE);
}
}
}
|
Increase the leak test timeout for CI | /* jshint esversion: 6 */
var ssr = require("../lib/");
var helpers = require("./helpers");
var iterate = require("leakage").iterate;
var path = require("path");
var through = require("through2");
describe("Memory leaks", function(){
this.timeout(30000);
before(function(){
this.oldXHR = global.XMLHttpRequest;
global.XMLHttpRequest = helpers.mockXHR(
'[ { "a": "a" }, { "b": "b" } ]');
var render = ssr({
config: "file:" + path.join(__dirname, "tests", "package.json!npm"),
main: "async/index.stache!done-autorender"
});
this.render = function(pth){
return new Promise(function(resolve, reject){
var stream = through(function(buffer){
resolve(buffer);
});
stream.on("error", reject);
render(pth).pipe(stream);
});
};
});
after(function(){
global.XMLHttpRequest = this.oldXHR;
});
it("do not happen", function(done){
iterate(10, () => {
return this.render("/");
})
.then(() => {
done();
})
.catch(done);
});
});
| var ssr = require("../lib/");
var helpers = require("./helpers");
var assert = require("assert");
var iterate = require("leakage").iterate;
var path = require("path");
var through = require("through2");
describe("Memory leaks", function(){
this.timeout(10000);
before(function(){
this.oldXHR = global.XMLHttpRequest;
global.XMLHttpRequest = helpers.mockXHR(
'[ { "a": "a" }, { "b": "b" } ]');
var render = ssr({
config: "file:" + path.join(__dirname, "tests", "package.json!npm"),
main: "async/index.stache!done-autorender"
});
this.render = function(pth){
return new Promise(function(resolve, reject){
var stream = through(function(buffer){
resolve(buffer);
});
stream.on("error", reject);
render(pth).pipe(stream);
});
};
});
after(function(){
global.XMLHttpRequest = this.oldXHR;
});
it("do not happen", function(done){
iterate(10, () => {
return this.render("/");
})
.then(() => {
done();
})
.catch(done);
});
});
|
Add game over when trying to move in game over state
Signed-off-by: Joern Bernhardt <7b85a41a628204b76aba4326273a3ccc74bd009a@campudus.com> | var Board = require('./Board');
var tiles = document.querySelectorAll('.tile');
var board = new Board(tiles);
console.log(board);
board.nextRound();
board.nextRound();
document.onkeydown = onKeyDown;
function onKeyDown(e) {
var event = e || window.event;
event.preventDefault();
event.stopPropagation();
move(event.keyCode);
function move(keyCode) {
var moved = false;
if (keyCode === 37 && board.isMoveXPossible()) {
board.moveLeft();
moved = true;
} else if (keyCode === 38 && board.isMoveYPossible()) {
board.moveUp();
moved = true;
} else if (keyCode === 39 && board.isMoveXPossible()) {
board.moveRight();
moved = true;
} else if (keyCode === 40 && board.isMoveYPossible()) {
board.moveDown();
moved = true;
}
if (moved) {
if (board.isGameOver()) {
alert('game over!');
} else {
board.nextRound();
}
}
}
}
document.board = board;
| var Board = require('./Board');
var tiles = document.querySelectorAll('.tile');
var board = new Board(tiles);
console.log(board);
board.nextRound();
board.nextRound();
document.onkeydown = onKeyDown;
function onKeyDown(e) {
var event = e || window.event;
event.preventDefault();
event.stopPropagation();
move(event.keyCode);
function move(keyCode) {
if (keyCode === 37 && board.isMoveXPossible()) {
board.moveLeft();
board.nextRound();
} else if (keyCode === 38 && board.isMoveYPossible()) {
board.moveUp();
board.nextRound();
} else if (keyCode === 39 && board.isMoveXPossible()) {
board.moveRight();
board.nextRound();
} else if (keyCode === 40 && board.isMoveYPossible()) {
board.moveDown();
board.nextRound();
}
}
console.log(event.keyCode);
}
document.board = board;
|
Reorder arg list, set default for static params | # -*- coding: utf-8 -*-
import copy
def init_abscissa(abscissae, abscissa_name, params = {}):
"""
List of dicts to initialize object w/ calc method
This method generates a list of dicts; each dict is sufficient to initialize an object featuring a calculator method of interest. This list can be thought of as the abscissae of a set of data. Each dict will contain data which remains constant for each calculation, but it nonetheless required to initialize the object. Each dict will also contain a datum which is the abscissa for the calculation and is also required to initialize the object.
:param dict params: Static parameters required to initialize the object featuring the ordinate calculator method.
:param list abscissae: Independent variable also required to initialize object featuring the ordinate calculator method.
:param str abscissa_name: Dictionary key for the abscissa name.
"""
dict_list = []
for abscissa in abscissae:
param_dict = copy.copy(params)
param_dict[abscissa_name] = abscissa
param_dict["abscissa_name"] = abscissa_name
dict_list.append(param_dict)
return dict_list
| # -*- coding: utf-8 -*-
import copy
def init_abscissa(params, abscissae, abscissa_name):
"""
List of dicts to initialize object w/ calc method
This method generates a list of dicts; each dict is sufficient to initialize an object featuring a calculator method of interest. This list can be thought of as the abscissae of a set of data. Each dict will contain data which remains constant for each calculation, but it nonetheless required to initialize the object. Each dict will also contain a datum which is the abscissa for the calculation and is also required to initialize the object.
:param dict params: Static parameters required to initialize the object featuring the ordinate calculator method.
:param list abscissae: Independent variable also required to initialize object featuring the ordinate calculator method.
:param str abscissa_name: Dictionary key for the abscissa name.
"""
dict_list = []
for abscissa in abscissae:
param_dict = copy.copy(params)
param_dict[abscissa_name] = abscissa
param_dict["abscissa_name"] = abscissa_name
dict_list.append(param_dict)
return dict_list
|
Put both output and console | const config = require("./../config.json");
const MSS = require("./../functions/");
const Sandbox = require("sandbox");
module.exports = function(message) {
var s = new Sandbox;
if(message.author.id === config.MSS.sysadmin) {
let input = message.content.replace (/\n/g, " ").split(" ");
input[0] = input[0].substring(config.MSS.prefix.length);
try {
let command = message.content.substring(config.MSS.prefix.length + input[0].length + 1);
s.run(command, function(output) {
var embed = new Discord.RichEmbed()
.setTitle(commands[input[1]].meta.name)
.setAuthor("MSS-Discord JS Sandbox", "http://moustacheminer.com/mss.png")
.setColor("#00AE86")
.setDescription(command)
.setFooter("MSS-Discord, " + config.MSS.version, "")
.setTimestamp()
.setURL("http://moustacheminer.com/")
.addField("Result", output.result)
.addField("Console", output.console);
message.channel.sendEmbed(embed, 'MSS-Discord JS Sandbox', { disableEveryone: true });
});
} catch(err) {
message.reply("Something happened and an ACTUAL ERROR happened outside the sandbox.");
}
} else {
MSS.msg.react(message, false, "X");
}
}
| const config = require("./../config.json");
const MSS = require("./../functions/");
const Sandbox = require("sandbox");
module.exports = function(message) {
var s = new Sandbox;
if(message.author.id === config.MSS.sysadmin) {
let input = message.content.replace (/\n/g, "").split(" ");
input[0] = input[0].substring(config.MSS.prefix.length);
try {
s.run(message.content.substring(config.MSS.prefix.length + input[0].length + 1), function(output) {
message.reply(`\n\`\`\``+output.result+`\`\`\``);
});
} catch(err) {
message.reply("Something happened and an ACTUAL ERROR happened outside the sandbox.");
}
} else {
MSS.msg.react(message, false, "X");
}
}
|
Implement new MPDChildProcess object into production code | var Q = require('q'),
spawn = require('child_process').spawn,
fs = require('fs'),
net = require('net'),
logger = require('winston'),
waitForSocket = require('./wait-for-socket'),
mpdChildProcess = require('./mpd-child-process'),
mpdConfig = require('./mpd-config');
exports.create = function(config) {
var mpdConf = mpdConfig.create(),
instance = {};
instance.port = mpdConf.port;
function waitToBeOnline() {
return waitForSocket
.create(instance.port)
.connect();
}
function spawnMPD(fileName) {
return mpdChildProcess.create(fileName);
}
instance.start = function() {
return mpdConf.write(config).then(spawnMPD)
.then(waitToBeOnline);
};
return instance;
};
| var Q = require('q'),
spawn = require('child_process').spawn,
fs = require('fs'),
net = require('net'),
logger = require('winston'),
waitForSocket = require('./wait-for-socket.js'),
mpdConfig = require(__dirname+'/mpd-config.js');
exports.create = function(config) {
var mpdConf = mpdConfig.create(),
instance = {};
instance.port = mpdConf.port;
function waitToBeOnline() {
return waitForSocket
.create(instance.port)
.connect();
}
function spawnMPD(fileName) {
var deferred = Q.defer(),
mpdProcess = spawn('/usr/local/bin/mpd', [fileName, '--no-daemon']);
mpdProcess.on('close', function(code, signal) {
logger.error('MPD Closed: ' + code);
});
mpdProcess.stdout.on('data', function(data) {
logger.info('MPD: ' + data);
});
mpdProcess.stderr.on('data', function(data) {
logger.warn('MPD: ' + data);
});
deferred.resolve();
return deferred.promise;
}
instance.start = function() {
return mpdConf.write(config).then(spawnMPD)
.then(waitToBeOnline);
};
return instance;
};
|
Update the "six" to force version 1.10.0 | """
The setup package to install TensorPy dependencies
*> This does NOT include TensorFlow installation
*> To install TensorFlow, use "./install_tensorflow.sh"
"""
from setuptools import setup, find_packages # noqa
setup(
name='tensorpy',
version='1.0.1',
url='http://tensorpy.com',
author='Michael Mintz',
author_email='@mintzworld',
maintainer='Michael Mintz',
description='The fast & easy way to get started with Tensorflow',
license='The MIT License',
install_requires=[
'requests==2.11.1',
'six==1.10.0',
'Pillow==3.4.1',
'BeautifulSoup==3.2.1',
],
packages=['tensorpy'],
)
| """
The setup package to install TensorPy dependencies
*> This does NOT include TensorFlow installation
*> To install TensorFlow, use "./install_tensorflow.sh"
"""
from setuptools import setup, find_packages # noqa
setup(
name='tensorpy',
version='1.0.1',
url='http://tensorpy.com',
author='Michael Mintz',
author_email='@mintzworld',
maintainer='Michael Mintz',
description='The fast & easy way to get started with Tensorflow',
license='The MIT License',
install_requires=[
'requests==2.11.1',
'six>=1.10.0',
'Pillow==3.4.1',
'BeautifulSoup==3.2.1',
],
packages=['tensorpy'],
)
|
Add Let's Encrypt env var | from .applications import get_application_domain, get_application_name
from .machine import get_env_vars
from .. import app
from subprocess import Popen, STDOUT, PIPE
from os import environ
from os.path import join
def init():
pass
def compose_start(machine, user, application, **environment):
compose_run(machine, user, application, "up", "-d", **environment)
def compose_stop(machine, user, application):
compose_run(machine, user, application, "down")
def compose_run(machine, user, application, *arguments, **environment):
name = get_application_name(user, application)
args = ["docker-compose", "-f", application.compose, "-p", name]
args += arguments
domain = get_application_domain(user, application)
env = dict(PATH=environ['PATH'], VIRTUAL_HOST=domain,
LETSENCRYPT_HOST=domain)
env.update(get_env_vars(machine))
env.update(**environment)
process = Popen(args, stderr=STDOUT, stdout=PIPE, universal_newlines=True, env=env)
process.wait()
out, err = process.communicate()
print(out)
#app.logger.info("Compose:", out)
| from .applications import get_application_domain, get_application_name
from .machine import get_env_vars
from .. import app
from subprocess import Popen, STDOUT, PIPE
from os import environ
from os.path import join
def init():
pass
def compose_start(machine, user, application, **environment):
compose_run(machine, user, application, "up", "-d", **environment)
def compose_stop(machine, user, application):
compose_run(machine, user, application, "down")
def compose_run(machine, user, application, *arguments, **environment):
name = get_application_name(user, application)
args = ["docker-compose", "-f", application.compose, "-p", name]
args += arguments
domain = get_application_domain(user, application)
env = dict(PATH=environ['PATH'], VIRTUAL_HOST=domain)
env.update(get_env_vars(machine))
env.update(**environment)
process = Popen(args, stderr=STDOUT, stdout=PIPE, universal_newlines=True, env=env)
process.wait()
out, err = process.communicate()
print(out)
#app.logger.info("Compose:", out)
|
Clean up name field assignments | import generateActions from './actions';
import generateApi from './api';
import generateNames from './names';
import generateStore from './store';
/**
* Base Flux resource class
*
* This isn't very useful by itself. Use the bindings for an actual Flux
* framework.
*/
export default class FluxResource {
constructor(options) {
Object.assign(this, this.generateNames(options));
this.fetch = this.getFetch(options);
this.api = this.generateApi(options);
this.actions = this.generateActions(options);
this.store = this.generateStore(options);
this.assignObject('Api', this.api);
this.assignObject('Actions', this.actions);
this.assignObject('Store', this.store);
}
generateNames(options) {
return this::generateNames(options);
}
getFetch() {
throw new Error('not implemented');
}
generateApi(options) {
return this::generateApi(options);
}
generateDispatch() {
throw new Error('not implemented');
}
generateActions(options) {
return this::generateActions(options);
}
generateStore(options) {
return this::generateStore(options);
}
assignObject(suffix, object) {
const objectName = `${this.name}${suffix}`;
object.displayName = objectName;
this[objectName] = object;
}
}
| import generateActions from './actions';
import generateApi from './api';
import generateNames from './names';
import generateStore from './store';
/**
* Base Flux resource class
*
* This isn't very useful by itself. Use the bindings for an actual Flux
* framework.
*/
export default class FluxResource {
constructor(options) {
const {name, methodNames} = this.generateNames(options);
this.name = name;
this.methodNames = methodNames;
this.fetch = this.getFetch(options);
this.api = this.generateApi(options);
this.actions = this.generateActions(options);
this.store = this.generateStore(options);
this.assignObject('Api', this.api);
this.assignObject('Actions', this.actions);
this.assignObject('Store', this.store);
}
generateNames(options) {
return this::generateNames(options);
}
getFetch() {
throw new Error('not implemented');
}
generateApi(options) {
return this::generateApi(options);
}
generateDispatch() {
throw new Error('not implemented');
}
generateActions(options) {
return this::generateActions(options);
}
generateStore(options) {
return this::generateStore(options);
}
assignObject(suffix, object) {
const objectName = `${this.name}${suffix}`;
object.displayName = objectName;
this[objectName] = object;
}
}
|
Update test to match changes in index | module.exports = {
'Filtering on search page': function (browser) {
browser
.url('http://localhost:8000/search?q=rocket')
.waitForElementVisible('body', 1000)
.waitForElementVisible('.resultcard__figure', 1000)
.assert.attributeEquals('.resultcard__figure img', 'src', 'http://smgco-images.s3.amazonaws.com/media/I/A/A/large_thumbnail_1949_0049_0003__0001_.jpg')
.url('http://localhost:8000/search?q=calculating-machine')
.click('.searchtab:nth-of-type(4)')
.pause(2000)
.waitForElementVisible('.resultcard__figure', 1000)
.assert.attributeEquals('.resultcard__figure img', 'src', 'http://smgco-images.s3.amazonaws.com/media/I/A/A/large_thumbnail_BAB_K_62_Calculating_Machine.jpg')
.end();
}
};
| module.exports = {
'Filtering on search page': function (browser) {
browser
.url('http://localhost:8000/search?q=rocket')
.waitForElementVisible('body', 1000)
.waitForElementVisible('.resultcard__figure', 1000)
.assert.attributeEquals('.resultcard__figure img', 'src', 'http://smgco-images.s3.amazonaws.com/media/W/P/A/large_thumbnail_1909_0003.jpg')
.url('http://localhost:8000/search?q=calculating-machine')
.click('.searchtab:nth-of-type(4)')
.pause(2000)
.waitForElementVisible('.resultcard__figure', 1000)
.assert.attributeEquals('.resultcard__figure img', 'src', 'http://smgco-images.s3.amazonaws.com/media/I/A/A/large_thumbnail_BAB_K_62_Calculating_Machine.jpg')
.end();
}
};
|
Add close and destroy; force fixed chunk length | module.exports = Storage
function Storage (chunkLength) {
if (!(this instanceof Storage)) return new Storage()
this.chunks = []
this.chunkLength = Number(chunkLength)
this.closed = false
if (!this.chunkLength) throw new Error('First argument must be a chunk length')
}
Storage.prototype.put = function (index, buf, cb) {
if (this.closed) return nextTick(cb, new Error('Storage is closed'))
if (buf.length !== this.chunkLength) {
return nextTick(cb, new Error('Chunk length must be ' + this.chunkLength))
}
this.chunks[index] = buf
if (cb) process.nextTick(cb)
}
Storage.prototype.get = function (index, opts, cb) {
if (typeof opts === 'function') return this.get(index, null, opts)
if (this.closed) return nextTick(cb, new Error('Storage is closed'))
var buf = this.chunks[index]
if (!buf) return nextTick(cb, new Error('Chunk not found'))
if (!opts) return nextTick(cb, null, buf)
var offset = opts.offset || 0
var len = opts.length || (buf.length - offset)
nextTick(cb, null, buf.slice(offset, len + offset))
}
Storage.prototype.close = Storage.prototype.destroy = function (cb) {
if (this.closed) return nextTick(cb, new Error('Storage is closed'))
this.closed = true
this.chunks = null
nextTick(cb, null)
}
function nextTick (cb, err, val) {
process.nextTick(function () {
if (cb) cb(err, val)
})
}
| module.exports = Storage
function Storage () {
if (!(this instanceof Storage)) return new Storage()
this.chunks = []
}
Storage.prototype.put = function (index, buf, cb) {
this.chunks[index] = buf
if (cb) process.nextTick(cb)
}
function nextTick (cb, err, val) {
process.nextTick(function () {
cb(err, val)
})
}
Storage.prototype.get = function (index, opts, cb) {
if (typeof opts === 'function') return this.get(index, null, opts)
var buf = this.chunks[index]
if (!buf) return nextTick(cb, new Error('Chunk not found'))
if (!opts) return nextTick(cb, null, buf)
var offset = opts.offset || 0
var len = opts.length || (buf.length - offset)
nextTick(cb, null, buf.slice(offset, len + offset))
}
|
Add method to say Achmed like jews. | package com.github.aureliano.achmed.helper;
import java.util.Properties;
public final class ApplicationHelper {
private ApplicationHelper() {
throw new InstantiationError(this.getClass().getName() + " cannot be instantiated.");
}
public static String help() {
String help = FileHelper.readResource("meta/help");
return help;
}
public static String version() {
Properties properties = PropertyHelper.loadProperties("meta/version.properties");
return new StringBuilder("achmed")
.append(" ")
.append(properties.get("version"))
.append(":")
.append(properties.get("release"))
.append(" (")
.append(properties.get("date"))
.append(")")
.toString();
}
public static String error(String[] args) {
String param = StringHelper.join(args, " ");
if ("".equals(param)) {
return EasterEggHelper.silence();
} else if ("greeting".equalsIgnoreCase(param)) {
return EasterEggHelper.greeting();
} else if ("hello".equalsIgnoreCase(param)) {
return EasterEggHelper.hello();
} else if ("you are dead".equalsIgnoreCase(param)) {
return EasterEggHelper.youAreDead();
} else if ("do you like jews?".equalsIgnoreCase(param)) {
return EasterEggHelper.doYouLikeJews();
} else {
return "Don't know how to handle such command: " + param;
}
}
} | package com.github.aureliano.achmed.helper;
import java.util.Properties;
public final class ApplicationHelper {
private ApplicationHelper() {
throw new InstantiationError(this.getClass().getName() + " cannot be instantiated.");
}
public static String help() {
String help = FileHelper.readResource("meta/help");
return help;
}
public static String version() {
Properties properties = PropertyHelper.loadProperties("meta/version.properties");
return new StringBuilder("achmed")
.append(" ")
.append(properties.get("version"))
.append(":")
.append(properties.get("release"))
.append(" (")
.append(properties.get("date"))
.append(")")
.toString();
}
public static String error(String[] args) {
String param = StringHelper.join(args, " ");
if ("".equals(param)) {
return EasterEggHelper.silence();
} else if ("greeting".equalsIgnoreCase(param)) {
return EasterEggHelper.greeting();
} else if ("hello".equalsIgnoreCase(param)) {
return EasterEggHelper.hello();
} else if ("you are dead".equalsIgnoreCase(param)) {
return EasterEggHelper.youAreDead();
} else if ("do you like hews?".equalsIgnoreCase(param)) {
return EasterEggHelper.doYouLikeJews();
} else {
return "Don't know how to handle such command: " + param;
}
}
} |
Add comment as to how important the call to render() is | import React, { PropTypes } from 'react';
import { Link, IndexLink } from 'react-router';
import { Login } from 'auth';
import { ErrorHandler } from 'error';
import { rendered } from 'lib/fetchData';
export default class App extends React.Component {
static propTypes = {
children: PropTypes.object,
};
componentDidMount() {
/* This is one of the most important lines of the app,
* it is where we start triggering loading of data
* on the client-side
*/
rendered();
}
render() {
return (
<div id="main-view">
<IndexLink to="/">About</IndexLink>
{' '}
<Link to="/todos">Todos</Link>
<hr />
<Login />
<hr />
<ErrorHandler>
{this.props.children}
</ErrorHandler>
</div>
);
}
}
| import React, { PropTypes } from 'react';
import { Link, IndexLink } from 'react-router';
import { Login } from 'auth';
import { ErrorHandler } from 'error';
import { rendered } from 'lib/fetchData';
export default class App extends React.Component {
static propTypes = {
children: PropTypes.object,
};
componentDidMount() {
rendered();
}
render() {
return (
<div id="main-view">
<IndexLink to="/">About</IndexLink>
{' '}
<Link to="/todos">Todos</Link>
<hr />
<Login />
<hr />
<ErrorHandler>
{this.props.children}
</ErrorHandler>
</div>
);
}
}
|
Fix gofmt formating for a file | package tools
import (
"fmt"
"log"
"strings"
)
// UploadFile used to upload file by S3 pre-signed URL
func UploadFile(path, url string) int {
log.Println("Uploading file from path:", path)
file, info := prepareFile(path)
resp := sendRequest(url, &file, info)
return getStatusOfUpload(resp)
}
// GetFileName returns file name from path string
func GetFileName(path string) string {
if !strings.Contains(path, "/") {
return path
}
pos := strings.LastIndex(path, "/")
return string(path[pos+1:])
}
// GenerateReportURL generate URL to test report from ARN
func GenerateReportURL(arn string) string {
URL := "https://us-west-2.console.aws.amazon.com/devicefarm/home?region=us-west-2#/projects/%s/runs/%s"
index := strings.Index(arn, ":run:")
if index == -1 {
log.Println("Can't generate test report URL from ARN:", arn)
return ""
}
str := arn[index+5:]
index = strings.Index(str, "/")
project := str[:index]
run := str[index+1:]
return fmt.Sprintf(URL, project, run)
}
| package tools
import (
"log"
"strings"
"fmt"
)
// UploadFile used to upload file by S3 pre-signed URL
func UploadFile(path, url string) int {
log.Println("Uploading file from path:", path)
file, info := prepareFile(path)
resp := sendRequest(url, &file, info)
return getStatusOfUpload(resp)
}
// GetFileName returns file name from path string
func GetFileName(path string) string {
if !strings.Contains(path, "/") {
return path
}
pos := strings.LastIndex(path, "/")
return string(path[pos+1:])
}
// GenerateReportURL generate URL to test report from ARN
func GenerateReportURL(arn string) string {
URL := "https://us-west-2.console.aws.amazon.com/devicefarm/home?region=us-west-2#/projects/%s/runs/%s"
index := strings.Index(arn, ":run:")
if index == -1 {
log.Println("Can't generate test report URL from ARN:", arn)
return ""
}
str := arn[index+5:]
index = strings.Index(str, "/")
project := str[:index]
run := str[index+1:]
return fmt.Sprintf(URL, project, run)
}
|
Fix critical Image delete observer!!!
Update ImageObserver.php | <?php
namespace Despark\Cms\Admin\Observers;
use Illuminate\Database\Eloquent\Model;
use Despark\Cms\Contracts\ImageContract;
/**
* Class ImageObserver.
*/
class ImageObserver
{
/**
* @param Model $model
*/
public function saved(Model $model)
{
$model->saveImages();
}
/**
* @param Model $model
*/
public function deleted(Model $model)
{
$imageInstance = app(ImageContract::class);
\DB::table($imageInstance->getTable())
->where('resource_id', '=', $model->getKey())
->where('resource_model', '=', $model->getMorphClass())
->delete();
\File::deleteDirectory($model->getCurrentUploadDir());
}
}
| <?php
namespace Despark\Cms\Admin\Observers;
use Illuminate\Database\Eloquent\Model;
use Despark\Cms\Contracts\ImageContract;
/**
* Class ImageObserver.
*/
class ImageObserver
{
/**
* @param Model $model
*/
public function saved(Model $model)
{
$model->saveImages();
}
/**
* @param Model $model
*/
public function deleted(Model $model)
{
$imageInstance = app(ImageContract::class);
\DB::table($imageInstance->getTable())->where('resource_id', '=', $model->getKey())
->delete();
\File::deleteDirectory($model->getCurrentUploadDir());
}
}
|
[test] Fix typo in whitelist and blacklist | // @flow
const { JSDOM } = require('jsdom');
const Node = require('jsdom/lib/jsdom/living/node-document-position');
// We can use jsdom-global at some point if maintaining these lists is a burden.
const whitelist = ['HTMLElement', 'Performance'];
const blacklist = ['sessionStorage', 'localStorage'];
function createDOM() {
const dom = new JSDOM('', { pretendToBeVisual: true });
global.window = dom.window;
global.Node = Node;
global.document = dom.window.document;
// Not yet supported: https://github.com/jsdom/jsdom/issues/317
global.document.createRange = () => ({
setStart: () => {},
setEnd: () => {},
commonAncestorContainer: {
nodeName: 'BODY',
ownerDocument: document,
},
});
global.navigator = {
userAgent: 'node.js',
};
Object.keys(dom.window)
.filter(key => !blacklist.includes(key))
.concat(whitelist)
.forEach(key => {
if (typeof global[key] === 'undefined') {
global[key] = dom.window[key];
}
});
}
module.exports = createDOM;
| // @flow
const { JSDOM } = require('jsdom');
const Node = require('jsdom/lib/jsdom/living/node-document-position');
// We can use jsdom-global at some point if maintaining that list turns out to be a burden.
const whiteList = ['HTMLElement', 'Performance'];
const blackList = ['sessionStorage', 'localStorage'];
function createDOM() {
const dom = new JSDOM('', { pretendToBeVisual: true });
global.window = dom.window;
global.Node = Node;
global.document = dom.window.document;
// Not yet supported: https://github.com/jsdom/jsdom/issues/317
global.document.createRange = () => ({
setStart: () => {},
setEnd: () => {},
commonAncestorContainer: {
nodeName: 'BODY',
ownerDocument: document,
},
});
global.navigator = {
userAgent: 'node.js',
};
Object.keys(dom.window)
.filter(key => !blackList.includes(key))
.concat(whiteList)
.forEach(key => {
if (typeof global[key] === 'undefined') {
global[key] = dom.window[key];
}
});
}
module.exports = createDOM;
|
Simplify and utilize request()->user() and request()->guard() | <?php
declare(strict_types=1);
namespace Rinvex\Support\Traits;
use DateTimeZone;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Date;
trait HasTimezones
{
/**
* Return a timestamp as DateTime object.
*
* @param mixed $value
*
* @return \Illuminate\Support\Carbon
*/
protected function asDateTime($value)
{
$datetime = parent::asDateTime($value);
$timezone = optional(request()->user())->timezone;
if (! $timezone || $timezone === config('app.timezone')) {
return $datetime;
}
$thisIsUpdateRequest = Arr::first(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 30), function ($trace) {
return $trace['function'] === 'setAttribute';
});
if ($thisIsUpdateRequest) {
// When updating attributes, we need to reset user timezone to system timezone before saving!
return Date::parse($datetime->toDateTimeString(), $timezone)->setTimezone(config('app.timezone'));
}
return $datetime->setTimezone(new DateTimeZone($timezone));
}
}
| <?php
declare(strict_types=1);
namespace Rinvex\Support\Traits;
use DateTimeZone;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Date;
trait HasTimezones
{
/**
* Return a timestamp as DateTime object.
*
* @param mixed $value
*
* @return \Illuminate\Support\Carbon
*/
protected function asDateTime($value)
{
$datetime = parent::asDateTime($value);
$timezone = app()->bound('request.user') ? optional(app('request.user'))->timezone : null;
if (! $timezone || $timezone === config('app.timezone')) {
return $datetime;
}
$thisIsUpdateRequest = Arr::first(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 30), function ($trace) {
return $trace['function'] === 'setAttribute';
});
if ($thisIsUpdateRequest) {
// When updating attributes, we need to reset user timezone to system timezone before saving!
return Date::parse($datetime->toDateTimeString(), $timezone)->setTimezone(config('app.timezone'));
}
return $datetime->setTimezone(new DateTimeZone($timezone));
}
}
|
Fix issue when hydrating settings with missing default keys | import { observable, toJS } from 'mobx';
import { pathExistsSync, outputJsonSync, readJsonSync } from 'fs-extra';
import { SETTINGS_PATH, DEFAULT_APP_SETTINGS } from '../config';
const debug = require('debug')('Settings');
export default class Settings {
@observable store = DEFAULT_APP_SETTINGS;
constructor() {
if (!pathExistsSync(SETTINGS_PATH)) {
this._writeFile();
} else {
this._hydrate();
}
}
set(settings) {
this.store = this._merge(this.store, settings);
this._writeFile();
}
get all() {
return this.store;
}
get(key) {
return this.store[key];
}
_merge(settings) {
return Object.assign(DEFAULT_APP_SETTINGS, settings);
}
_hydrate() {
this.store = this._merge(readJsonSync(SETTINGS_PATH));
debug('Hydrate store', toJS(this.store));
}
_writeFile() {
outputJsonSync(SETTINGS_PATH, this.store);
debug('Write settings file', toJS(this.store));
}
}
| import { observable, toJS } from 'mobx';
import { pathExistsSync, outputJsonSync, readJsonSync } from 'fs-extra';
import { SETTINGS_PATH, DEFAULT_APP_SETTINGS } from '../config';
const debug = require('debug')('Settings');
export default class Settings {
@observable store = DEFAULT_APP_SETTINGS;
constructor() {
if (!pathExistsSync(SETTINGS_PATH)) {
this._writeFile();
} else {
this._hydrate();
}
}
set(settings) {
this.store = Object.assign(this.store, settings);
this._writeFile();
}
get all() {
return this.store;
}
get(key) {
return this.store[key];
}
_hydrate() {
this.store = readJsonSync(SETTINGS_PATH);
debug('Hydrate store', toJS(this.store));
}
_writeFile() {
outputJsonSync(SETTINGS_PATH, this.store);
debug('Write settings file', toJS(this.store));
}
}
|
Make sure pwd strength API is not required to be able to register | <?php
namespace App\Validator;
use Symfony\Component\Validator\Constraints\Compound;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @Annotation
*/
class Password extends Compound
{
/**
* @param array<string, mixed> $options
*/
protected function getConstraints(array $options): array
{
return [
new Assert\NotBlank([
'message' => 'Please enter a password',
]),
new Assert\Type('string'),
new Assert\Length([
'min' => 8,
'minMessage' => 'Your password should be at least {{ limit }} characters',
// max length allowed by Symfony for security reasons
'max' => 4096,
]),
new Assert\NotCompromisedPassword(skipOnError: true),
];
}
}
| <?php
namespace App\Validator;
use Symfony\Component\Validator\Constraints\Compound;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @Annotation
*/
class Password extends Compound
{
/**
* @param array<string, mixed> $options
*/
protected function getConstraints(array $options): array
{
return [
new Assert\NotBlank([
'message' => 'Please enter a password',
]),
new Assert\Type('string'),
new Assert\Length([
'min' => 8,
'minMessage' => 'Your password should be at least {{ limit }} characters',
// max length allowed by Symfony for security reasons
'max' => 4096,
]),
new Assert\NotCompromisedPassword(),
];
}
}
|
[FIX] Move code outside of exception | # -*- coding: utf-8 -*-
# See README file for full copyright and licensing details.
import time
from openerp import models, api
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT
class PosPicking(models.Model):
_inherit = 'pos.order'
@api.multi
def create_picking(self):
try:
super(PosPicking, self).create_picking()
except:
pass
if self.picking_id.state != 'done':
for move in self.picking_id.move_lines:
if move.quant_ids:
# We pass this move to done because the quants were already moved
move.write({'state': 'done', 'date': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)})
else:
# If there are no moved quants we pass the move to Waiting Availability
move.do_unreserve()
return True
| # -*- coding: utf-8 -*-
# See README file for full copyright and licensing details.
import time
from openerp import models, api
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT
class PosPicking(models.Model):
_inherit = 'pos.order'
@api.multi
def create_picking(self):
try:
super(PosPicking, self).create_picking()
except:
if self.picking_id.state != 'done':
for move in self.picking_id.move_lines:
if move.quant_ids:
# We pass this move to done because the quants were already moved
move.write({'state': 'done', 'date': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)})
else:
# If there are no moved quants we pass the move to Waiting Availability
move.do_unreserve()
return True
|
Fix test by adding missing index | <?php
require_once __DIR__ . DIRECTORY_SEPARATOR . 'config.php';
class OrganismsTest extends PHPUnit_Framework_TestCase
{
public function testExecute()
{
list($service) = \WebService::factory('listing/Organisms');
$results = ($service->execute(array('limit' => 2)));
$this->assertEquals(2, count($results));
$results = ($service->execute(array()));
$this->assertEquals(5, count($results));
$organism = 'Thermopsis';
$results = ($service->execute(array('limit' => 1, 'search' => $organism)));
$this->assertEquals(1, count($results));
$pos = strpos($results[0]['scientific_name'], $organism);
$this->assertEquals(0, $pos);
}
}
?> | <?php
require_once __DIR__ . DIRECTORY_SEPARATOR . 'config.php';
class OrganismsTest extends PHPUnit_Framework_TestCase
{
public function testExecute()
{
list($service) = \WebService::factory('listing/Organisms');
$results = ($service->execute(array('limit' => 2)));
$this->assertEquals(2, count($results));
$results = ($service->execute(array()));
$this->assertEquals(5, count($results));
$organism = 'Thermopsis';
$results = ($service->execute(array('limit' => 1, 'search' => $organism)));
$this->assertEquals(1, count($results));
$pos = strpos($results['scientific_name'], $organism);
$this->assertEquals(0, $pos);
}
}
?> |
Comment out flutter tests until we have set up CI to download it | var path = require('path');
var childProcess = require('child_process');
const env = Object.create(process.env);
const args = ['node_modules/vscode/bin/test'];
var exitCode = 0;
function runTests(testFolder, workspaceFolder) {
env.CODE_TESTS_WORKSPACE = path.join(process.cwd(), 'test', 'test_projects', workspaceFolder);
env.CODE_TESTS_PATH = path.join(process.cwd(), 'out', 'test', testFolder);
const res = childProcess.spawnSync('node', args, { env: env, stdio: 'pipe', cwd: process.cwd() });
if (res.error)
throw error;
if (res.output)
res.output.filter(l => l).forEach(l => console.log(l.toString().trim()));
exitCode = exitCode || res.status;
}
runTests('general', 'hello_world');
//runTests('flutter', 'flutter_hello_world');
process.exit(exitCode);
| var path = require('path');
var childProcess = require('child_process');
const env = Object.create(process.env);
const args = ['node_modules/vscode/bin/test'];
var exitCode = 0;
function runTests(testFolder, workspaceFolder) {
env.CODE_TESTS_WORKSPACE = path.join(process.cwd(), 'test', 'test_projects', workspaceFolder);
env.CODE_TESTS_PATH = path.join(process.cwd(), 'out', 'test', testFolder);
const res = childProcess.spawnSync('node', args, { env: env, stdio: 'pipe', cwd: process.cwd() });
if (res.error)
throw error;
if (res.output)
res.output.filter(l => l).forEach(l => console.log(l.toString().trim()));
exitCode = exitCode || res.status;
}
runTests('general', 'hello_world');
runTests('flutter', 'flutter_hello_world');
process.exit(exitCode);
|
[SysApps] Make the JavaScript shim dispatch events
The first thing to be done is make the JavaScript DeviceCapabilties an EventTarget
(which is also a BindingObject). The BindingObjects are JavaScripts objects with
a link with some native object and they use a unique ID for routing messages
between them.
common.EventTarget.call(this) initializes the EventTarget and makes
this._addEvent() possible.
Now all the blanks are filled and we are good to go. The next step would be
replace the StorageInfoProviderMock with a real implementation for each platform
we support. No need to touch on anything else. | // Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Implementation of the W3C's Device Capabilities API.
// http://www.w3.org/2012/sysapps/device-capabilities/
var internal = requireNative('internal');
internal.setupInternalExtension(extension);
var v8tools = requireNative('v8tools');
var common = requireNative('sysapps_common');
common.setupSysAppsCommon(internal, v8tools);
var Promise = requireNative('sysapps_promise').Promise;
var DeviceCapabilities = function() {
common.BindingObject.call(this, common.getUniqueId());
common.EventTarget.call(this);
internal.postMessage("deviceCapabilitiesConstructor", [this._id]);
this._addEvent("storageattach");
this._addEvent("storagedetach");
this._addMethodWithPromise("getAVCodecs", Promise);
this._addMethodWithPromise("getCPUInfo", Promise);
this._addMethodWithPromise("getMemoryInfo", Promise);
this._addMethodWithPromise("getStorageInfo", Promise);
};
DeviceCapabilities.prototype = new common.EventTargetPrototype();
DeviceCapabilities.prototype.constructor = DeviceCapabilities;
exports = new DeviceCapabilities();
| // Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Implementation of the W3C's Device Capabilities API.
// http://www.w3.org/2012/sysapps/device-capabilities/
var internal = requireNative('internal');
internal.setupInternalExtension(extension);
var v8tools = requireNative('v8tools');
var common = requireNative('sysapps_common');
common.setupSysAppsCommon(internal, v8tools);
var Promise = requireNative('sysapps_promise').Promise;
var DeviceCapabilities = function() {
common.BindingObject.call(this, common.getUniqueId());
internal.postMessage("deviceCapabilitiesConstructor", [this._id]);
this._addMethodWithPromise("getAVCodecs", Promise);
this._addMethodWithPromise("getCPUInfo", Promise);
this._addMethodWithPromise("getMemoryInfo", Promise);
this._addMethodWithPromise("getStorageInfo", Promise);
};
DeviceCapabilities.prototype = new common.BindingObjectPrototype();
DeviceCapabilities.prototype.constructor = DeviceCapabilities;
exports = new DeviceCapabilities();
|
Make it clear it's an empty loop. | var Events = {
add: function(obj, events) {
for (var type in events) {
var func = events[type];
if (obj.addEventListener) {
obj.addEventListener(type, func, false);
} else if (obj.attachEvent) {
// Make a bound closure that calls on the right object and
// passes on the global event object as a parameter.
obj.attachEvent('on' + type, func.bound = function() {
func.call(obj, window.event);
});
}
}
},
remove: function(obj, events) {
for (var type in events) {
var func = events[type];
if (obj.removeEventListener) {
obj.removeEventListener(type, func, false);
} else if (obj.detachEvent) {
// Remove the bound closure instead of func itself
obj.detachEvent('on' + type, func.bound);
}
}
},
getPoint: function(event) {
return Point.create(
event.pageX || event.clientX + document.documentElement.scrollLeft,
event.pageY || event.clientY + document.documentElement.scrollTop
);
},
getOffset: function(event) {
var point = Events.getPoint(event);
// Remove target offsets from page coordinates
for (var el = event.target || event.srcElement; el;
point.x -= el.offsetLeft, point.y -= el.offsetTop,
el = el.offsetParent) {}
return point;
}
};
| var Events = {
add: function(obj, events) {
for (var type in events) {
var func = events[type];
if (obj.addEventListener) {
obj.addEventListener(type, func, false);
} else if (obj.attachEvent) {
// Make a bound closure that calls on the right object and
// passes on the global event object as a parameter.
obj.attachEvent('on' + type, func.bound = function() {
func.call(obj, window.event);
});
}
}
},
remove: function(obj, events) {
for (var type in events) {
var func = events[type];
if (obj.removeEventListener) {
obj.removeEventListener(type, func, false);
} else if (obj.detachEvent) {
// Remove the bound closure instead of func itself
obj.detachEvent('on' + type, func.bound);
}
}
},
getPoint: function(event) {
return Point.create(
event.pageX || event.clientX + document.documentElement.scrollLeft,
event.pageY || event.clientY + document.documentElement.scrollTop
);
},
getOffset: function(event) {
var point = Events.getPoint(event);
// Remove target offsets from page coordinates
for (var el = event.target || event.srcElement; el;
point.x -= el.offsetLeft, point.y -= el.offsetTop,
el = el.offsetParent);
return point;
}
};
|
Add update store packet code | module.exports = {
// Packet constants
PLAYER_START: "1",
PLAYER_ADD: "2",
PLAYER_ANGLE: "2",
PLAYER_UPDATE: "3",
PLAYER_ATTACK :"4",
LEADERBOAD: "5",
PLAYER_MOVE: "3",
PLAYER_REMOVE: "4",
LEADERS_UPDATE: "5",
LOAD_GAME_OBJ: "6",
GATHER_ANIM: "7",
AUTO_ATK: "7",
WIGGLE: "8",
CLAN_CREATE: "8",
PLAYER_LEAVE_CLAN: "9",
STAT_UPDATE: "9",
CLAN_REQ_JOIN: "10",
UPDATE_HEALTH: "10",
CLAN_ACC_JOIN: "11",
CLAN_KICK: "12",
ITEM_BUY: "13",
UPDATE_AGE: "15",
CHAT: "ch",
CLAN_DEL: "ad",
PLAYER_SET_CLAN: "st",
SET_CLAN_PLAYERS: "sa",
CLAN_ADD: "ac",
CLAN_NOTIFY: "an",
MINIMAP: "mm",
UPDATE_STORE: "us",
DISCONN: "d"
} | module.exports = {
// Packet constants
PLAYER_START: "1",
PLAYER_ADD: "2",
PLAYER_ANGLE: "2",
PLAYER_UPDATE: "3",
PLAYER_ATTACK :"4",
LEADERBOAD: "5",
PLAYER_MOVE: "3",
PLAYER_REMOVE: "4",
LEADERS_UPDATE: "5",
LOAD_GAME_OBJ: "6",
GATHER_ANIM: "7",
AUTO_ATK: "7",
WIGGLE: "8",
CLAN_CREATE: "8",
PLAYER_LEAVE_CLAN: "9",
STAT_UPDATE: "9",
CLAN_REQ_JOIN: "10",
UPDATE_HEALTH: "10",
CLAN_ACC_JOIN: "11",
CLAN_KICK: "12",
ITEM_BUY: "13",
UPDATE_AGE: "15",
CHAT: "ch",
CLAN_DEL: "ad",
PLAYER_SET_CLAN: "st",
SET_CLAN_PLAYERS: "sa",
CLAN_ADD: "ac",
CLAN_NOTIFY: "an",
MINIMAP: "mm",
DISCONN: "d"
} |
Check if type is undefined first | const squanch = (...patterns) => {
return v => {
const primitives = ['Number', 'String', 'Boolean', 'Symbol'];
const isIdentical = (p, v) => p === v;
const isNull = (p, v) => isIdentical(null, p) && isIdentical(p, v);
const isUndefined = (p, v) => isIdentical(undefined, p) && isIdentical(p, v);
const isPrimitiveWithValue = (primitives, type, value) => {
return (value !== null && value !== undefined)
&& primitives.includes(type.name)
&& {}.valueOf.call(value) instanceof type;
};
const callalbeTruthy = (p, v) => {
if (p instanceof Function && ! primitives.includes(p.name)) {
return p.call(null, v);
}
};
for (let sequence of patterns) {
let [pattern, fn] = sequence;
switch(true) {
case (isUndefined(pattern, v)) :
case (isNull(pattern, v)) :
case (isIdentical(pattern, v)) :
case (isPrimitiveWithValue(primitives, pattern, v)) :
case (callalbeTruthy(pattern, v)) :
return fn.call(null, v);
break;
}
}
return 'No patterns matched';
};
};
export default squanch; | const squanch = (...patterns) => {
return v => {
const primitives = ['Number', 'String', 'Boolean', 'Symbol'];
const isIdentical = (p, v) => p === v;
const isNull = (p, v) => isIdentical(null, p) && isIdentical(p, v);
const isUndefined = (p, v) => isIdentical(undefined, p) && isIdentical(p, v);
const isPrimitiveWithValue = (primitives, type, value) => {
return (value !== null && value !== undefined)
&& primitives.includes(type.name)
&& {}.valueOf.call(value) instanceof type;
};
const callalbeTruthy = (p, v) => {
if (p instanceof Function && ! primitives.includes(p.name)) {
return p.call(null, v);
}
};
for (let sequence of patterns) {
let [pattern, fn] = sequence;
switch(true) {
case (isNull(pattern, v)) :
case (isUndefined(pattern, v)) :
case (isIdentical(pattern, v)) :
case (isPrimitiveWithValue(primitives, pattern, v)) :
case (callalbeTruthy(pattern, v)) :
return fn.call(null, v);
break;
}
}
return 'No patterns matched';
};
};
export default squanch; |
Allow tty process longer time to spawn in feature tests | import time, pexpect, re
PROMPT = "root@\w+:[^\r]+"
UP_ARROW = "\x1b[A"
def type(process, input_):
process.send(input_.encode())
process.expect(PROMPT)
# Remove the typed input from the returned standard out
return re.sub(re.escape(input_.strip()), '', process.before).strip()
@when(u'I run the interactive command')
def step_impl(context):
process = pexpect.spawn(context.text)
time.sleep(3)
type(process, UP_ARROW)
class Output(object):
pass
context.output = Output()
context.output.stderr = ""
context.output.stdout = ""
context.process = process
@when(u'I type')
def step_impl(context):
cmd = context.text.strip() + "\n"
context.output.stdout = type(context.process, cmd)
@when(u'I exit the shell')
def step_impl(context):
context.process.send("exit\n")
| import time, pexpect, re
import nose.tools as nt
import subprocess as spr
PROMPT = "root@\w+:[^\r]+"
ENTER = "\n"
def type(process, input_):
process.send(input_.encode())
process.expect(PROMPT)
# Remove the typed input from the returned standard out
return re.sub(re.escape(input_.strip()), '', process.before).strip()
@when(u'I run the interactive command')
def step_impl(context):
process = pexpect.spawn(context.text)
time.sleep(0.5)
type(process, ENTER)
class Output(object):
pass
context.output = Output()
context.output.stderr = ""
context.output.stdout = ""
context.process = process
@when(u'I type')
def step_impl(context):
cmd = context.text.strip() + "\n"
context.output.stdout = type(context.process, cmd)
@when(u'I exit the shell')
def step_impl(context):
context.process.send("exit\n")
|
Update to include the latest web platform tests
Includes https://github.com/w3c/web-platform-tests/pull/5792. | "use strict";
if (process.env.NO_UPDATE) {
process.exit(0);
}
const path = require("path");
const fs = require("fs");
const request = require("request");
// Pin to specific version, reflecting the spec version in the readme.
//
// To get the latest commit:
// 1. Go to https://github.com/w3c/web-platform-tests/tree/master/url
// 2. Press "y" on your keyboard to get a permalink
// 3. Copy the commit hash
const commitHash = "5ae94e10d50e76fdfc120863c198d3a3937000dc";
const sourceURL = `https://raw.githubusercontent.com/w3c/web-platform-tests/${commitHash}/url/urltestdata.json`;
const setterSourceURL = `https://raw.githubusercontent.com/w3c/web-platform-tests/${commitHash}/url/setters_tests.json`;
const targetDir = path.resolve(__dirname, "..", "test", "web-platform-tests");
request.get(sourceURL)
.pipe(fs.createWriteStream(path.resolve(targetDir, "urltestdata.json")));
request.get(setterSourceURL)
.pipe(fs.createWriteStream(path.resolve(targetDir, "setters_tests.json")));
| "use strict";
if (process.env.NO_UPDATE) {
process.exit(0);
}
const path = require("path");
const fs = require("fs");
const request = require("request");
// Pin to specific version, reflecting the spec version in the readme.
//
// To get the latest commit:
// 1. Go to https://github.com/w3c/web-platform-tests/tree/master/url
// 2. Press "y" on your keyboard to get a permalink
// 3. Copy the commit hash
const commitHash = "28541bb338e33fb79bc6bf64330b62fac2eca325";
const sourceURL = `https://raw.githubusercontent.com/w3c/web-platform-tests/${commitHash}/url/urltestdata.json`;
const setterSourceURL = `https://raw.githubusercontent.com/w3c/web-platform-tests/${commitHash}/url/setters_tests.json`;
const targetDir = path.resolve(__dirname, "..", "test", "web-platform-tests");
request.get(sourceURL)
.pipe(fs.createWriteStream(path.resolve(targetDir, "urltestdata.json")));
request.get(setterSourceURL)
.pipe(fs.createWriteStream(path.resolve(targetDir, "setters_tests.json")));
|
Update CSS Selector to Match ExHentai Changes | <?php
class ExPage_Index extends ExPage_Abstract
{
public function isLastPage()
{
return (count($this->find('td.ptds + td.ptdd')) > 0);
}
public function getGalleries()
{
$ret = array();
$links = $this->find('.itg.gld .gl1t .glname a');
foreach ($links as $linkElem) {
$gallery = new stdClass();
$link = pq($linkElem);
$gallery->name = $link->text();
preg_match("~https://exhentai.org/g/(\d*)/(\w*)/~", $link->attr('href'), $matches);
if (isset($matches[1]) && isset($matches[2])) {
$gallery->exhenid = $matches[1];
$gallery->hash = $matches[2];
$ret[] = $gallery;
}
}
return $ret;
}
}
| <?php
class ExPage_Index extends ExPage_Abstract
{
public function isLastPage()
{
return (count($this->find('td.ptds + td.ptdd')) > 0);
}
public function getGalleries()
{
$ret = array();
$links = $this->find('td.itd .it5 a');
foreach ($links as $linkElem) {
$gallery = new stdClass();
$link = pq($linkElem);
$gallery->name = $link->text();
preg_match("~https://exhentai.org/g/(\d*)/(\w*)/~", $link->attr('href'), $matches);
if (isset($matches[1]) && isset($matches[2])) {
$gallery->exhenid = $matches[1];
$gallery->hash = $matches[2];
$ret[] = $gallery;
}
}
return $ret;
}
}
|
Add Shifting Sands to benchmark tests | """Script to run performance check."""
import time
from examples.game_of_life import (
GameOfLife, GOLExperiment
)
from examples.shifting_sands import (
ShiftingSands, ShiftingSandsExperiment
)
from xentica.utils.formatters import sizeof_fmt
MODELS = [
("Conway's Life", GameOfLife, GOLExperiment),
("Shifting Sands", ShiftingSands, ShiftingSandsExperiment),
]
NUM_STEPS = 10000
if __name__ == "__main__":
for name, model, experiment in MODELS:
ca = model(experiment)
start_time = time.time()
for j in range(NUM_STEPS):
ca.step()
time_passed = time.time() - start_time
speed = NUM_STEPS * ca.cells_num // time_passed
print("%s: %s cells/s" % (name, sizeof_fmt(speed)))
del ca
| """Script to run performance check."""
import time
from examples.game_of_life import GameOfLife, GOLExperiment
from xentica.utils.formatters import sizeof_fmt
MODELS = [
("Conway's Life", GameOfLife, GOLExperiment),
]
NUM_STEPS = 10000
if __name__ == "__main__":
for name, model, experiment in MODELS:
ca = model(experiment)
start_time = time.time()
for j in range(NUM_STEPS):
ca.step()
time_passed = time.time() - start_time
speed = NUM_STEPS * ca.cells_num // time_passed
print("%s: %s cells/s" % (name, sizeof_fmt(speed)))
del ca
|
Fix getting view path name. | <?php
namespace Ouzo;
use Ouzo\Utilities\Path;
class ViewPathResolver
{
public static function resolveViewPath($name)
{
return Path::join(ROOT_PATH, 'application', 'view', $name . self::getViewPostfix());
}
private static function getViewPostfix()
{
if (Uri::isAjax()) {
return '.ajax.phtml';
}
switch (ContentType::value()) {
case 'text/xml':
return '.xml.phtml';
case 'application/json':
case 'text/json':
return '.json.phtml';
default:
return '.phtml';
}
}
} | <?php
namespace Ouzo;
use Ouzo\Utilities\Path;
class ViewPathResolver
{
public static function resolveViewPath($name)
{
return Path::join(ROOT_PATH, 'application', 'view', $name . self::getViewPostfix());
}
private static function getViewPostfix()
{
if (Uri::isAjax()) {
return '.ajax.phtml';
}
switch (ContentType::getFromServer()) {
case 'text/xml':
return '.xml.phtml';
case 'application/json':
case 'text/json':
return '.json.phtml';
default:
return '.phtml';
}
}
} |
Check VE is available before running unit tests
Bug: T127763
Change-Id: Ic5eef55c3327f95362e2f69fbebc86be306790f7 | <?php
/**
* Graph extension Hooks
*
* @file
* @ingroup Extensions
*/
namespace Graph;
use ResourceLoader;
class Hooks {
/**
* Conditionally register the unit testing module for the ext.graph.visualEditor module
* only if that module is loaded
*
* @param array $testModules The array of registered test modules
* @param ResourceLoader $resourceLoader The reference to the resource loader
* @return bool
*/
public static function onResourceLoaderTestModules( array &$testModules, ResourceLoader &$resourceLoader ) {
$resourceModules = $resourceLoader->getConfig()->get( 'ResourceModules' );
if (
isset( $resourceModules[ 'ext.visualEditor.mediawiki' ] ) ||
$resourceLoader->isModuleRegistered( 'ext.visualEditor.mediawiki' )
) {
$testModules['qunit']['ext.graph.visualEditor.test'] = array(
'scripts' => array(
'modules/ve-graph/tests/ext.graph.visualEditor.test.js'
),
'dependencies' => array(
'ext.graph.visualEditor',
'ext.graph.vega1',
'ext.visualEditor.test'
),
'localBasePath' => dirname( __DIR__ ),
'remoteExtPath' => 'Graph'
);
}
return true;
}
}
| <?php
/**
* Graph extension Hooks
*
* @file
* @ingroup Extensions
*/
namespace Graph;
use ResourceLoader;
class Hooks {
/**
* Conditionally register the unit testing module for the ext.graph.visualEditor module
* only if that module is loaded
*
* @param array $testModules The array of registered test modules
* @param ResourceLoader $resourceLoader The reference to the resource loader
* @return bool
*/
public static function onResourceLoaderTestModules( array &$testModules, ResourceLoader &$resourceLoader ) {
$resourceModules = $resourceLoader->getConfig()->get( 'ResourceModules' );
if ( isset( $resourceModules[ 'ext.graph.visualEditor' ] ) || $resourceLoader->isModuleRegistered( 'ext.graph.visualEditor' ) ) {
$testModules['qunit']['ext.graph.visualEditor.test'] = array(
'scripts' => array(
'modules/ve-graph/tests/ext.graph.visualEditor.test.js'
),
'dependencies' => array(
'ext.graph.visualEditor',
'ext.graph.vega1',
'ext.visualEditor.test'
),
'localBasePath' => dirname( __DIR__ ),
'remoteExtPath' => 'Graph'
);
}
return true;
}
}
|
Correct import order in tests init file | # tests.__init__
import os
import os.path
import shutil
import tempfile
from mock import patch
import yvs.shared as yvs
temp_dir = tempfile.gettempdir()
local_data_dir_patcher = patch(
'yvs.shared.LOCAL_DATA_DIR_PATH',
os.path.join(temp_dir, 'yvs-data'))
local_cache_dir_patcher = patch(
'yvs.shared.LOCAL_CACHE_DIR_PATH',
os.path.join(temp_dir, 'yvs-cache'))
def set_up():
local_data_dir_patcher.start()
try:
os.mkdir(yvs.LOCAL_DATA_DIR_PATH)
except OSError:
pass
local_cache_dir_patcher.start()
try:
os.mkdir(yvs.LOCAL_CACHE_DIR_PATH)
except OSError:
pass
def tear_down():
try:
shutil.rmtree(yvs.LOCAL_CACHE_DIR_PATH)
except OSError:
pass
local_cache_dir_patcher.stop()
try:
shutil.rmtree(yvs.LOCAL_DATA_DIR_PATH)
except OSError:
pass
local_data_dir_patcher.stop()
| # tests.__init__
import os
import os.path
import shutil
import tempfile
import yvs.shared as yvs
from mock import patch
temp_dir = tempfile.gettempdir()
local_data_dir_patcher = patch(
'yvs.shared.LOCAL_DATA_DIR_PATH',
os.path.join(temp_dir, 'yvs-data'))
local_cache_dir_patcher = patch(
'yvs.shared.LOCAL_CACHE_DIR_PATH',
os.path.join(temp_dir, 'yvs-cache'))
def set_up():
local_data_dir_patcher.start()
try:
os.mkdir(yvs.LOCAL_DATA_DIR_PATH)
except OSError:
pass
local_cache_dir_patcher.start()
try:
os.mkdir(yvs.LOCAL_CACHE_DIR_PATH)
except OSError:
pass
def tear_down():
try:
shutil.rmtree(yvs.LOCAL_CACHE_DIR_PATH)
except OSError:
pass
local_cache_dir_patcher.stop()
try:
shutil.rmtree(yvs.LOCAL_DATA_DIR_PATH)
except OSError:
pass
local_data_dir_patcher.stop()
|
Add column width to posts for larger displays | <div class="post col-md-10 col-lg-8">
@if (isset($post))
<h1>{{{ $post->title }}}</h1>
{{-- Escape html entities, format with paragraph tags --}}
{{-- Leading and trailing paragraph tags are required for leading and trailing paragraphs respectively --}}
<p>{{ str_replace(array("\n","\r\n"), "</p><p>", e($post->content)) }}</p>
<div class="well well-sm clearfix">
<span class="pull-left">{{{ $post->tags }}}</span>
<span class="pull-right">{{ $post->created_at }}</span>
</div>
@else
<h1>Sorry! That post doesn't exist!</h1>
<p>Unfortunately the post you were looking for isn't in the database. Maybe try looking in the <a href="{{ action('BlogController@getList') }}">archive</a> for the post you were seeking.</p>
@endif
</div> | <div class="post">
@if (isset($post))
<h1>{{{ $post->title }}}</h1>
{{-- Escape html entities, format with paragraph tags --}}
{{-- Leading and trailing paragraph tags are required for leading and trailing paragraphs respectively --}}
<p>{{ str_replace(array("\n","\r\n"), "</p><p>", e($post->content)) }}</p>
<div class="well well-sm clearfix">
<span class="pull-left">{{{ $post->tags }}}</span>
<span class="pull-right">{{ $post->created_at }}</span>
</div>
@else
<h1>Sorry! That post doesn't exist!</h1>
<p>Unfortunately the post you were looking for isn't in the database. Maybe try looking in the <a href="{{ action('BlogController@getList') }}">archive</a> for the post you were seeking.</p>
@endif
</div> |
Check update against right property | module.exports = function(sugar, models, assert) {
return function updateMultipleAuthors(cb) {
var firstAuthor = {name: 'foo'};
var secondAuthor = {name: 'bar'};
var authors = [firstAuthor, secondAuthor];
sugar.create(models.Author, authors, function(err, d) {
if(err) return cb(err);
var name = 'joe';
sugar.update(models.Author, [d && d[0]._id, d && d[1]._id], {name: name}, function(err, d) {
if(err) return cb(err);
assert.equal(d && d[0].name, name);
assert.equal(d && d[1].name, name);
cb();
});
});
};
};
| module.exports = function(sugar, models, assert) {
return function updateMultipleAuthors(cb) {
var firstAuthor = {name: 'foo'};
var secondAuthor = {name: 'bar'};
var authors = [firstAuthor, secondAuthor];
sugar.create(models.Author, authors, function(err, d) {
if(err) return cb(err);
var name = 'joe';
sugar.update(models.Author, [d && d[0]._id, d && d[1]._id], {name: name}, function(err, d) {
if(err) return cb(err);
assert.equal(d && d[0], name);
assert.equal(d && d[1], name);
cb();
});
});
};
};
|
Use regex instead of explode | <?php
# Copyright © 2012 Martin Ueding <dev@martin-ueding.de>
class BookmarkHelper extends AppHelper {
var $helpers = array('Html');
function print_bookmark($bookmark) {
echo $this->favicon($bookmark);
echo '<td>';
echo $this->Html->link($bookmark['title'],
array('controller' => 'bookmarks', 'action' => 'visit', $bookmark['id']),
array('class' => 'bookmark_link', 'title' => $bookmark['url']));
echo '</td>';
echo '<td>';
echo $this->Html->link(__('View', true),
array('controller' => 'bookmarks', 'action' => 'view', $bookmark['id']),
array('class' => 'edit_option'));
echo '</td>';
}
function favicon($bookmark) {
$html = '';
if (Configure::read('favicon.show')) {
$url = $this->favicon_url($bookmark['url']);
$html .= '<td><img width="16" height="16" src="'.$url.'" /></td>';
}
return $html;
}
function favicon_url($url) {
preg_match('#(https?://[^/]+)/?.*#', $url, $matches);
if (count($matches) >= 2) {
$favico_url = $matches[1].'/favicon.ico';
}
else {
$favico_url = '';
}
return $favico_url;
}
}
| <?php
# Copyright © 2012 Martin Ueding <dev@martin-ueding.de>
class BookmarkHelper extends AppHelper {
var $helpers = array('Html');
function print_bookmark($bookmark) {
echo $this->favicon($bookmark);
echo '<td>';
echo $this->Html->link($bookmark['title'],
array('controller' => 'bookmarks', 'action' => 'visit', $bookmark['id']),
array('class' => 'bookmark_link', 'title' => $bookmark['url']));
echo '</td>';
echo '<td>';
echo $this->Html->link(__('View', true),
array('controller' => 'bookmarks', 'action' => 'view', $bookmark['id']),
array('class' => 'edit_option'));
echo '</td>';
}
function favicon($bookmark) {
$html = '';
if (Configure::read('favicon.show')) {
$url = $this->favicon_url($bookmark['url']);
$html .= '<td><img width="16" height="16" src="'.$url.'" /></td>';
}
return $html;
}
function favicon_url($url) {
$url = trim(
str_replace(
'http://',
'',
trim($url)
),
'/'
);
$url = explode('/', $url);
$url = 'http://' . $url[0] . '/favicon.ico';
return $url;
}
}
|
ca_on_candidates: Make CSV URL more specific | from utils import CSVScraper
from datetime import date
class OntarioCandidatesPersonScraper(CSVScraper):
csv_url = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vQhrWSeOEC9DaNN2iDKcPC9IH701Al0pELevzSO62maI9WXt1TGvFH2fzUkXjUfujc3ontePcroFbT2/pub?gid=881365071&single=true&output=csv'
encoding = 'utf-8'
updated_at = date(2018, 1, 31)
contact_person = 'andrew@newmode.net'
corrections = {
'district name': {
'Brantford-Brant': 'Brantford\u2014Brant',
}
}
def is_valid_row(self, row):
return any(row.values()) and row['last name'] and row['first name']
| from utils import CSVScraper
from datetime import date
class OntarioCandidatesPersonScraper(CSVScraper):
csv_url = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vQhrWSeOEC9DaNN2iDKcPC9IH701Al0pELevzSO62maI9WXt1TGvFH2fzUkXjUfujc3ontePcroFbT2/pub?output=csv'
encoding = 'utf-8'
updated_at = date(2018, 1, 31)
contact_person = 'andrew@newmode.net'
corrections = {
'district name': {
'Brantford-Brant': 'Brantford\u2014Brant',
}
}
def is_valid_row(self, row):
return any(row.values()) and row['last name'] and row['first name']
|
Remove unnecessary "/" in path | package cmd
import (
"fmt"
"net/http"
"net/url"
"os"
"github.com/cozy/cozy-stack/config"
"github.com/spf13/cobra"
"strconv"
)
// statusCmd represents the status command
var statusCmd = &cobra.Command{
Use: "status",
Short: "Check if the HTTP server is running",
Long: `Check if the HTTP server has been started and answer 200 for /status.`,
RunE: func(cmd *cobra.Command, args []string) error {
if err := Configure(); err != nil {
return err
}
url := &url.URL{
Scheme: "http",
Host: config.GetConfig().Host + ":" + strconv.Itoa(config.GetConfig().Port),
Path: "status",
}
resp, err := http.Get(url.String())
if err != nil {
fmt.Println("Error the HTTP server is not running:", err)
os.Exit(1)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
fmt.Println("Error, unexpected HTTP status code:", resp.Status)
os.Exit(1)
}
fmt.Println("OK, the HTTP server is ready.")
return nil
},
}
func init() {
RootCmd.AddCommand(statusCmd)
}
| package cmd
import (
"fmt"
"net/http"
"net/url"
"os"
"github.com/cozy/cozy-stack/config"
"github.com/spf13/cobra"
"strconv"
)
// statusCmd represents the status command
var statusCmd = &cobra.Command{
Use: "status",
Short: "Check if the HTTP server is running",
Long: `Check if the HTTP server has been started and answer 200 for /status.`,
RunE: func(cmd *cobra.Command, args []string) error {
if err := Configure(); err != nil {
return err
}
url := &url.URL{
Scheme: "http",
Host: config.GetConfig().Host + ":" + strconv.Itoa(config.GetConfig().Port),
Path: "/status",
}
resp, err := http.Get(url.String())
if err != nil {
fmt.Println("Error the HTTP server is not running:", err)
os.Exit(1)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
fmt.Println("Error, unexpected HTTP status code:", resp.Status)
os.Exit(1)
}
fmt.Println("OK, the HTTP server is ready.")
return nil
},
}
func init() {
RootCmd.AddCommand(statusCmd)
}
|
Replace $this->container->get() with $this->get() in controllers extending abstract controller. | <?php
/**
* @author Igor Nikolaev <igor.sv.n@gmail.com>
* @copyright Copyright (c) 2015, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Darvin\ImageBundle\Controller;
use Darvin\ImageBundle\Entity\Image\AbstractImage;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
/**
* Image controller
*/
class ImageController extends Controller
{
/**
* @param int $id Image ID
*
* @return \Symfony\Component\HttpFoundation\Response
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*/
public function deleteAction($id)
{
$em = $this->getEntityManager();
$image = $em->getRepository(AbstractImage::ABSTRACT_IMAGE_CLASS)->find($id);
if (empty($image)) {
throw $this->createNotFoundException(sprintf('Unable to find image by ID "%d".', $id));
}
$em->remove($image);
$em->flush();
return new Response();
}
/**
* @return \Doctrine\ORM\EntityManager
*/
private function getEntityManager()
{
return $this->get('doctrine.orm.entity_manager');
}
}
| <?php
/**
* @author Igor Nikolaev <igor.sv.n@gmail.com>
* @copyright Copyright (c) 2015, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Darvin\ImageBundle\Controller;
use Darvin\ImageBundle\Entity\Image\AbstractImage;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
/**
* Image controller
*/
class ImageController extends Controller
{
/**
* @param int $id Image ID
*
* @return \Symfony\Component\HttpFoundation\Response
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*/
public function deleteAction($id)
{
$em = $this->getEntityManager();
$image = $em->getRepository(AbstractImage::ABSTRACT_IMAGE_CLASS)->find($id);
if (empty($image)) {
throw $this->createNotFoundException(sprintf('Unable to find image by ID "%d".', $id));
}
$em->remove($image);
$em->flush();
return new Response();
}
/**
* @return \Doctrine\ORM\EntityManager
*/
private function getEntityManager()
{
return $this->container->get('doctrine.orm.entity_manager');
}
}
|
Set initialLine of found file | 'use babel'
import * as util from './util'
import { Range } from 'atom'
export default {
wordRegExp: /([\w\.\-_]+)/,
providerName: "moie-modelica",
setClient(client) {
this.client = client
console.log("setting client in hyperclickProvider")
},
getSuggestionForWord(editor, text, range) {
self = this
return new Promise((resolve, reject) => {
if(util.isModelicaFile(editor.getPath()) && text.trim() !== "") {
const className = text
self.client.getContainingFile(
className,
(data) => {
resolve({
range:range,
callback: () => atom.workspace.open(data.path, {initialLine: data.line})
})
},
(xhr, status, error) => {
resolve({
range: range,
callback: () => atom.notifications.addWarning("Can't go to anywhere :-(", {detail:`can't find source for ${className}`})
})
})
}
})
}
}
| 'use babel'
import * as util from './util'
import { Range } from 'atom'
export default {
wordRegExp: /([\w\.\-_]+)/,
providerName: "moie-modelica",
setClient(client) {
this.client = client
console.log("setting client in hyperclickProvider")
},
getSuggestionForWord(editor, text, range) {
self = this
return new Promise((resolve, reject) => {
if(util.isModelicaFile(editor.getPath()) && text.trim() !== "") {
const className = text
self.client.getContainingFile(
className,
(data) => {
resolve({
range:range,
callback: () => util.openFile(data.path)
})
},
(xhr, status, error) => {
resolve({
range: range,
callback: () => atom.notifications.addWarning("Can't go to anywhere :-(", {detail:`can't find source for ${className}`})
})
})
}
})
}
}
|
Add another url pattern for debugging public layers | from django.conf.urls.defaults import *
import time
urlpatterns = patterns('lingcod.layers.views',
url(r'^public/$',
'get_public_layers',
name='public-data-layers'),
# Useful for debugging, avoids GE caching interference
url(r'^public/cachebuster/%s' % str(time.time()),
'get_public_layers',
name='public-data-layers-cachebuster'),
url(r'^kml_file/(?P<session_key>\w+)/(?P<uid>[\w_]+).kml',
'get_kml_file',
name='kml-file'),
url(r'^privatekml/(?P<session_key>\w+)/$',
'get_privatekml_list',
name='layers-privatekml-list'),
url(r'^privatekml/(?P<session_key>\w+)/(?P<pk>\d+)/$',
'get_privatekml',
name='layers-privatekml'),
url(r'^privatekml/(?P<session_key>\w+)/(?P<pk>\d+)/(?P<path>[^\z]+)$',
'get_relative_to_privatekml',
name='layers-privatekml-relative'),
)
| from django.conf.urls.defaults import *
urlpatterns = patterns('lingcod.layers.views',
url(r'^public/',
'get_public_layers',
name='public-data-layers'),
url(r'^kml_file/(?P<session_key>\w+)/(?P<uid>[\w_]+).kml',
'get_kml_file',
name='kml-file'),
url(r'^privatekml/(?P<session_key>\w+)/$',
'get_privatekml_list',
name='layers-privatekml-list'),
url(r'^privatekml/(?P<session_key>\w+)/(?P<pk>\d+)/$',
'get_privatekml',
name='layers-privatekml'),
url(r'^privatekml/(?P<session_key>\w+)/(?P<pk>\d+)/(?P<path>[^\z]+)$',
'get_relative_to_privatekml',
name='layers-privatekml-relative'),
)
|
Trim whitespace from argument on insert | /* Copyright 2015 Troy D. Heninger
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dsp.servlet;
import java.util.List;
class DspInsert extends DspToken implements Insert
{
static final String NAME = "insert";
DspInsert(String eat, List<DspArg> args)
{
super(eat, args);
} // DspInsert()
public String getPath(DspCompile comp, int index) throws DspParseException
{
if (args.size() != 1) throw new DspParseException("file name", "an expression", index, comp);
DspArg arg = args.get(0);
String expr = arg.getExpr();
if (expr != null) throw new DspParseException("file name", expr, index, comp);
return arg.getText().trim();
} // getPath()
public String toString()
{
return toString(NAME);
} // toString()
} // DspInsert
| /* Copyright 2015 Troy D. Heninger
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dsp.servlet;
import java.util.List;
class DspInsert extends DspToken implements Insert
{
static final String NAME = "insert";
DspInsert(String eat, List<DspArg> args)
{
super(eat, args);
} // DspInsert()
public String getPath(DspCompile comp, int index) throws DspParseException
{
if (args.size() != 1) throw new DspParseException("file name", "an expression", index, comp);
DspArg arg = args.get(0);
String expr = arg.getExpr();
if (expr != null) throw new DspParseException("file name", expr, index, comp);
return arg.getText();
} // getPath()
public String toString()
{
return toString(NAME);
} // toString()
} // DspInsert
|
Disable timezone support for tests, as the date / time fields' tests use naive datatime objects and fail if it's enabled. | # -*- coding: utf-8 -*-
"""
Settings overrided for test time
"""
import os
from django.conf import settings
DIRNAME = os.path.dirname(__file__)
INSTALLED_APPS = tuple(settings.INSTALLED_APPS) + (
'modeltranslation.tests',
)
# IMO this is unimportant
#if django.VERSION[0] >= 1 and django.VERSION[1] >= 3:
#INSTALLED_APPS += ('django.contrib.staticfiles',)
#STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(DIRNAME, 'media/')
LANGUAGES = (('de', 'Deutsch'),
('en', 'English'))
LANGUAGE_CODE = 'de'
MODELTRANSLATION_DEFAULT_LANGUAGE = 'de'
USE_I18N = True
USE_TZ = False
MODELTRANSLATION_AUTO_POPULATE = False
MODELTRANSLATION_FALLBACK_LANGUAGES = ()
| # -*- coding: utf-8 -*-
"""
Settings overrided for test time
"""
import os
from django.conf import settings
DIRNAME = os.path.dirname(__file__)
INSTALLED_APPS = tuple(settings.INSTALLED_APPS) + (
'modeltranslation.tests',
)
# IMO this is unimportant
#if django.VERSION[0] >= 1 and django.VERSION[1] >= 3:
#INSTALLED_APPS += ('django.contrib.staticfiles',)
#STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(DIRNAME, 'media/')
LANGUAGES = (('de', 'Deutsch'),
('en', 'English'))
LANGUAGE_CODE = 'de'
MODELTRANSLATION_DEFAULT_LANGUAGE = 'de'
USE_I18N = True
MODELTRANSLATION_AUTO_POPULATE = False
MODELTRANSLATION_FALLBACK_LANGUAGES = ()
|
Write sourcemaps to a separate file. | var gulp = require('gulp'),
mocha = require('gulp-mocha'),
eslint = require('gulp-eslint'),
babel = require('gulp-babel'),
sourcemaps = require('gulp-sourcemaps');
require('babel/register');
gulp.task('lint', function () {
return gulp
.src(['./src/**/*.js', './tests/**/*.js'])
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failOnError());
});
gulp.task('test', ['lint'], function () {
return gulp
.src('./tests/**/*.js', {read: false})
.pipe(mocha());
});
gulp.task('dist', ['test'], function () {
return gulp
.src('./src/**/*.js')
.pipe(sourcemaps.init())
.pipe(babel())
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('./dist'));
});
gulp.task('watch', function () {
gulp.watch(['./src/**/*', './tests/**/*'], ['default']);
});
gulp.task('default', ['dist']);
| var gulp = require('gulp'),
mocha = require('gulp-mocha'),
eslint = require('gulp-eslint'),
babel = require('gulp-babel'),
sourcemaps = require('gulp-sourcemaps');
require('babel/register');
gulp.task('lint', function () {
return gulp
.src(['./src/**/*.js', './tests/**/*.js'])
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failOnError());
});
gulp.task('test', ['lint'], function () {
return gulp
.src('./tests/**/*.js', {read: false})
.pipe(mocha());
});
gulp.task('dist', ['test'], function () {
return gulp
.src('./src/**/*.js')
.pipe(sourcemaps.init())
.pipe(babel())
.pipe(sourcemaps.write(''))
.pipe(gulp.dest('./dist'));
});
gulp.task('watch', function () {
gulp.watch(['./src/**/*', './tests/**/*'], ['default']);
});
gulp.task('default', ['dist']);
|
Use is instead of == for types. | from nolang.error import AppError
from nolang.objects.root import W_Root
class W_ListObject(W_Root):
def __init__(self, w_items):
self._w_items = w_items
def str(self, space):
return '[' + ', '.join([space.str(i) for i in self._w_items]) + ']'
def len(self, space):
return len(self._w_items)
def unwrap_index(self, space, w_index):
try:
i = space.int_w(w_index)
except AppError as ae:
if space.type(ae.w_exception) is space.w_typeerror:
raise space.apperr(space.w_typeerror, 'list index must be int')
raise
if i < 0 or i >= len(self._w_items):
raise space.apperr(space.w_indexerror, 'list index out of range')
return i
def getitem(self, space, w_index):
return self._w_items[self.unwrap_index(space, w_index)]
def setitem(self, space, w_index, w_value):
self._w_items[self.unwrap_index(space, w_index)] = w_value
| from nolang.error import AppError
from nolang.objects.root import W_Root
class W_ListObject(W_Root):
def __init__(self, w_items):
self._w_items = w_items
def str(self, space):
return '[' + ', '.join([space.str(i) for i in self._w_items]) + ']'
def len(self, space):
return len(self._w_items)
def unwrap_index(self, space, w_index):
try:
i = space.int_w(w_index)
except AppError as ae:
if space.type(ae.w_exception) == space.w_typeerror:
raise space.apperr(space.w_typeerror, 'list index must be int')
raise
if i < 0 or i >= len(self._w_items):
raise space.apperr(space.w_indexerror, 'list index out of range')
return i
def getitem(self, space, w_index):
return self._w_items[self.unwrap_index(space, w_index)]
def setitem(self, space, w_index, w_value):
self._w_items[self.unwrap_index(space, w_index)] = w_value
|
Fix early return failure to reset context |
var Picker = function(context) {
this.context = context;
}
Picker.prototype = {
pick: function(node, x, y, lx, ly) {
var ctx = this.context;
var tx = node.x || 0;
var ty = node.y || 0;
ctx.save();
ctx.translate(tx, ty);
// Apply transform to local coordinate values
lx -= tx;
ly -= ty;
var result = node.pick(ctx, x, y, lx, ly) && node;
if (!result && node.children) {
for (var i=node.children.length-1; i>=0; i--) {
result = this.pick(node.children[i], x, y, lx, ly);
if (result) {
break;
}
}
}
ctx.restore();
return result;
}
};
module.exports = Picker; |
var Picker = function(context) {
this.context = context;
}
Picker.prototype = {
pick: function(node, x, y, lx, ly) {
var ctx = this.context;
var tx = node.x || 0;
var ty = node.y || 0;
ctx.save();
ctx.translate(tx, ty);
// Apply transform to local coordinate values
lx -= tx;
ly -= ty;
var result = node.pick(ctx, x, y, lx, ly);
if (result) {
return node;
}
if (node.children) {
for (var i=node.children.length-1; i>=0; i--) {
result = this.pick(node.children[i], x, y, lx, ly);
if (result) {
break;
}
}
}
ctx.restore();
return result;
}
};
module.exports = Picker; |
Upgrade Localstack image to version 0.12.3 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.test.infra.aws2.services;
public class AWSSQSLocalContainerService extends AWSLocalContainerService {
public AWSSQSLocalContainerService() {
super("localstack/localstack:0.12.3", Service.SQS);
}
}
| /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.test.infra.aws2.services;
public class AWSSQSLocalContainerService extends AWSLocalContainerService {
public AWSSQSLocalContainerService() {
super("localstack/localstack:0.12.2", Service.SQS);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.