text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Exclude test package from builds.
|
#!/usr/bin/env python
import os
from setuptools import setup, find_packages
from eodatasets import __version__ as version
# Append TeamCity build number if it gives us one.
if 'BUILD_NUMBER' in os.environ and version.endswith('b'):
version += '' + os.environ['BUILD_NUMBER']
setup(
name="eodatasets",
version=version,
packages=find_packages(exclude=('tests', 'tests.*')),
install_requires=[
'click',
'python-dateutil',
'gdal',
'numpy',
'pathlib',
'pyyaml',
],
entry_points='''
[console_scripts]
eod-package=eodatasets.scripts.package:cli
eod-generate-browse=eodatasets.scripts.generatebrowse:cli
''',
)
|
#!/usr/bin/env python
import os
from setuptools import setup, find_packages
from eodatasets import __version__ as version
# Append TeamCity build number if it gives us one.
if 'BUILD_NUMBER' in os.environ and version.endswith('b'):
version += '' + os.environ['BUILD_NUMBER']
setup(
name="eodatasets",
version=version,
packages=find_packages(),
install_requires=[
'click',
'python-dateutil',
'gdal',
'numpy',
'pathlib',
'pyyaml',
],
entry_points='''
[console_scripts]
eod-package=eodatasets.scripts.package:cli
eod-generate-browse=eodatasets.scripts.generatebrowse:cli
''',
)
|
Change color of test button to match app
|
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
Button,
TouchableHighlight
} from 'react-native';
import {dispatch} from 'ringa';
import {attach, depend, dependency, walkReactParents} from 'react-ringa';
import SixController from '../global/SixController';
export default class Child extends React.Component {
constructor() {
super();
this.displayMessage = this.displayMessage.bind(this);
}
componentDidMount() {
let topBus = undefined;
walkReactParents(this, (parent) => topBus = parent.bus ? parent.bus : topBus);
this.setState({
bus: topBus
})
}
displayMessage() {
dispatch(SixController.UPDATE_MESSAGE, {message: 'This is from Child'}, this.state.bus);
}
render() {
return (
<View>
<Button
onPress={this.displayMessage}
title="Update Message"
style={styles.button}
color='#6A85B1'
/>
</View>
);
}
}
const styles = StyleSheet.create({
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 5,
},
button: {
color: '#841584'
},
});
|
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
Button,
TouchableHighlight
} from 'react-native';
import {dispatch} from 'ringa';
import {attach, depend, dependency, walkReactParents} from 'react-ringa';
import SixController from '../global/SixController';
export default class Child extends React.Component {
constructor() {
super();
this.displayMessage = this.displayMessage.bind(this);
}
componentDidMount() {
let topBus = undefined;
walkReactParents(this, (parent) => topBus = parent.bus ? parent.bus : topBus);
this.setState({
bus: topBus
})
}
displayMessage() {
dispatch(SixController.UPDATE_MESSAGE, {message: 'This is from Child'}, this.state.bus);
}
render() {
return (
<View>
<Button
onPress={this.displayMessage}
title="Update Message"
style={styles.button}
/>
</View>
);
}
}
const styles = StyleSheet.create({
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 5,
},
button: {
color: '#841584'
},
});
|
Add service to retrieve list of APIs by user
|
/**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* 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 io.gravitee.repository.api;
import io.gravitee.repository.model.Api;
import java.util.Optional;
import java.util.Set;
/**
* @author David BRASSELY (brasseld at gmail.com)
*/
public interface ApiRepository {
Optional<Api> findByName(String apiName);
Set<Api> findAll();
Set<Api> findByTeam(String teamName);
Set<Api> findByUser(String username);
Api create(Api api);
Api update(Api api);
void delete(String apiName);
int countByUser(String username);
int countByTeam(String teamName);
}
|
/**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* 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 io.gravitee.repository.api;
import io.gravitee.repository.model.Api;
import java.util.Optional;
import java.util.Set;
/**
* @author David BRASSELY (brasseld at gmail.com)
*/
public interface ApiRepository {
Optional<Api> findByName(String apiName);
Set<Api> findAll();
Set<Api> findByTeam(String teamName);
Api create(Api api);
Api update(Api api);
void delete(String apiName);
int countByUser(String username);
int countByTeam(String teamName);
}
|
Update dsub version to 0.3.3.dev0
PiperOrigin-RevId: 253060658
|
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.3.3.dev0'
|
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.3.2'
|
Update FF icon to correct size
|
var buttons = require('sdk/ui/button/action');
var panels = require("sdk/panel");
var self = require("sdk/self");
const {Cu} = require("chrome");
Cu.import(self.data.url('freedom-for-firefox.jsm'));
// Main uProxy button.
var button = buttons.ActionButton({
id: "uProxy-button",
label: "uProxy-button",
icon: {
"32": "./icons/NotLoggedIn_32.gif"
},
onClick: start
});
var panel;
// Load freedom.
var manifest = self.data.url('core/freedom-module.json');
freedom(manifest, {}).then(function(uproxy) {
// Panel that gets displayed when user clicks the button.
panel = panels.Panel({
width: 371,
height: 600,
contentURL: self.data.url("index.html")
})
// Set up connection between freedom and content script.
require('glue.js').setUpConnection(new uproxy(), panel, button);
});
function start(state) {
panel.show({
position: button,
});
}
|
var buttons = require('sdk/ui/button/action');
var panels = require("sdk/panel");
var self = require("sdk/self");
const {Cu} = require("chrome");
Cu.import(self.data.url('freedom-for-firefox.jsm'));
// Main uProxy button.
var button = buttons.ActionButton({
id: "uProxy-button",
label: "uProxy-button",
icon: {
"16": "./icons/NotLoggedIn_32.gif",
"19": "./icons/NotLoggedIn_32.gif",
"128": "./icons/LoggedIn_256.gif"
},
onClick: start
});
var panel;
// Load freedom.
var manifest = self.data.url('core/freedom-module.json');
freedom(manifest, {}).then(function(uproxy) {
// Panel that gets displayed when user clicks the button.
panel = panels.Panel({
width: 371,
height: 600,
contentURL: self.data.url("index.html")
})
// Set up connection between freedom and content script.
require('glue.js').setUpConnection(new uproxy(), panel, button);
});
function start(state) {
panel.show({
position: button,
});
}
|
Use `django.templatetags.static`to load the file
Debugging this issue: https://github.com/timmyomahony/django-pagedown/issues/25
|
from django.conf import settings
def compatible_staticpath(path):
'''
Try to return a path compatible all the way back to Django 1.2. If anyone
has a cleaner or better way to do this let me know!
'''
try:
# >= 1.4
from django.templatetags.static import static
return static(path)
except ImportError:
pass
try:
# >= 1.3
return '%s/%s' % (settings.STATIC_URL.rstrip('/'), path)
except AttributeError:
pass
try:
return '%s/%s' % (settings.PAGEDOWN_URL.rstrip('/'), path)
except AttributeError:
pass
return '%s/%s' % (settings.MEDIA_URL.rstrip('/'), path)
|
from django.conf import settings
def compatible_staticpath(path):
'''
Try to return a path compatible all the way back to Django 1.2. If anyone
has a cleaner or better way to do this let me know!
'''
try:
# >= 1.4
from django.contrib.staticfiles.storage import staticfiles_storage
return staticfiles_storage.url(path)
except ImportError:
pass
try:
# >= 1.3
return '%s/%s' % (settings.STATIC_URL.rstrip('/'), path)
except AttributeError:
pass
try:
return '%s/%s' % (settings.PAGEDOWN_URL.rstrip('/'), path)
except AttributeError:
pass
return '%s/%s' % (settings.MEDIA_URL.rstrip('/'), path)
|
Add a close method to EnhancedDataset that won't raise a RuntimeError
|
#!python
# coding=utf-8
from netCDF4 import Dataset
class EnhancedDataset(Dataset):
def __init__(self, *args, **kwargs):
super(EnhancedDataset, self).__init__(*args, **kwargs)
def get_variables_by_attributes(self, **kwargs):
vs = []
has_value_flag = False
for vname in self.variables:
var = self.variables[vname]
for k, v in kwargs.iteritems():
if hasattr(var, k) and getattr(var, k) == v:
has_value_flag = True
else:
has_value_flag = False
break
if has_value_flag is True:
vs.append(self.variables[vname])
return vs
def close(self):
try:
self.sync()
self.close()
except RuntimeError:
pass
|
#!python
# coding=utf-8
from netCDF4 import Dataset
class EnhancedDataset(Dataset):
def __init__(self, *args, **kwargs):
super(EnhancedDataset, self).__init__(*args, **kwargs)
def get_variables_by_attributes(self, **kwargs):
vs = []
has_value_flag = False
for vname in self.variables:
var = self.variables[vname]
for k, v in kwargs.iteritems():
if hasattr(var, k) and getattr(var, k) == v:
has_value_flag = True
else:
has_value_flag = False
break
if has_value_flag is True:
vs.append(self.variables[vname])
return vs
|
Support for controller API concerning graphs.
|
App.Graphs = Ember.Object.extend({
graph: function(emberId, entityName, entityType) {
hash = {
url: ((!localStorage.apiDomain) ? '' : '//' + localStorage.apiDomain) + '/api/v1/graphs?entityType=' + entityType + '&entityName=' + entityName,
type: 'GET',
dataType: 'json',
success: function (data, textStatus, jqXHR) {
var numericArray = App.associativeToNumericArray(data);
if (entityType == 'node') {
App.Node.find(emberId).set('graphs', numericArray);
} else if (entityType == 'vm') {
return App.Vm.find(emberId).set('graphs', numericArray);
}
}
}
hash = $.extend(hash, App.ajaxSetup);
return App.ajaxPromise(hash);
}
});
App.graphs = App.Graphs.create();
|
App.Graphs = Ember.Object.extend({
graph: function(emberId, entityName, entityType) {
$.ajax({
url: ((!localStorage.apiDomain) ? '' : '//' + localStorage.apiDomain) + '/graphs/getGraphs.php?entityType=' + entityType + '&entityName=' + entityName,
type: 'GET',
dataType: 'json',
success: function (data, textStatus, jqXHR) {
var numericArray = App.associativeToNumericArray(data);
if (entityType == 'node') {
App.Node.find(emberId).set('graphs', numericArray);
} else if (entityType == 'vm') {
return App.Vm.find(emberId).set('graphs', numericArray);
}
}
});
}
});
App.graphs = App.Graphs.create();
|
Add Access-Control-Allow-Origin for CORS from gh-pages
|
var express = require('express');
var path = require('path');
var expressValidator = require('express-validator');
var home = require('./routes/home.js');
var api = require('./routes/api.js');
var port = process.env.PORT || 5000;
var app = express();
app.configure(function () {
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.logger());
app.use(express.urlencoded());
app.use(express.json());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'controllers')));
app.use(express.static(path.join(__dirname, 'services')));
app.use(expressValidator());
});
app.all('/', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
app.get('/', home.index);
app.put('/api/subscriptions', api.createSubscription);
app.get('/api/subscriptions', api.readSubscriptions);
app.del('/api/subscriptions', api.deleteSubscription);
app.get('/api/updates', api.readUpdates);
app.listen(port);
|
var express = require('express');
var path = require('path');
var expressValidator = require('express-validator');
var home = require('./routes/home.js');
var api = require('./routes/api.js');
var port = process.env.PORT || 5000;
var app = express();
app.configure(function () {
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.logger());
app.use(express.urlencoded());
app.use(express.json());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'controllers')));
app.use(express.static(path.join(__dirname, 'services')));
app.use(expressValidator());
});
app.get('/', home.index);
app.put('/api/subscriptions', api.createSubscription);
app.get('/api/subscriptions', api.readSubscriptions);
app.del('/api/subscriptions', api.deleteSubscription);
app.get('/api/updates', api.readUpdates);
app.listen(port);
|
Reorder imports to dodge a settings problem.
|
#! /usr/bin/env python3
from os import path
import sys
from colour_runner.django_runner import ColourRunnerMixin
from django.conf import settings
settings.configure(
INSTALLED_APPS=(
# Put contenttypes before auth to work around test issue.
# See: https://code.djangoproject.com/ticket/10827#comment:12
'django.contrib.contenttypes',
'django.contrib.auth',
'django.contrib.sessions',
'django.contrib.admin',
'django-admin-sso',
'django-crispy-forms',
'incuna_auth',
),
PASSWORD_HASHERS = ('django.contrib.auth.hashers.MD5PasswordHasher',),
AUTH_USER_MODEL='tests.User',
ROOT_URLCONF='incuna_auth.urls',
REST_FRAMEWORK={
'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',),
'DEFAULT_RENDERER_CLASSES': ('rest_framework.renderers.JSONRenderer',),
},
TEST_DISCOVER_TOP_LEVEL=path.dirname(path.dirname(__file__)),
)
from django.test.runner import DiscoverRunner
class Runner(ColourRunnerMixin, DiscoverRunner):
pass
test_runner = Runner(verbosity=1)
failures = test_runner.run_tests(['tests'])
if failures:
sys.exit(1)
|
#! /usr/bin/env python3
from os import path
import sys
from colour_runner.django_runner import ColourRunnerMixin
from django.conf import settings
from django.test.runner import DiscoverRunner
settings.configure(
INSTALLED_APPS=(
# Put contenttypes before auth to work around test issue.
# See: https://code.djangoproject.com/ticket/10827#comment:12
'django.contrib.contenttypes',
'django.contrib.auth',
'django.contrib.sessions',
'django.contrib.admin',
'django-admin-sso',
'django-crispy-forms',
'incuna_auth',
),
PASSWORD_HASHERS = ('django.contrib.auth.hashers.MD5PasswordHasher',),
AUTH_USER_MODEL='tests.User',
ROOT_URLCONF='incuna_auth.urls',
REST_FRAMEWORK={
'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',),
'DEFAULT_RENDERER_CLASSES': ('rest_framework.renderers.JSONRenderer',),
},
TEST_DISCOVER_TOP_LEVEL=path.dirname(path.dirname(__file__)),
)
class Runner(ColourRunnerMixin, DiscoverRunner):
pass
test_runner = Runner(verbosity=1)
failures = test_runner.run_tests(['tests'])
if failures:
sys.exit(1)
|
Append menu to main menu if extensions doesn't exist.
Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
|
<?php namespace Orchestra\Control;
use Orchestra\Contracts\Foundation\Foundation;
class ControlMenuHandler
{
/**
* ACL instance.
*
* @var \Orchestra\Contracts\Authorization\Authorization
*/
protected $acl;
/**
* Menu instance.
*
* @var \Orchestra\Widget\Handlers\Menu
*/
protected $menu;
/**
* Construct a new handler.
*
* @param \Orchestra\Contracts\Foundation\Foundation $foundation
*/
public function __construct(Foundation $foundation)
{
$this->menu = $foundation->menu();
$this->acl = $foundation->acl();
}
/**
* Create a handler for `orchestra.ready: admin` event.
*
* @return void
*/
public function handle()
{
if (! ($this->acl->can('manage roles') || $this->acl->can('manage acl'))) {
return ;
}
$parent = $this->menu->has('extensions') ? '^:extensions' : '<:home';
$this->menu->add('control', $parent)
->title('Control')
->link(handles('orchestra::control'));
}
}
|
<?php namespace Orchestra\Control;
use Orchestra\Contracts\Foundation\Foundation;
class ControlMenuHandler
{
/**
* ACL instance.
*
* @var \Orchestra\Contracts\Authorization\Authorization
*/
protected $acl;
/**
* Menu instance.
*
* @var \Orchestra\Widget\Handlers\Menu
*/
protected $menu;
/**
* Construct a new handler.
*
* @param \Orchestra\Contracts\Foundation\Foundation $foundation
*/
public function __construct(Foundation $foundation)
{
$this->menu = $foundation->menu();
$this->acl = $foundation->acl();
}
/**
* Create a handler for `orchestra.ready: admin` event.
*
* @return void
*/
public function handle()
{
if (! ($this->acl->can('manage roles') || $this->acl->can('manage acl'))) {
return ;
}
$this->menu->add('control', '^:extensions')
->title('Control')
->link(handles('orchestra::control'));
}
}
|
Fix the redirect via origin so we don't get a //
git-svn-id: 3b6cb4556d214d66df54bca2662d7ef408f367bf@2482 46e82423-29d8-e211-989e-002590a4cdd4
|
<?
# $Id: logout.php,v 1.1.2.13 2003-09-25 10:46:14 dan Exp $
#
# Copyright (c) 1998-2003 DVL Software Limited
require_once($_SERVER['DOCUMENT_ROOT'] . '/include/common.php');
require_once($_SERVER['DOCUMENT_ROOT'] . '/include/freshports.php');
require_once($_SERVER['DOCUMENT_ROOT'] . '/include/databaselogin.php');
freshports_CookieClear();
if (IsSet($_GET['origin'])) {
$origin = $_GET['origin'];
} else {
$origin = '';
}
if ($origin == '/index.php') {
$origin = '';
}
header("Location: /$origin"); /* Redirect browser to PHP web site */
exit; /* Make sure that code below does not get executed when we redirect. */
?>
<html>
<head>
<title></title>
</head
<body>
</body>
</html>
|
<?
# $Id: logout.php,v 1.1.2.12 2003-07-04 14:59:16 dan Exp $
#
# Copyright (c) 1998-2003 DVL Software Limited
require_once($_SERVER['DOCUMENT_ROOT'] . '/include/common.php');
require_once($_SERVER['DOCUMENT_ROOT'] . '/include/freshports.php');
require_once($_SERVER['DOCUMENT_ROOT'] . '/include/databaselogin.php');
freshports_CookieClear();
if (IsSet($_GET['origin'])) {
$origin = $_GET['origin'];
} else {
$origin = '/';
}
if ($origin == '/index.php') {
$origin = '/';
}
header('Location: http://' . $_SERVER['HTTP_HOST'] . "/$origin"); /* Redirect browser to PHP web site */
exit; /* Make sure that code below does not get executed when we redirect. */
?>
<html>
<head>
<title></title>
</head
<body>
</body>
</html>
|
Add javadocs to example system test.
As required by checkstyle settings.
|
package nl.tudelft.jpacman.integration;
import nl.tudelft.jpacman.Launcher;
import nl.tudelft.jpacman.game.Game;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* An example test class that conducts integration tests.
*/
public class StartupSystemTest {
private Launcher launcher;
/**
* Start a launcher, which can display the user interface.
*/
@BeforeEach
public void before() {
launcher = new Launcher();
}
/**
* Close the user interface.
*/
@AfterEach
public void after() {
launcher.dispose();
}
/**
* The simplest test that just starts the
* game and checks it is indeed in progress.
*/
@Test
public void gameIsRunning() {
launcher.launch();
getGame().start();
assertThat(getGame().isInProgress()).isTrue();
}
private Game getGame() {
return launcher.getGame();
}
}
|
package nl.tudelft.jpacman.integration;
import nl.tudelft.jpacman.Launcher;
import nl.tudelft.jpacman.game.Game;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class StartupSystemTest {
private Launcher launcher;
@BeforeEach
public void before() {
launcher = new Launcher();
}
@AfterEach
public void after() {
launcher.dispose();
}
@Test
public void gameIsRunning() {
launcher.launch();
getGame().start();
assertThat(getGame().isInProgress()).isTrue();
}
private Game getGame() {
return launcher.getGame();
}
}
|
Add two more tests for defaultFields
|
var assert = require('assert')
var ethUtil = require('../index.js')
describe('define', function () {
const fields = [{
word: true,
default: new Buffer([])
}, {
name: 'empty',
allowZero: true,
length: 20,
default: new Buffer([])
}, {
name: 'cannotBeZero',
allowZero: false,
default: new Buffer([ 0 ])
}, {
name: 'value',
default: new Buffer([])
}, {
name: 'r',
length: 32,
allowLess: true,
default: ethUtil.zeros(32)
}]
var someOb = {}
ethUtil.defineProperties(someOb, fields)
it('should trim zeros', function () {
// Define Properties
someOb.r = '0x00004'
assert.equal(someOb.r.toString('hex'), '04')
someOb.r = new Buffer([0, 0, 0, 0, 4])
assert.equal(someOb.r.toString('hex'), '04')
})
it('shouldn\'t allow wrong size for exact size requirements', function () {
assert.throws(function () {
const tmp = [{
name: 'mustBeExactSize',
allowZero: false,
length: 20,
default: new Buffer([1, 2, 3, 4])
}]
ethUtil.defineProperties(someOb, tmp)
})
})
})
|
var assert = require('assert')
var ethUtil = require('../index.js')
describe('define', function () {
const fields = [{
word: true,
default: new Buffer([])
}, {
name: 'empty',
allowZero: true,
length: 20,
default: new Buffer([])
}, {
name: 'value',
default: new Buffer([])
}, {
name: 'r',
length: 32,
allowLess: true,
default: ethUtil.zeros(32)
}]
var someOb = {}
ethUtil.defineProperties(someOb, fields)
it('should trim zeros', function () {
// Define Properties
someOb.r = '0x00004'
assert.equal(someOb.r.toString('hex'), '04')
someOb.r = new Buffer([0, 0, 0, 0, 4])
assert.equal(someOb.r.toString('hex'), '04')
})
})
|
fix: Add linked bank accounts to supplier dashboard
|
from __future__ import unicode_literals
from frappe import _
def get_data():
return {
'heatmap': True,
'heatmap_message': _('This is based on transactions against this Supplier. See timeline below for details'),
'fieldname': 'supplier',
'non_standard_fieldnames': {
'Payment Entry': 'party_name',
'Bank Account': 'party'
},
'transactions': [
{
'label': _('Procurement'),
'items': ['Request for Quotation', 'Supplier Quotation']
},
{
'label': _('Orders'),
'items': ['Purchase Order', 'Purchase Receipt', 'Purchase Invoice']
},
{
'label': _('Payments'),
'items': ['Payment Entry']
},
{
'label': _('Bank'),
'items': ['Bank Account']
},
{
'label': _('Pricing'),
'items': ['Pricing Rule']
}
]
}
|
from __future__ import unicode_literals
from frappe import _
def get_data():
return {
'heatmap': True,
'heatmap_message': _('This is based on transactions against this Supplier. See timeline below for details'),
'fieldname': 'supplier',
'non_standard_fieldnames': {
'Payment Entry': 'party_name'
},
'transactions': [
{
'label': _('Procurement'),
'items': ['Request for Quotation', 'Supplier Quotation']
},
{
'label': _('Orders'),
'items': ['Purchase Order', 'Purchase Receipt', 'Purchase Invoice']
},
{
'label': _('Payments'),
'items': ['Payment Entry']
},
{
'label': _('Pricing'),
'items': ['Pricing Rule']
}
]
}
|
Add BL4 to Tier Shift mod
|
exports.BattleScripts = {
init: function () {
for (var i in this.data.Pokedex) {
var tier = '';
var adjustment = 0;
// mega evolutions get the same stat boost as their base forme
if (this.data.FormatsData[i]) tier = this.data.FormatsData[i].tier || this.data.FormatsData[toId(this.getTemplate(i).baseSpecies)].tier;
switch (tier) {
case 'BL':
case 'UU':
adjustment = 5;
break;
case 'BL2':
case 'RU':
adjustment = 10;
break;
case 'BL3':
case 'NU':
case 'BL4':
case 'PU':
case 'NFE':
case 'LC Uber':
case 'LC':
adjustment = 15;
}
if (adjustment) {
for (var j in this.data.Pokedex[i].baseStats) {
this.modData('Pokedex', i).baseStats[j] = this.clampIntRange(this.data.Pokedex[i].baseStats[j] + adjustment, 1, 255);
}
}
}
}
};
|
exports.BattleScripts = {
init: function () {
for (var i in this.data.Pokedex) {
var tier = '';
var adjustment = 0;
// mega evolutions get the same stat boost as their base forme
if (this.data.FormatsData[i]) tier = this.data.FormatsData[i].tier || this.data.FormatsData[toId(this.getTemplate(i).baseSpecies)].tier;
switch (tier) {
case 'BL':
case 'UU':
adjustment = 5;
break;
case 'BL2':
case 'RU':
adjustment = 10;
break;
case 'BL3':
case 'NU':
case 'PU':
case 'NFE':
case 'LC Uber':
case 'LC':
adjustment = 15;
}
if (adjustment) {
for (var j in this.data.Pokedex[i].baseStats) {
this.modData('Pokedex', i).baseStats[j] = this.clampIntRange(this.data.Pokedex[i].baseStats[j] + adjustment, 1, 255);
}
}
}
}
};
|
Correct config props for `async-to-gen`
|
#!/usr/bin/env node
// Packages
const asyncToGen = require('async-to-gen/register')
const updateNotifier = require('update-notifier')
const {red} = require('chalk')
const nodeVersion = require('node-version')
// Ours
const pkg = require('../package')
// Support for keywords "async" and "await"
const pathSep = process.platform === 'win32' ? '\\\\' : '/'
asyncToGen({
includes: new RegExp(`.*serve?${pathSep}(lib|bin).*`),
excludes: null
})
// Throw an error if node version is too low
if (nodeVersion.major < 6) {
console.error(`${red('Error!')} Serve requires at least version 6 of Node. Please upgrade!`)
process.exit(1)
}
// Let user know if there's an update
// This isn't important when deployed to Now
if (!process.env.NOW) {
updateNotifier({pkg}).notify()
}
// Load package core with async/await support
require('../lib')
|
#!/usr/bin/env node
// Packages
const asyncToGen = require('async-to-gen/register')
const updateNotifier = require('update-notifier')
const {red} = require('chalk')
const nodeVersion = require('node-version')
// Ours
const pkg = require('../package')
// Support for keywords "async" and "await"
const pathSep = process.platform === 'win32' ? '\\\\' : '/'
asyncToGen({
include: new RegExp(`.*serve?${pathSep}(lib|bin).*`),
exclude: null
})
// Throw an error if node version is too low
if (nodeVersion.major < 6) {
console.error(`${red('Error!')} Serve requires at least version 6 of Node. Please upgrade!`)
process.exit(1)
}
// Let user know if there's an update
// This isn't important when deployed to Now
if (!process.env.NOW) {
updateNotifier({pkg}).notify()
}
// Load package core with async/await support
require('../lib')
|
Fix for intel routing changes
|
// ==UserScript==
// @id iitc-plugin-chat-tools@hansolo669
// @name IITC plugin: chat tools
// @category Tweaks
// @version 0.1.1
// @namespace https://github.com/hansolo669/iitc-tweaks
// @updateURL https://iitc.reallyawesomedomain.com/chat-tools.meta.js
// @downloadURL https://iitc.reallyawesomedomain.com/chat-tools.user.js
// @description Tools for chat including regex based filters and highligters
// @include https://*.ingress.com/intel*
// @include http://*.ingress.com/intel*
// @match https://*.ingress.com/intel*
// @match http://*.ingress.com/intel*
// @include https://*.ingress.com/mission/*
// @include http://*.ingress.com/mission/*
// @match https://*.ingress.com/mission/*
// @match http://*.ingress.com/mission/*
// @grant none
// ==/UserScript==
|
// ==UserScript==
// @id iitc-plugin-chat-tools@hansolo669
// @name IITC plugin: chat tools
// @category Tweaks
// @version 0.1.0
// @namespace https://github.com/hansolo669/iitc-tweaks
// @updateURL https://iitc.reallyawesomedomain.com/chat-tools.meta.js
// @downloadURL https://iitc.reallyawesomedomain.com/chat-tools.user.js
// @description Tools for chat including regex based filters and highligters
// @include https://www.ingress.com/intel*
// @include http://www.ingress.com/intel*
// @match https://www.ingress.com/intel*
// @match http://www.ingress.com/intel*
// @include https://www.ingress.com/mission/*
// @include http://www.ingress.com/mission/*
// @match https://www.ingress.com/mission/*
// @match http://www.ingress.com/mission/*
// @grant none
// ==/UserScript==
|
Fix clear order in castAttribute
|
'use strict';
var isCallable = require('es5-ext/object/is-callable')
, isAttr = require('../../attr/is-attr')
, element = require('../valid-element');
module.exports = function (name, value) {
element(this);
if (value == null) {
this[name] = null;
this.removeAttribute(name);
} else if (typeof value === 'string') {
this.setAttribute(name, value);
} else if (isCallable(value)) {
this.setAttribute(name, name);
this[name] = value;
} else if (typeof value === 'boolean') {
if (value) {
this.setAttribute(name, name);
this[name] = true;
} else {
this[name] = false;
this.removeAttribute(name);
}
} else if (isCallable(value.toDOMAttr)) {
value.toDOMAttr(this, name);
} else if (isAttr(value)) {
// Deprecated
this.setAttributeNode(value);
} else {
this.setAttribute(name, value);
}
};
|
'use strict';
var isCallable = require('es5-ext/object/is-callable')
, isAttr = require('../../attr/is-attr')
, element = require('../valid-element');
module.exports = function (name, value) {
element(this);
if (value == null) {
this.removeAttribute(name);
this[name] = null;
} else if (typeof value === 'string') {
this.setAttribute(name, value);
} else if (isCallable(value)) {
this.setAttribute(name, name);
this[name] = value;
} else if (typeof value === 'boolean') {
if (value) {
this.setAttribute(name, name);
this[name] = true;
} else {
this.removeAttribute(name);
this[name] = false;
}
} else if (isCallable(value.toDOMAttr)) {
value.toDOMAttr(this, name);
} else if (isAttr(value)) {
// Deprecated
this.setAttributeNode(value);
} else {
this.setAttribute(name, value);
}
};
|
Return data when ``resource_name`` == False
|
import copy
from rest_framework import renderers
from rest_framework_ember.utils import get_resource_name
class JSONRenderer(renderers.JSONRenderer):
"""
Render a JSON response the way Ember Data wants it. Such as:
{
"company": {
"id": 1,
"name": "nGen Works",
"slug": "ngen-works",
"date_created": "2014-03-13 16:33:37"
}
}
"""
def render(self, data, accepted_media_type=None, renderer_context=None):
view = renderer_context.get('view')
resource_name = get_resource_name(view)
if resource_name == False:
return super(JSONRenderer, self).render(
data, accepted_media_type, renderer_context)
try:
data_copy = copy.copy(data)
content = data_copy.pop('results')
data = {resource_name : content, "meta" : data_copy}
except (TypeError, KeyError, AttributeError) as e:
data = {resource_name : data}
return super(JSONRenderer, self).render(
data, accepted_media_type, renderer_context)
|
import copy
from rest_framework import renderers
from rest_framework_ember.utils import get_resource_name
class JSONRenderer(renderers.JSONRenderer):
"""
Render a JSON response the way Ember Data wants it. Such as:
{
"company": {
"id": 1,
"name": "nGen Works",
"slug": "ngen-works",
"date_created": "2014-03-13 16:33:37"
}
}
"""
def render(self, data, accepted_media_type=None, renderer_context=None):
view = renderer_context.get('view')
resource_name = get_resource_name(view)
try:
data_copy = copy.copy(data)
content = data_copy.pop('results')
data = {resource_name : content, "meta" : data_copy}
except (TypeError, KeyError, AttributeError) as e:
data = {resource_name : data}
return super(JSONRenderer, self).render(
data, accepted_media_type, renderer_context)
|
Include webpack-dev-server URL as a valid redirect
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-07-26 20:29
from __future__ import unicode_literals
from django.db import migrations
from oauth2_provider.models import Application
class Migration(migrations.Migration):
def add_default_application(apps, schema_editor):
Application.objects.create(
name="OSM Export Tool UI",
redirect_uris=
"http://localhost/authorized http://localhost:8080/authorized",
client_type=Application.CLIENT_PUBLIC,
authorization_grant_type=Application.GRANT_IMPLICIT,
skip_authorization=True)
dependencies = [
("oauth2_provider", "0005_auto_20170514_1141"),
]
operations = [
migrations.RunPython(add_default_application),
]
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-07-26 20:29
from __future__ import unicode_literals
from django.db import migrations
from oauth2_provider.models import Application
class Migration(migrations.Migration):
def add_default_application(apps, schema_editor):
Application.objects.create(
name="OSM Export Tool UI",
redirect_uris="http://localhost/authorized",
client_type=Application.CLIENT_PUBLIC,
authorization_grant_type=Application.GRANT_IMPLICIT,
skip_authorization=True)
dependencies = [
("oauth2_provider", "0005_auto_20170514_1141"),
]
operations = [
migrations.RunPython(add_default_application),
]
|
Adjust comments on ConditionalTagCheck to match actual functionality.
The check returns false, if any of it's tags are true, not vise versa.
|
<?php
namespace Roots\Sage;
/**
* Utility class which takes an array of conditional tags (or any function which returns a boolean)
* and returns `false` if *any* of them are `true`, and `true` otherwise.
*
* @param array list of conditional tags (http://codex.wordpress.org/Conditional_Tags)
* or custom function which returns a boolean
*
* @return boolean
*/
class ConditionalTagCheck {
private $conditionals;
public $result = true;
public function __construct($conditionals = []) {
$this->conditionals = $conditionals;
$conditionals = array_map([$this, 'checkConditionalTag'], $this->conditionals);
if (in_array(true, $conditionals)) {
$this->result = false;
}
}
private function checkConditionalTag($conditional) {
if (is_array($conditional)) {
list($tag, $args) = $conditional;
} else {
$tag = $conditional;
$args = false;
}
if (function_exists($tag)) {
return $args ? $tag($args) : $tag();
} else {
return false;
}
}
}
|
<?php
namespace Roots\Sage;
/**
* Utility class which takes an array of conditional tags (or any function which returns a boolean)
* and returns `true` if *any* of them are `true`, and `false` otherwise.
*
* @param array list of conditional tags (http://codex.wordpress.org/Conditional_Tags)
* or custom function which returns a boolean
*
* @return boolean
*/
class ConditionalTagCheck {
private $conditionals;
public $result = true;
public function __construct($conditionals = []) {
$this->conditionals = $conditionals;
$conditionals = array_map([$this, 'checkConditionalTag'], $this->conditionals);
if (in_array(true, $conditionals)) {
$this->result = false;
}
}
private function checkConditionalTag($conditional) {
if (is_array($conditional)) {
list($tag, $args) = $conditional;
} else {
$tag = $conditional;
$args = false;
}
if (function_exists($tag)) {
return $args ? $tag($args) : $tag();
} else {
return false;
}
}
}
|
Test coverage at 90% for student and professor
|
package edu.msudenver.cs3250.group6.msubanner.entities;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
/**
* Student class.
*/
public final class Student extends User {
/** The student id. */
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(unique = true)
private String id;
/**
* Default constructor.
*/
public Student() { }
/**
* Constructor.
* @param firstName Student's first name
* @param lastName Student's last name
*/
public Student(final String firstName, final String lastName) {
super(firstName, lastName);
}
@Override
public boolean equals(final Object other) {
return other instanceof Student && super.equals(other);
}
}
|
package edu.msudenver.cs3250.group6.msubanner.entities;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
/**
* Student class.
*/
public final class Student extends User {
/** The student id. */
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(unique = true)
private String id;
/**
* Default constructor.
*/
public Student() { }
/**
* Constructor.
* @param firstName Student's first name
* @param lastName Student's last name
*/
public Student(final String firstName, final String lastName) {
super(firstName, lastName);
}
@Override
public boolean equals(final Object other) {
return other instanceof Student && super.equals(other);
}
}
|
Return array instead of nil when no results are found
This commit addresses an edge case in which the Puppet agent prints an
unclear error message due to the value of the results key being set to
nil.
|
package release
import (
"path/filepath"
)
// Factory is responsible for instantiating slices
// of Releases based upon queries given from the API.
type Factory struct {
modulepath string
fileurl string
}
// NewFactory returns a new instance of Factory
// with the given modulepath.
func NewFactory(modulepath string, fileurl string) *Factory {
return &Factory{
modulepath: modulepath,
fileurl: fileurl,
}
}
// AllForModule returns an instance of Release for each
// available version of a given module. Each instance will
// have had .FromDisk() called on it already prior to returning.
// An error will be returned if an error is encountered during
// the process of loading each release from disk.
func (f *Factory) AllForModule(slug string) (releases []*Release, err error) {
tarballs, err := filepath.Glob(f.modulepath + "/" + slug + "-*.tar.gz")
if err != nil {
return nil, err
}
for _, tarball := range tarballs {
release := New(tarball)
release.FromDisk()
release.File_uri = f.fileurl + "/" + release.Slug() + ".tar.gz"
releases = append(releases, release)
}
return []*Release{}, nil
}
|
package release
import (
"path/filepath"
)
// Factory is responsible for instantiating slices
// of Releases based upon queries given from the API.
type Factory struct {
modulepath string
fileurl string
}
// NewFactory returns a new instance of Factory
// with the given modulepath.
func NewFactory(modulepath string, fileurl string) *Factory {
return &Factory{
modulepath: modulepath,
fileurl: fileurl,
}
}
// AllForModule returns an instance of Release for each
// available version of a given module. Each instance will
// have had .FromDisk() called on it already prior to returning.
// An error will be returned if an error is encountered during
// the process of loading each release from disk.
func (f *Factory) AllForModule(slug string) (releases []*Release, err error) {
tarballs, err := filepath.Glob(f.modulepath + "/" + slug + "-*.tar.gz")
if err != nil {
return nil, err
}
for _, tarball := range tarballs {
release := New(tarball)
release.FromDisk()
release.File_uri = f.fileurl + "/" + release.Slug() + ".tar.gz"
releases = append(releases, release)
}
return
}
|
Fix HardwareDevice docstring to match implementation
|
"""
Module with the HardwareDevice model.
"""
from launch_control.utils.json import PlainOldData
class HardwareDevice(PlainOldData):
"""
Model representing any HardwareDevice
A device is just a "device_type" attribute with a bag of properties
and a human readable description. Individual device types can be
freely added. For simplicity some common types of devices are
provided as class properties DEVICE_xxx.
Instances will come from a variety of factory classes, each capable
of enumerating devices that it understands. The upside of having a
common class like this is that it's easier to store it in the
database _and_ not have to agree on a common set of properties for,
say, all CPUs.
If you want you can create instances manually, like this:
>>> cpu = HardwareDevice(HardwareDevice.DEVICE_CPU,
... u"800MHz OMAP3 Processor")
>>> cpu.attributes[u'machine'] = u'arm'
>>> cpu.attributes[u'mhz'] = '800'
>>> cpu.attributes[u'vendor'] = u'Texas Instruments'
"""
DEVICE_CPU = "device.cpu"
DEVICE_MEM = "device.mem"
DEVICE_USB = "device.usb"
DEVICE_PCI = "device.pci"
DEVICE_BOARD = "device.board"
__slots__ = ('device_type', 'desc', 'attributes')
def __init__(self, device_type, description, attributes=None):
self.device_type = device_type
self.description = description
self.attributes = attributes or {}
|
"""
Module with the HardwareDevice model.
"""
from launch_control.utils.json import PlainOldData
class HardwareDevice(PlainOldData):
"""
Model representing any HardwareDevice
A device is just a "device_type" attribute with a bag of properties
and a human readable description. Individual device types can be
freely added. For simplicity some common types of devices are
provided as class properties DEVICE_xxx.
Instances will come from a variety of factory classes, each capable
of enumerating devices that it understands. The upside of having a
common class like this is that it's easier to store it in the
database _and_ not have to agree on a common set of properties for,
say, all CPUs.
If you want you can create instances manually, like this:
>>> cpu = HardwareDevice(HardwareDevice.DEVICE_CPU)
>>> cpu.desc = "800MHz OMAP3 Processor"
>>> cpu.attributes['machine'] = 'arm'
>>> cpu.attributes['mhz'] = 800
>>> cpu.attributes['vendor'] = 'Texas Instruments'
"""
DEVICE_CPU = "device.cpu"
DEVICE_MEM = "device.mem"
DEVICE_USB = "device.usb"
DEVICE_PCI = "device.pci"
DEVICE_BOARD = "device.board"
__slots__ = ('device_type', 'desc', 'attributes')
def __init__(self, device_type, description, attributes=None):
self.device_type = device_type
self.description = description
self.attributes = attributes or {}
|
Remove legacy and stop using deprecated things
|
module.exports = {
"sourceMaps": true,
"presets": [
["@babel/preset-env", {
"targets": [
"last 2 Chrome versions", "last 2 Firefox versions", "last 2 Safari versions"
],
}],
"@babel/preset-typescript",
"@babel/preset-flow",
"@babel/preset-react"
],
"plugins": [
["@babel/plugin-proposal-decorators", {decoratorsBeforeExport: true}],
"@babel/plugin-proposal-export-default-from",
"@babel/plugin-proposal-numeric-separator",
"@babel/plugin-proposal-class-properties",
"@babel/plugin-proposal-object-rest-spread",
"@babel/plugin-transform-flow-comments",
"@babel/plugin-syntax-dynamic-import",
"@babel/plugin-transform-runtime"
]
};
|
module.exports = {
"sourceMaps": true,
"presets": [
["@babel/preset-env", {
"targets": {
"browsers": [
"last 2 Chrome versions", "last 2 Firefox versions", "last 2 Safari versions"
]
},
}],
"@babel/preset-typescript",
"@babel/preset-flow",
"@babel/preset-react"
],
"plugins": [
["@babel/plugin-proposal-decorators", {"legacy": false, decoratorsBeforeExport: true}],
"@babel/plugin-proposal-export-default-from",
"@babel/plugin-proposal-numeric-separator",
"@babel/plugin-proposal-class-properties",
"@babel/plugin-proposal-object-rest-spread",
"@babel/plugin-transform-flow-comments",
"@babel/plugin-syntax-dynamic-import",
"@babel/plugin-transform-runtime"
]
};
|
Bump version number for release.
|
#!/usr/bin/env python
import os
from setuptools import setup
def readreq(filename):
result = []
with open(filename) as f:
for req in f:
req = req.partition('#')[0].strip()
if not req:
continue
result.append(req)
return result
def readfile(filename):
with open(filename) as f:
return f.read()
setup(
name='cli_tools',
version='0.2.2',
author='Kevin L. Mitchell',
author_email='klmitch@mit.edu',
description="Command Line Interface Tools",
py_modules=['cli_tools'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU General Public License v3 or '
'later (GPLv3+)',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: User Interfaces',
],
url='https://github.com/klmitch/cli_utils',
long_description=readfile('README.rst'),
install_requires=readreq('.requires'),
tests_require=readreq('.test-requires'),
)
|
#!/usr/bin/env python
import os
from setuptools import setup
def readreq(filename):
result = []
with open(filename) as f:
for req in f:
req = req.partition('#')[0].strip()
if not req:
continue
result.append(req)
return result
def readfile(filename):
with open(filename) as f:
return f.read()
setup(
name='cli_tools',
version='0.2.1',
author='Kevin L. Mitchell',
author_email='klmitch@mit.edu',
description="Command Line Interface Tools",
py_modules=['cli_tools'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU General Public License v3 or '
'later (GPLv3+)',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: User Interfaces',
],
url='https://github.com/klmitch/cli_utils',
long_description=readfile('README.rst'),
install_requires=readreq('.requires'),
tests_require=readreq('.test-requires'),
)
|
Add pillar data to default renderer
|
'''
The default rendering engine, process yaml with the jinja2 templating engine
This renderer will take a yaml file with the jinja2 template and render it to a
high data format for salt states.
'''
# Import Python Modules
import os
# Import thirt party modules
import yaml
try:
yaml.Loader = yaml.CLoader
yaml.Dumper = yaml.CDumper
except:
pass
# Import Salt libs
from salt.utils.jinja import get_template
def render(template_file, env='', sls=''):
'''
Render the data passing the functions and grains into the rendering system
'''
if not os.path.isfile(template_file):
return {}
passthrough = {}
passthrough['salt'] = __salt__
passthrough['grains'] = __grains__
passthrough['pillar'] = __pillar__
passthrough['env'] = env
passthrough['sls'] = sls
template = get_template(template_file, __opts__, env)
yaml_data = template.render(**passthrough)
return yaml.safe_load(yaml_data)
|
'''
The default rendering engine, process yaml with the jinja2 templating engine
This renderer will take a yaml file with the jinja2 template and render it to a
high data format for salt states.
'''
# Import Python Modules
import os
# Import thirt party modules
import yaml
try:
yaml.Loader = yaml.CLoader
yaml.Dumper = yaml.CDumper
except:
pass
# Import Salt libs
from salt.utils.jinja import get_template
def render(template_file, env='', sls=''):
'''
Render the data passing the functions and grains into the rendering system
'''
if not os.path.isfile(template_file):
return {}
passthrough = {}
passthrough['salt'] = __salt__
passthrough['grains'] = __grains__
passthrough['env'] = env
passthrough['sls'] = sls
template = get_template(template_file, __opts__, env)
yaml_data = template.render(**passthrough)
return yaml.safe_load(yaml_data)
|
Add comment re: send IP of controller for test.
|
package org.bitbucket.openkilda.atdd;
import cucumber.api.PendingException;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class TopologyDiscoveryBasicTest {
public TopologyDiscoveryBasicTest() {
}
@Given("^a new controller$")
public void a_new_controller() throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
@Given("^a random linear topology of (\\d+)$")
public void a_random_linear_topology_of(int arg1) throws Throwable {
// Write code here that turns the phrase above into concrete actions
// TODO: Will need to send the IP address of the controller.
throw new PendingException();
}
@When("^the controller learns the topology$")
public void the_controller_learns_the_topology() throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
@Then("^the controller should converge within (\\d+) milliseconds$")
public void the_controller_should_converge_within_milliseconds(int arg1) throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
@Given("^a random full-mesh topology of (\\d+)$")
public void a_random_full_mesh_topology_of(int arg1) throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
}
|
package org.bitbucket.openkilda.atdd;
import cucumber.api.PendingException;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class TopologyDiscoveryBasicTest {
public TopologyDiscoveryBasicTest() {
}
@Given("^a new controller$")
public void a_new_controller() throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
@Given("^a random linear topology of (\\d+)$")
public void a_random_linear_topology_of(int arg1) throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
@When("^the controller learns the topology$")
public void the_controller_learns_the_topology() throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
@Then("^the controller should converge within (\\d+) milliseconds$")
public void the_controller_should_converge_within_milliseconds(int arg1) throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
@Given("^a random full-mesh topology of (\\d+)$")
public void a_random_full_mesh_topology_of(int arg1) throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
}
|
Allow script to take multiple paths, and adjust to standard __main__ idiom
for cmdline scripts.
* tools/dev/wc-format.py:
(usage): remove. all paths are allowed.
(print_format): move guts of format fetching and printing into this
function. print 'not under version control' for such a path, rather
than bailing with USAGE. expand sqlite stuff to use normal pydb idioms
(eg. execute is not supposed to return anything)
(__main__): invoke print_format for each path provided
git-svn-id: f8a4e5e023278da1e04e203c7fe051e3c4285d88@1001109 13f79535-47bb-0310-9956-ffa450edef68
|
#!/usr/bin/env python
import os
import sqlite3
import sys
def print_format(wc_path):
entries = os.path.join(wc_path, '.svn', 'entries')
wc_db = os.path.join(wc_path, '.svn', 'wc.db')
if os.path.exists(entries):
formatno = int(open(entries).readline())
elif os.path.exists(wc_db):
conn = sqlite3.connect(wc_db)
curs = conn.cursor()
curs.execute('pragma user_version;')
formatno = curs.fetchone()[0]
else:
formatno = 'not under version control'
# see subversion/libsvn_wc/wc.h for format values and information
# 1.0.x -> 1.3.x: format 4
# 1.4.x: format 8
# 1.5.x: format 9
# 1.6.x: format 10
# 1.7.x: format XXX
print '%s: %s' % (wc_path, formatno)
if __name__ == '__main__':
paths = sys.argv[1:]
if not paths:
paths = ['.']
for wc_path in paths:
print_format(wc_path)
|
#!/usr/bin/env python
import os
import sqlite3
import sys
# helper
def usage():
sys.stderr.write("USAGE: %s [PATH]\n" + \
"\n" + \
"Prints to stdout the format of the working copy at PATH.\n")
# parse argv
wc = (sys.argv[1:] + ['.'])[0]
# main()
entries = os.path.join(wc, '.svn', 'entries')
wc_db = os.path.join(wc, '.svn', 'wc.db')
if os.path.exists(entries):
formatno = int(open(entries).readline())
elif os.path.exists(wc_db):
formatno = sqlite3.connect(wc_db).execute('pragma user_version;').fetchone()[0]
else:
usage()
sys.exit(1)
# 1.0.x -> 1.3.x: format 4
# 1.4.x: format 8
# 1.5.x: format 9
# 1.6.x: format 10
# 1.7.x: format XXX
print("%s: %d" % (wc, formatno))
|
Work with http handler func
|
package servo
import "net/http"
// The Server is responsible for running the server process.
// It can be injected via the goldi type "kernel.server"
type Server interface {
// Run starts the server and blocks until it has finished
Run() error
}
// DefaultServer is the standard implementation of the Server interface.
// It accepts a listen address and an HTTP handler and uses the http package of
// the standard library.
type HTTPServer struct {
ListenAddress string
Handler http.HandlerFunc
Log Logger
}
// NewHTTPServer creates a new HTTPServer
func NewHTTPServer(listenAddress string, handler http.HandlerFunc, log Logger) *HTTPServer {
return &HTTPServer{listenAddress, handler, log}
}
// Run will make this server listen on the given ListenAddress and use the handler to
// handle all incoming HTTP requests. The method blocks.
func (s *HTTPServer) Run() error {
s.Log.Info("Server started", "address", s.ListenAddress)
http.HandleFunc("/", s.Handler)
return http.ListenAndServe(s.ListenAddress, s.Handler)
}
|
package servo
import "net/http"
// The Server is responsible for running the server process.
// It can be injected via the goldi type "kernel.server"
type Server interface {
// Run starts the server and blocks until it has finished
Run() error
}
// DefaultServer is the standard implementation of the Server interface.
// It accepts a listen address and an HTTP handler and uses the http package of
// the standard library.
type HTTPServer struct {
ListenAddress string
Handler http.Handler
Log Logger
}
// NewHTTPServer creates a new HTTPServer
func NewHTTPServer(listenAddress string, handler http.Handler, log Logger) *HTTPServer {
return &HTTPServer{listenAddress, handler, log}
}
// Run will make this server listen on the given ListenAddress and use the handler to
// handle all incoming HTTP requests. The method blocks.
func (s *HTTPServer) Run() error {
s.Log.Info("Server started", "address", s.ListenAddress)
return http.ListenAndServe(s.ListenAddress, s.Handler)
}
|
Update spec to use real class, DateTime comes back as false size.
|
<?php
namespace spec\Elfiggo\Brobdingnagian\Detector;
use Elfiggo\Brobdingnagian\Detector\ClassSize;
use PhpSpec\Event\SpecificationEvent;
use PhpSpec\Loader\Node\SpecificationNode;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class DetectorSpec extends ObjectBehavior
{
function it_is_initializable()
{
$this->shouldHaveType('Elfiggo\Brobdingnagian\Detector\Detector');
}
function it_should_analyse_the_class_size(SpecificationEvent $specificationEvent, SpecificationNode $specificationNode)
{
$specificationEvent->getSpecification()->willReturn($specificationNode);
$specificationNode->getClassReflection()->willReturn(new \ReflectionClass(ClassSize::class));
$this->shouldNotThrow('Elfiggo\Brobdingnagian\Exception\ClassSizeTooLarge');
$this->analyse($specificationEvent);
}
}
|
<?php
namespace spec\Elfiggo\Brobdingnagian\Detector;
use PhpSpec\Event\SpecificationEvent;
use PhpSpec\Loader\Node\SpecificationNode;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class DetectorSpec extends ObjectBehavior
{
function it_is_initializable()
{
$this->shouldHaveType('Elfiggo\Brobdingnagian\Detector\Detector');
}
function it_should_analyse_the_class_size(SpecificationEvent $specificationEvent, SpecificationNode $specificationNode)
{
$specificationEvent->getSpecification()->willReturn($specificationNode);
$specificationNode->getClassReflection()->willReturn(new \ReflectionClass(\DateTime::class));
$this->shouldNotThrow('Elfiggo\Brobdingnagian\Exception\ClassSizeTooLarge');
$this->analyse($specificationEvent);
}
}
|
Add sign up link that shows if no user is signed in
|
{
angular
.module('meganote.users')
.directive('userLinks', [
'CurrentUser',
(CurrentUser) => {
class UserLinksController {
user() {
return CurrentUser.get();
}
signedIn() {
return CurrentUser.signedIn();
}
}
return {
scope: {},
controller: UserLinksController,
controllerAs: 'vm',
bindToController: true,
template: `
<div class="user-links">
<span ng-show="vm.signedIn()">
Signed in as {{ vm.user().name }}
</span>
<span ng-hide="vm.signedIn()">
<a ui-sref="sign-up">Sign up for Meganote today!</a>
</span>
</div>`,
};
}]);
}
|
{
angular
.module('meganote.users')
.directive('userLinks', [
'CurrentUser',
(CurrentUser) => {
class UserLinksController {
user() {
return CurrentUser.get();
}
signedIn() {
return CurrentUser.signedIn();
}
}
return {
scope: {},
controller: UserLinksController,
controllerAs: 'vm',
bindToController: true,
template: `
<div class="user-links" ng-show="vm.signedIn()">
Signed in as {{ vm.user().name }}
</div>`,
};
}]);
}
|
Align animal population counts rounding
- round animal population counts down for the frontend "analyze" display to match the MapShed implementation
|
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from django.contrib.gis.geos import GEOSGeometry
from django.conf import settings
from apps.modeling.mapshed.calcs import animal_energy_units
ANIMAL_KEYS = settings.GWLFE_CONFIG['AnimalKeys']
ANIMAL_NAMES = settings.GWLFE_DEFAULTS['AnimalName']
ANIMAL_DISPLAY_NAMES = dict(zip(ANIMAL_KEYS, ANIMAL_NAMES))
def animal_population(geojson):
"""
Given a GeoJSON shape, call MapShed's `animal_energy_units` method
to calculate the area-weighted county animal population. Returns a
dictionary to append to the outgoing JSON for analysis results.
"""
geom = GEOSGeometry(geojson, srid=4326)
aeu_for_geom = animal_energy_units(geom)[2]
aeu_return_values = []
for animal, aeu_value in aeu_for_geom.iteritems():
aeu_return_values.append({
'type': ANIMAL_DISPLAY_NAMES[animal],
'aeu': int(aeu_value),
})
return {
'displayName': 'Animals',
'name': 'animals',
'categories': aeu_return_values
}
|
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from django.contrib.gis.geos import GEOSGeometry
from django.conf import settings
from apps.modeling.mapshed.calcs import animal_energy_units
ANIMAL_KEYS = settings.GWLFE_CONFIG['AnimalKeys']
ANIMAL_NAMES = settings.GWLFE_DEFAULTS['AnimalName']
ANIMAL_DISPLAY_NAMES = dict(zip(ANIMAL_KEYS, ANIMAL_NAMES))
def animal_population(geojson):
"""
Given a GeoJSON shape, call MapShed's `animal_energy_units` method
to calculate the area-weighted county animal population. Returns a
dictionary to append to the outgoing JSON for analysis results.
"""
geom = GEOSGeometry(geojson, srid=4326)
aeu_for_geom = animal_energy_units(geom)[2]
aeu_return_values = []
for animal, aeu_value in aeu_for_geom.iteritems():
aeu_return_values.append({
'type': ANIMAL_DISPLAY_NAMES[animal],
'aeu': int(round(aeu_value)),
})
return {
'displayName': 'Animals',
'name': 'animals',
'categories': aeu_return_values
}
|
Add pytest as a dependency
|
import distutils.core
# Uploading to PyPI
# =================
# $ python setup.py register -r pypi
# $ python setup.py sdist upload -r pypi
version = '0.0'
distutils.core.setup(
name='kxg',
version=version,
author='Kale Kundert and Alex Mitchell',
url='https://github.com/kxgames/GameEngine',
download_url='https://github.com/kxgames/GameEngine/tarball/'+version,
license='LICENSE.txt',
description="A multiplayer game engine.",
long_description=open('README.rst').read(),
keywords=['game', 'network', 'gui', 'pyglet'],
packages=['kxg'],
requires=[
'pyglet',
'nonstdlib',
'linersock',
'vecrec',
'glooey',
'pytest',
],
)
|
import distutils.core
# Uploading to PyPI
# =================
# $ python setup.py register -r pypi
# $ python setup.py sdist upload -r pypi
version = '0.0'
distutils.core.setup(
name='kxg',
version=version,
author='Kale Kundert and Alex Mitchell',
url='https://github.com/kxgames/GameEngine',
download_url='https://github.com/kxgames/GameEngine/tarball/'+version,
license='LICENSE.txt',
description="A multiplayer game engine.",
long_description=open('README.rst').read(),
keywords=['game', 'network', 'gui', 'pyglet'],
packages=['kxg'],
requires=[
'pyglet',
'nonstdlib',
'linersock',
'vecrec',
'glooey',
],
)
|
Include custom config IF present
Reverted the logic:
- `config.php` could not exists
- `config.dist.php` should exists by design instead
|
<?php
final class app
{
protected static $_instance = null;
protected $_data = array();
protected function __construct()
{
$this->_data['config'] = include_once(file_exists('../config.php') ? '../config.php' : '../config.dist.php');
$this->_data['drivers'] = 'drivers/';
}
public static function instance()
{
if (!self::$_instance) {
self::$_instance = new self;
}
return self::$_instance;
}
public function __get($key)
{
return isset($this->_data[$key]) ? $this->_data[$key] : null;
}
public function __set($key, $value)
{
$this->_data[$key] = $value;
}
}
|
<?php
final class app
{
protected static $_instance = null;
protected $_data = array();
protected function __construct()
{
$this->_data['config'] = include_once(file_exists('../config.dist.php') ? '../config.dist.php' : '../config.php');
$this->_data['drivers'] = 'drivers/';
}
public static function instance()
{
if (!self::$_instance) {
self::$_instance = new self;
}
return self::$_instance;
}
public function __get($key)
{
return isset($this->_data[$key]) ? $this->_data[$key] : null;
}
public function __set($key, $value)
{
$this->_data[$key] = $value;
}
}
|
ast: Remove optional semicolons from test.
|
package ast_test
import (
"strings"
"testing"
"github.com/DeedleFake/wdte/ast"
)
func printTree(t *testing.T, cur ast.Node, depth int) {
indent := strings.Repeat(" ", depth)
switch cur := cur.(type) {
case *ast.Term:
t.Logf("%v%v", indent, cur)
case *ast.NTerm:
t.Logf("%v(%v", indent, cur)
for _, c := range cur.Children() {
printTree(t, c, depth+1)
}
t.Logf("%v)", indent)
case *ast.Epsilon:
t.Logf("%vε", indent)
default:
t.Fatalf("Unexpected node: %#v", cur)
}
}
func TestParse(t *testing.T) {
//const test = `"test" => t; + x y => nil;`
const test = `
'test' => test;
fib n => switch n {
0 => 0;
default => + (fib (- n 1)) (fib (- n 2));
};
main => print (fib 5);
`
root, err := ast.Parse(strings.NewReader(test))
if err != nil {
t.Fatal(err)
}
printTree(t, root, 0)
}
|
package ast_test
import (
"strings"
"testing"
"github.com/DeedleFake/wdte/ast"
)
func printTree(t *testing.T, cur ast.Node, depth int) {
indent := strings.Repeat(" ", depth)
switch cur := cur.(type) {
case *ast.Term:
t.Logf("%v%v", indent, cur)
case *ast.NTerm:
t.Logf("%v(%v", indent, cur)
for _, c := range cur.Children() {
printTree(t, c, depth+1)
}
t.Logf("%v)", indent)
case *ast.Epsilon:
t.Logf("%vε", indent)
default:
t.Fatalf("Unexpected node: %#v", cur)
}
}
func TestParse(t *testing.T) {
//const test = `"test" => t; + x y => nil;`
const test = `
'test' => test;
fib n => switch n {
0 => 0;
default => + (fib (- n 1;);) (fib (- n 2;););
};
main => print (fib 5;);
`
root, err := ast.Parse(strings.NewReader(test))
if err != nil {
t.Fatal(err)
}
printTree(t, root, 0)
}
|
Fix 'open reference' test case
|
#!/usr/bin/env python
import unittest
import yv_suggest.open as yvs
import inspect
class WebbrowserMock(object):
'''mock the builtin webbrowser module'''
def open(self, url):
'''mock the webbrowser.open() function'''
self.url = url
class OpenTestCase(unittest.TestCase):
'''test the handling of Bible reference URLs'''
def test_url(self):
'''should build correct URL to Bible reference'''
url = yvs.get_ref_url('esv/jhn.3.16')
self.assertEqual(url, 'https://www.bible.com/bible/esv/jhn.3.16')
def test_query_param(self):
'''should use received query parameter as default ref ID'''
spec = inspect.getargspec(yvs.main)
default_query_str = spec.defaults[0]
self.assertEqual(default_query_str, '{query}')
def test_url_open(self):
'''should attempt to open URL using webbrowser module'''
mock = WebbrowserMock()
yvs.webbrowser = mock
yvs.main('nlt/jhn.3.17')
self.assertEqual(mock.url, 'https://www.bible.com/bible/nlt/jhn.3.17')
|
#!/usr/bin/env python
import unittest
import yv_suggest.open as yvs
import inspect
class WebbrowserMock(object):
'''mock the builtin webbrowser module'''
def open(self, url):
'''mock the webbrowser.open() function'''
self.url = url
class OpenTestCase(unittest.TestCase):
'''test the handling of Bible reference URLs'''
def test_url(self):
'''should build correct URL to Bible reference'''
url = yvs.get_ref_url('esv/jhn.3.16')
self.assertEqual(url, 'https://www.bible.com/bible/esv/jhn.3.16')
def test_query_param(self):
'''should use received query parameter as default ref ID'''
spec = inspect.getargspec(yvs.main)
default_query_str = spec.defaults[0]
self.assertEqual(default_query_str, '{query}')
def test_url_open(self):
'''should attempt to open URL using webbrowser module'''
mock = self.WebbrowserMock()
yvs.webbrowser = mock
yvs.main('nlt/jhn.3.17')
self.assertEqual(mock.url, 'https://www.bible.com/bible/nlt/jhn.3.17')
|
Implement privileged functions for executing OAuth methods with ze secrets
|
'use strict';
var OAuth = require('OAuth');
var querystring = require('querystring');
// Wrapper for the OAuth 1.0 consumer used to make authenticated called to the Yelp API.
var Client = function(options) {
if(!options) { options = {}; }
this.apiHost = 'http://api.yelp.com';
this.apiPath = { search: '/v2/search/?', business:'/v2/business/' };
var token = options.token || process.env.TOKEN;
var tokenSecret = options.tokenSecret || process.env.TOKEN_SECRET;
var oauth = new OAuth.OAuth
(
options.requestUrl || null,
options.accessUrl || null,
options.consumerKey || process.env.CONSUMER_KEY,
options.consumerSecret || process.env.CONSUMER_SECRET,
options.version || '1.0',
options.authorizeCallback || null,
options.signatureMethod || 'HMAC-SHA1',
options.nonceSize || null,
options.customHeaders || null
);
this.get = function get(url, callback) {
return oauth.get(
url,
token,
tokenSecret,
callback
);
};
this.signRequest = function signRequest(url, callback) {
return oauth.signUrl(url, token, tokenSecret);
};
};
module.exports = Client;
|
'use strict';
var OAuth = require('OAuth');
var querystring = require('querystring');
// Wrapper for the OAuth 1.0 consumer used to make authenticated called to the Yelp API.
var Client = function(options) {
if(!options) { options = {}; }
this.apiHost = 'http://api.yelp.com';
this.apiPath = { search: '/v2/search/?', business:'/v2/business/' };
var token = options.token || process.env.TOKEN;
var tokenSecret = options.tokenSecret || process.env.TOKEN_SECRET;
var oauth = new OAuth.OAuth
(
options.requestUrl || null,
options.accessUrl || null,
options.consumerKey || process.env.CONSUMER_KEY,
options.consumerSecret || process.env.CONSUMER_SECRET,
options.version || '1.0',
options.authorizeCallback || null,
options.signatureMethod || 'HMAC-SHA1',
options.nonceSize || null,
options.customHeaders || null
);
};
|
8: Create documentation of DataSource Settings
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/8
|
######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
dbs = AdminConfig.list('DataSource',AdminConfig.getid('/Cell:cnxwas1Cell01/')).splitlines()
for db in dbs:
print db
# dbs = dbs.split('(')[0]
# print dbs
# dbs = ['FNOSDS', 'FNGCDDS', 'IBM_FORMS_DATA_SOURCE', 'activities', 'blogs', 'communities', 'dogear', 'files', 'forum', 'homepage', 'metrics', 'mobile', 'news', 'oauth provider', 'profiles', 'search', 'wikis'] # List of all databases to check
#
# for db in dbs:
# t1 = ibmcnx.functions.getDSId( db )
# AdminConfig.show( t1 )
# print '\n\n'
# AdminConfig.showall( t1 )
# AdminConfig.showAttribute(t1,'statementCacheSize' )
# AdminConfig.showAttribute(t1,'[statementCacheSize]' )
|
######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
dbs = AdminConfig.list('DataSource', AdminConfig.getid('/Cell:cnxwas1Cell01/'))
for db in dbs:
print db
# dbs = dbs.split('(')[0]
# print dbs
# dbs = ['FNOSDS', 'FNGCDDS', 'IBM_FORMS_DATA_SOURCE', 'activities', 'blogs', 'communities', 'dogear', 'files', 'forum', 'homepage', 'metrics', 'mobile', 'news', 'oauth provider', 'profiles', 'search', 'wikis'] # List of all databases to check
#
# for db in dbs:
# t1 = ibmcnx.functions.getDSId( db )
# AdminConfig.show( t1 )
# print '\n\n'
# AdminConfig.showall( t1 )
# AdminConfig.showAttribute(t1,'statementCacheSize' )
# AdminConfig.showAttribute(t1,'[statementCacheSize]' )
|
Create a source map file
|
'use strict';
let gulp = require('gulp'),
rollup = require('rollup').rollup;
let cache;
module.exports = () => {
gulp.task('copy-dependencies', () => {
return gulp
.src([
'./node_modules/three/build/three.js'
])
.pipe(gulp.dest('./dist/'))
});
gulp.task('build', ['copy-dependencies'], (callback) => {
return rollup({
entry: 'src/js/main.js',
cache: cache,
sourceMap: true,
external: ['three']
}).then(function(bundle) {
return bundle.write({
dest: 'dist/main.js',
sourceMap: true,
format: 'iife',
globals: {
three: 'THREE'
}
});
});
});
};
|
'use strict';
let gulp = require('gulp'),
rename = require('gulp-rename'),
rollup = require('rollup').rollup;
module.exports = () => {
gulp.task('copy-dependencies', () => {
return gulp
.src([
'./node_modules/three/build/three.js'
])
.pipe(gulp.dest('./dist/'))
});
gulp.task('build', ['copy-dependencies'], (callback) => {
return rollup({
entry: 'src/js/main.js',
sourceMap: true,
external: ['three']
}).then(function(bundle) {
return bundle.write({
dest: 'dist/main.js',
format: 'iife',
globals: {
three: 'THREE'
}
});
});
});
};
|
Disable DevModePlugin until py3 fix is fixed upstream
|
import logging
import json
from django.conf import settings
import hypernova
logger = logging.getLogger(__name__)
class HypernovaService():
def load_or_empty(self, component, headers={}, ssr_context=None):
# from hypernova.plugins.dev_mode import DevModePlugin
renderer = hypernova.Renderer(
settings.REACT_RENDER_HOST,
# [DevModePlugin(logger)] if settings.DEBUG else [],
[],
timeout=get_request_timeout(),
headers=headers,
)
inner_html = ""
try:
inner_html = renderer.render({component['name']: component['json']})
except Exception as e:
msg = "SSR request to '{}' failed: {}".format(
settings.REACT_RENDER_HOST,
e.__class__.__name__
)
logger.exception(msg)
return inner_html
def get_request_timeout():
if not hasattr(settings, 'REACT_RENDER_TIMEOUT'):
return 20
return settings.REACT_RENDER_TIMEOUT
|
import logging
import json
from django.conf import settings
import hypernova
from hypernova.plugins.dev_mode import DevModePlugin
logger = logging.getLogger(__name__)
class HypernovaService():
def load_or_empty(self, component, headers={}, ssr_context=None):
renderer = hypernova.Renderer(
settings.REACT_RENDER_HOST,
[DevModePlugin(logger)] if settings.DEBUG else [],
timeout=get_request_timeout(),
headers=headers,
)
inner_html = ""
try:
inner_html = renderer.render({component['name']: component['json']})
except Exception as e:
msg = "SSR request to '{}' failed: {}".format(
settings.REACT_RENDER_HOST,
e.__class__.__name__
)
logger.exception(msg)
return inner_html
def get_request_timeout():
if not hasattr(settings, 'REACT_RENDER_TIMEOUT'):
return 20
return settings.REACT_RENDER_TIMEOUT
|
Change port for client development
|
'use strict'
// see http://vuejs-templates.github.io/webpack for documentation.
const path = require('path')
module.exports = {
build: {
env: require('./prod.env'),
index: path.resolve(__dirname, '../dist/index.html'),
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
productionSourceMap: true,
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
},
dev: {
env: require('./dev.env'),
port: 8081,
autoOpenBrowser: true,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {},
// CSS Sourcemaps off by default because relative paths are "buggy"
// with this option, according to the CSS-Loader README
// (https://github.com/webpack/css-loader#sourcemaps)
// In our experience, they generally work as expected,
// just be aware of this issue when enabling this option.
cssSourceMap: false
}
}
|
'use strict'
// see http://vuejs-templates.github.io/webpack for documentation.
const path = require('path')
module.exports = {
build: {
env: require('./prod.env'),
index: path.resolve(__dirname, '../dist/index.html'),
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
productionSourceMap: true,
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
},
dev: {
env: require('./dev.env'),
port: 8080,
autoOpenBrowser: true,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {},
// CSS Sourcemaps off by default because relative paths are "buggy"
// with this option, according to the CSS-Loader README
// (https://github.com/webpack/css-loader#sourcemaps)
// In our experience, they generally work as expected,
// just be aware of this issue when enabling this option.
cssSourceMap: false
}
}
|
Disable reloader. It messes with plugins.
|
#!/usr/bin/python
from optparse import OptionParser
from sys import stderr
import pytz
from werkzeug import script
from werkzeug.script import make_runserver
from firmant.wsgi import Application
from firmant.utils import mod_to_dict
from firmant.utils import get_module
parser = OptionParser()
parser.add_option('-s', '--settings',
dest='settings', type='string', default='settings',
help='the settings module to use for the test server.')
parser.add_option('-p', '--port',
dest='port', type='int', default='8080',
help='the port on which to run the test server.')
parser.add_option('-H', '--host',
dest='host', type='string', default='',
help='the host to which the server should bind.')
(options, args) = parser.parse_args()
try:
settings = mod_to_dict(get_module(options.settings))
except ImportError:
stderr.write('Please specify a settings module that can be imported.\n')
exit(1)
def make_app():
return Application(settings)
action_runserver = script.make_runserver(make_app, use_reloader=False)
if __name__ == '__main__':
print 'Starting local WSGI Server'
print 'Please do not use this server for production'
script.run()
|
#!/usr/bin/python
from optparse import OptionParser
from sys import stderr
import pytz
from werkzeug import script
from werkzeug.script import make_runserver
from firmant.wsgi import Application
from firmant.utils import mod_to_dict
from firmant.utils import get_module
parser = OptionParser()
parser.add_option('-s', '--settings',
dest='settings', type='string', default='settings',
help='the settings module to use for the test server.')
parser.add_option('-p', '--port',
dest='port', type='int', default='8080',
help='the port on which to run the test server.')
parser.add_option('-H', '--host',
dest='host', type='string', default='',
help='the host to which the server should bind.')
(options, args) = parser.parse_args()
try:
settings = mod_to_dict(get_module(options.settings))
except ImportError:
stderr.write('Please specify a settings module that can be imported.\n')
exit(1)
def make_app():
return Application(settings)
action_runserver = script.make_runserver(make_app, use_reloader=True)
if __name__ == '__main__':
print 'Starting local WSGI Server'
print 'Please do not use this server for production'
script.run()
|
Undo custom `unhandledrejection` and just use Raven's suggestions (too much spam of events that provide no information to resolve them)
|
import React from 'react';
import { render } from 'react-dom';
import { Router, Route, browserHistory } from 'react-router';
import './static/bootstrap/css/bootstrap.css';
import App from './Main/App';
import ErrorBoundary from './Main/ErrorBoundary';
import { unregister } from './registerServiceWorker';
// Source: https://docs.sentry.io/clients/javascript/usage/#promises
window.onunhandledrejection = function(evt) {
Raven && Raven.captureException(evt.reason); // eslint-disable-line no-undef
};
render(
<ErrorBoundary>
<Router history={browserHistory}>
<Route path="/" component={App}>
<Route path="report/:reportCode" />
<Route path="report/:reportCode/:fightId" />
<Route path="report/:reportCode/:fightId/:playerName" />
<Route path="report/:reportCode/:fightId/:playerName/:resultTab" />
</Route>
</Router>
</ErrorBoundary>,
document.getElementById('app-mount')
);
unregister();
|
import React from 'react';
import { render } from 'react-dom';
import { Router, Route, browserHistory } from 'react-router';
import './static/bootstrap/css/bootstrap.css';
import App from './Main/App';
import ErrorBoundary from './Main/ErrorBoundary';
import { unregister } from './registerServiceWorker';
function isError(x) {
return x instanceof Error;
}
function toMessage(x) {
return isError(x) ? x.message : x;
}
function toStack(x) {
return isError(x) ? x.stack : undefined;
}
window.addEventListener('unhandledrejection', event => {
const message = toMessage(event);
console.error(`Unhandled rejection: ${message}`);
Raven && Raven.captureException(event.reason || new Error('Unhandled promise rejection'), { // eslint-disable-line no-undef
extra: {
reason: message,
originalEvent: event,
stack: toStack(event),
},
});
});
render(
<ErrorBoundary>
<Router history={browserHistory}>
<Route path="/" component={App}>
<Route path="report/:reportCode" />
<Route path="report/:reportCode/:fightId" />
<Route path="report/:reportCode/:fightId/:playerName" />
<Route path="report/:reportCode/:fightId/:playerName/:resultTab" />
</Route>
</Router>
</ErrorBoundary>,
document.getElementById('app-mount')
);
unregister();
|
Allow relative paths when extending / including
See #9
|
<?php namespace Bkwld\LaravelPug;
// Dependencies
use Illuminate\View\Compilers\BladeCompiler;
use Illuminate\View\Compilers\CompilerInterface;
use Illuminate\Filesystem\Filesystem;
use Pug\Pug;
class PugBladeCompiler extends BladeCompiler implements CompilerInterface {
/**
* The MtHaml instance.
*
* @var Pug
*/
protected $pug;
/**
* Create a new compiler instance.
*
* @param Pug $pug
* @param \Illuminate\Filesystem\Filesystem $files
* @param string $cachePath
* @return void
*/
public function __construct(Pug $pug, Filesystem $files, $cachePath)
{
$this->pug = $pug;
parent::__construct($files, $cachePath);
}
/**
* Compile the view at the given path.
*
* @param string $path
* @return void
*/
public function compile($path) {
$this->footer = array();
if (is_null($this->cachePath)) return;
// First compile the Pug syntax
$contents = $this->pug->compile($this->files->get($path), $path);
// Then the Blade syntax
$contents = $this->compileString($contents);
// Save
$this->files->put($this->getCompiledPath($path), $contents);
}
}
|
<?php namespace Bkwld\LaravelPug;
// Dependencies
use Illuminate\View\Compilers\BladeCompiler;
use Illuminate\View\Compilers\CompilerInterface;
use Illuminate\Filesystem\Filesystem;
use Pug\Pug;
class PugBladeCompiler extends BladeCompiler implements CompilerInterface {
/**
* The MtHaml instance.
*
* @var Pug
*/
protected $pug;
/**
* Create a new compiler instance.
*
* @param Pug $pug
* @param \Illuminate\Filesystem\Filesystem $files
* @param string $cachePath
* @return void
*/
public function __construct(Pug $pug, Filesystem $files, $cachePath)
{
$this->pug = $pug;
parent::__construct($files, $cachePath);
}
/**
* Compile the view at the given path.
*
* @param string $path
* @return void
*/
public function compile($path) {
$this->footer = array();
if (is_null($this->cachePath)) return;
// First compile the Pug syntax
$contents = $this->pug->compile($this->files->get($path));
// Then the Blade syntax
$contents = $this->compileString($contents);
// Save
$this->files->put($this->getCompiledPath($path), $contents);
}
}
|
chore: Use reporter that's better suited for CI
|
var path = require('path')
process.env.BUILD_TEST = 'true'
var webpackConfig = require('./webpack.config')
delete webpackConfig.entry
delete webpackConfig.output
webpackConfig.module.preLoaders = [{
test: /\.js$/,
include: path.resolve('src/'),
loader: 'babel-istanbul'
}]
module.exports = function (config) {
config.set({
basePath: './',
frameworks: ['jasmine'],
files: [{
pattern: 'spec/*.spec.js',
watched: false
}],
preprocessors: {
'spec/*.spec.js': ['webpack', 'sourcemap']
},
coverageReporter: {
dir: 'coverage',
reporters: [{ type: 'lcov', subdir: 'lcov' }]
},
webpack: webpackConfig,
webpackMiddleware: {noInfo: true},
reporters: ['dots', 'coverage'],
port: 9876,
runnerPort: 9100,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['ChromeHeadlessNoSandbox'],
customLaunchers: {
ChromeHeadlessNoSandbox: {
base: 'ChromeHeadless',
flags: ['--no-sandbox']
}
},
captureTimeout: 8000,
singleRun: true,
reportSlowerThan: 500
})
}
|
var path = require('path')
process.env.BUILD_TEST = 'true'
var webpackConfig = require('./webpack.config')
delete webpackConfig.entry
delete webpackConfig.output
webpackConfig.module.preLoaders = [{
test: /\.js$/,
include: path.resolve('src/'),
loader: 'babel-istanbul'
}]
module.exports = function (config) {
config.set({
basePath: './',
frameworks: ['jasmine'],
files: [{
pattern: 'spec/*.spec.js',
watched: false
}],
preprocessors: {
'spec/*.spec.js': ['webpack', 'sourcemap']
},
coverageReporter: {
dir: 'coverage',
reporters: [{ type: 'lcov', subdir: 'lcov' }]
},
webpack: webpackConfig,
webpackMiddleware: {noInfo: true},
reporters: ['progress', 'coverage'],
port: 9876,
runnerPort: 9100,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['ChromeHeadlessNoSandbox'],
customLaunchers: {
ChromeHeadlessNoSandbox: {
base: 'ChromeHeadless',
flags: ['--no-sandbox']
}
},
captureTimeout: 8000,
singleRun: true,
reportSlowerThan: 500
})
}
|
Update user migration file with facebook_id column
|
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('facebook_id')->unique();
$table->string('avatar');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('users');
}
}
|
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('users');
}
}
|
Fix observers dropping their items when joining after dying, but not respawning
|
package in.twizmwaz.cardinal.util;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect;
public class PlayerUtil {
public static void resetPlayer(Player player) {
player.setMaxHealth(20);
player.setHealth(20);
player.setFoodLevel(20);
player.setSaturation(20);
player.getInventory().clear();
player.getInventory().setArmorContents(new ItemStack[]{new ItemStack(Material.AIR), new ItemStack(Material.AIR), new ItemStack(Material.AIR), new ItemStack(Material.AIR)});
for (PotionEffect effect : player.getActivePotionEffects()) {
try {
player.removePotionEffect(effect.getType());
} catch (NullPointerException e) {
}
}
player.clearIgnorantEffects();
player.setWalkSpeed(0.2F);
}
}
|
package in.twizmwaz.cardinal.util;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect;
public class PlayerUtil {
public static void resetPlayer(Player player) {
player.setMaxHealth(20);
player.setFoodLevel(20);
player.setSaturation(20);
player.getInventory().clear();
player.getInventory().setArmorContents(new ItemStack[]{new ItemStack(Material.AIR), new ItemStack(Material.AIR), new ItemStack(Material.AIR), new ItemStack(Material.AIR)});
for (PotionEffect effect : player.getActivePotionEffects()) {
try {
player.removePotionEffect(effect.getType());
} catch (NullPointerException e) {
}
}
player.clearIgnorantEffects();
player.setWalkSpeed(0.2F);
}
}
|
Make 404 page render as HTML
|
'use strict';
var bodyParser = require('body-parser');
var express = require('express');
var app = express();
var Config = require('./config/index');
//var SessionConfig = require('./config/session'); /* Requires mongo and isn't used yet. */
var NunjucksEnv = require('./config/nunjucks')(app);
var server = app.listen(Config.SERVER_PORT, Config.SERVER_ADDRESS, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Developers\' Guild Website listening at http://%s:%s in ' +
'%s mode.', host, port, Config.NODE_ENV);
});
var io = require('socket.io')(server);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//app.use(SessionConfig); /* Requires mongo and isn't used yet. */
app.use(express.static('public'));
var routerIndex = require('./routes');
// Use the routers
app.use(routerIndex);
require('./events')(io);
// Handle 404 Error
app.use(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.send('<h1>404</h1>');
res.end();
});
|
'use strict';
var bodyParser = require('body-parser');
var express = require('express');
var app = express();
var Config = require('./config/index');
//var SessionConfig = require('./config/session'); /* Requires mongo and isn't used yet. */
var NunjucksEnv = require('./config/nunjucks')(app);
var server = app.listen(Config.SERVER_PORT, Config.SERVER_ADDRESS, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Developers\' Guild Website listening at http://%s:%s in ' +
'%s mode.', host, port, Config.NODE_ENV);
});
var io = require('socket.io')(server);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//app.use(SessionConfig); /* Requires mongo and isn't used yet. */
app.use(express.static('public'));
var routerIndex = require('./routes');
// Use the routers
app.use(routerIndex);
require('./events')(io);
// Handle 404 Error
app.use(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.send('<h1>404</h1>');
res.end();
});
|
Update comment and test code.
|
/**
* Context.spec.js
* (c) 2015~ Summernote Team
* summernote may be freely distributed under the MIT license./
*/
/* jshint unused: false */
define([
'chai',
'spies',
'helper',
'jquery',
'summernote/lite/settings',
'summernote/base/core/agent',
'summernote/base/core/dom',
'summernote/base/Context'
], function (chai, spies, helper, $, settings, agent, dom, Context) {
'use strict';
var expect = chai.expect;
chai.use(spies);
describe('Context', function () {
it('should be initialized without calling callback', function () {
var options = $.extend({}, $.summernote.options);
options.langInfo = $.extend(true, {}, $.summernote.lang['en-US'], $.summernote.lang[options.lang]);
var spy = chai.spy();
var $note = $('<div><p>hello</p></div>');
$note.on('summernote.change', spy);
var context = new Context($note, options);
expect(spy).to.have.not.been.called();
context.invoke('insertText', 'hello');
expect(spy).to.have.been.called();
});
});
});
|
/**
* Context.spec.js
* (c) 2015~ Summernote Team
* summernote may be freely distributed under the MIT license./
*/
/* jshint unused: false */
define([
'chai',
'spies',
'helper',
'jquery',
'summernote/lite/settings',
'summernote/base/core/agent',
'summernote/base/core/dom',
'summernote/base/Context'
], function (chai, spies, helper, $, settings, agent, dom, Context) {
'use strict';
var expect = chai.expect;
chai.use(spies);
describe('Context.Initialize.Check', function () {
var options = $.extend({}, $.summernote.options);
options.langInfo = $.extend(true, {}, $.summernote.lang['en-US'], $.summernote.lang[options.lang]);
var context = new Context($('<div><p>hello</p></div>'), options);
var $note = context.layoutInfo.note;
var spy = chai.spy();
$note.on('summernote.change', spy);
expect(spy).to.have.not.been.called();
var expectToHaveBeenCalled = function () {
expect(spy).to.have.been.called();
};
expect(expectToHaveBeenCalled).throw(chai.AssertionError);
});
});
|
Tweak the hack to fix bug when scanning through a proxy
|
# Utility to parse HTTP responses
# http://pythonwise.blogspot.com/2010/02/parse-http-response.html
from StringIO import StringIO
from httplib import HTTPResponse
class FakeSocket(StringIO):
def makefile(self, *args, **kw):
return self
def parse_http_response(sock):
try:
# H4ck to standardize the API between sockets and SSLConnection objects
response = sock.read(4096)
except AttributeError:
response = sock.recv(4096)
if 'HTTP/' not in response:
# Try to get the rest of the response
try:
response += sock.read(4096)
except AttributeError:
response += sock.recv(4096)
fake_sock = FakeSocket(response)
response = HTTPResponse(fake_sock)
response.begin()
return response
|
# Utility to parse HTTP responses
# http://pythonwise.blogspot.com/2010/02/parse-http-response.html
from StringIO import StringIO
from httplib import HTTPResponse
class FakeSocket(StringIO):
def makefile(self, *args, **kw):
return self
def parse_http_response(sock):
try:
# H4ck to standardize the API between sockets and SSLConnection objects
# sock is a Python socket
sock.read = sock.recv
except AttributeError:
# sock is an SSLConnection
pass
response = sock.read(4096)
if 'HTTP/' not in response:
# Try to get the rest of the response
response += sock.read(4096)
fake_sock = FakeSocket(response)
response = HTTPResponse(fake_sock)
response.begin()
return response
|
Exit streaming example once all streams have been flushed
|
<?php
// this example executes some commands within the given running container and
// displays the streaming output as it happens.
require __DIR__ . '/../vendor/autoload.php';
use React\EventLoop\Factory as LoopFactory;
use Clue\React\Docker\Factory;
use React\Stream\Stream;
$container = 'asd';
//$cmd = array('echo', 'hello world');
//$cmd = array('sleep', '2');
$cmd = array('sh', '-c', 'echo -n hello && sleep 1 && echo world && sleep 1 && env');
//$cmd = array('cat', 'invalid-path');
if (isset($argv[1])) {
$container = $argv[1];
$cmd = array_slice($argv, 2);
}
$loop = LoopFactory::create();
$factory = new Factory($loop);
$client = $factory->createClient();
$out = new Stream(STDOUT, $loop);
$out->pause();
// unkown exit code by default
$exit = 1;
$client->execCreate($container, $cmd)->then(function ($info) use ($client, $out, &$exit) {
$stream = $client->execStartStream($info['Id']);
$stream->pipe($out);
$stream->on('error', 'printf');
// remember exit code of executed command once it closes
$stream->on('close', function () use ($client, $info, &$exit) {
$client->execInspect($info['Id'])->then(function ($info) use (&$exit) {
$exit = $info['ExitCode'];
}, 'printf');
});
}, 'printf');
$loop->run();
exit($exit);
|
<?php
// this example executes some commands within the given running container and
// displays the streaming output as it happens.
require __DIR__ . '/../vendor/autoload.php';
use React\EventLoop\Factory as LoopFactory;
use Clue\React\Docker\Factory;
use React\Stream\Stream;
$container = 'asd';
//$cmd = array('echo', 'hello world');
//$cmd = array('sleep', '2');
$cmd = array('sh', '-c', 'echo -n hello && sleep 1 && echo world && sleep 1 && env');
//$cmd = array('cat', 'invalid-path');
if (isset($argv[1])) {
$container = $argv[1];
$cmd = array_slice($argv, 2);
}
$loop = LoopFactory::create();
$factory = new Factory($loop);
$client = $factory->createClient();
$out = new Stream(STDOUT, $loop);
$out->pause();
$client->execCreate($container, $cmd)->then(function ($info) use ($client, $out) {
$stream = $client->execStartStream($info['Id']);
$stream->pipe($out);
$stream->on('error', 'printf');
// exit with error code of executed command once it closes
$stream->on('close', function () use ($client, $info) {
$client->execInspect($info['Id'])->then(function ($info) {
exit($info['ExitCode']);
}, 'printf');
});
}, 'printf');
$loop->run();
|
Delete argument "-1" from Abort()
|
package static
import (
"github.com/gin-gonic/gin"
"net/http"
"os"
"path"
"path/filepath"
)
func exists(name string) bool {
_, err := os.Stat(name)
return !os.IsNotExist(err)
}
// Static returns a middleware handler that serves static files in the given directory.
func Serve(directories ...interface{}) gin.HandlerFunc {
fileservers := []http.Handler{}
for i := 0; i < len(directories); i++ {
directory, err := filepath.Abs(directories[i].(string))
if err != nil {
panic(err)
}
fileservers = append(fileservers, http.FileServer(http.Dir(directory)))
}
return func(c *gin.Context) {
for i := 0; i < len(directories); i++ {
directory := directories[i].(string)
p := path.Join(directory, c.Request.URL.Path)
if exists(p) {
fileservers[i].ServeHTTP(c.Writer, c.Request)
c.Abort()
break
}
}
}
}
|
package static
import (
"github.com/gin-gonic/gin"
"net/http"
"os"
"path"
"path/filepath"
)
func exists(name string) bool {
_, err := os.Stat(name)
return !os.IsNotExist(err)
}
// Static returns a middleware handler that serves static files in the given directory.
func Serve(directories ...interface{}) gin.HandlerFunc {
fileservers := []http.Handler{}
for i := 0; i < len(directories); i++ {
directory, err := filepath.Abs(directories[i].(string))
if err != nil {
panic(err)
}
fileservers = append(fileservers, http.FileServer(http.Dir(directory)))
}
return func(c *gin.Context) {
for i := 0; i < len(directories); i++ {
directory := directories[i].(string)
p := path.Join(directory, c.Request.URL.Path)
if exists(p) {
fileservers[i].ServeHTTP(c.Writer, c.Request)
c.Abort(-1)
break
}
}
}
}
|
Fix for order exists helper
This will return partial matches when using the orderNumber query parameter filter.
|
<?php
namespace LaravelShipStation\Helpers;
class Orders extends Endpoint
{
/**
* Create a single order in ShipStation.
*
* @param array $order
* @return array
*/
public function create($order)
{
return $this->post($order, 'createorder');
}
/**
* Does the specified order exist by the given order number?
*
* @param mixed $orderNumber
* @return bool
*/
public function exists($orderNumber)
{
$orders = $this->get([
'orderNumber' => $orderNumber
]);
foreach ($orders->orders as $order) {
if ($order->orderNumber == $orderNumber) {
return true;
}
}
return false;
}
/**
* How many orders are awaiting shipment?
*
* @return int
*/
public function awaitingShipmentCount()
{
$count = $this->get([
'orderStatus' => 'awaiting_shipment'
]);
return isset($count->total) ? $count->total : 0;
}
}
|
<?php
namespace LaravelShipStation\Helpers;
class Orders extends Endpoint
{
/**
* Create a single order in ShipStation.
*
* @param array $order
* @return array
*/
public function create($order)
{
return $this->post($order, 'createorder');
}
/**
* Does the specified order exist by the given order number?
*
* @param mixed $orderNumber
* @return bool
*/
public function exists($orderNumber)
{
$order = $this->get([
'orderNumber' => $orderNumber
]);
return isset($order->total) && $order->total > 0 ? true : false;
}
/**
* How many orders are awaiting shipment?
*
* @return int
*/
public function awaitingShipmentCount()
{
$count = $this->get([
'orderStatus' => 'awaiting_shipment'
]);
return isset($count->total) ? $count->total : 0;
}
}
|
Use new colours enum in output
|
<?php
namespace Bolt;
use Bolt\Interfaces\Connection;
use Bolt\Job\Colours;
abstract class Job extends Base
{
protected $connection;
public $type = null;
public $data = array();
public $receipt = null;
public function __construct(Connection $connection = null)
{
$this->connection = $connection;
}
abstract public function execute($data = null);
protected function output($message, $type = null)
{
switch ($type)
{
case "system":
$colour = Colours::SYSTEM;
break;
case "job":
$colour = Colours::JOB;
break;
case "error":
$colour = Colours::ERROR;
break;
default:
$colour = Colours::DEFAULT;
break;
}
echo(sprintf("- %s(%s) %s \033[0m \n", $colour, date("c"), $message));
}
}
?>
|
<?php
namespace Bolt;
use Bolt\Interfaces\Connection;
abstract class Job extends Base
{
protected $connection;
public $type = null;
public $data = array();
public $receipt = null;
public function __construct(Connection $connection = null)
{
$this->connection = $connection;
}
abstract public function execute($data = null);
protected function output($message, $type = null)
{
switch ($type)
{
case "system":
$colour = Job\Output::SYSTEM;
break;
case "job":
$colour = Job\Output::JOB;
break;
case "error":
$colour = Job\Output::ERROR;
break;
default:
$colour = Job\Output::DEFAULT;
break;
}
echo(sprintf("- %s(%s) %s \033[0m \n", $colour, date("c"), $message));
}
}
?>
|
Add isDerMarktEnabled to defaultConfigs seeder
|
module.exports = {
up: queryInterface => {
return queryInterface.bulkInsert('configs', [{
app: 'default',
baseUrl: 'https://domain.com',
currency: 'EUR',
defaultCity: 'Berlin',
defaultCountry: 'Germany',
defaultLatitude: 52.53647,
defaultLongitude: 13.40780,
description: 'HOFFNUNG 3000 is a festival',
festivalDateEnd: '2017-08-27',
festivalDateStart: '2017-08-24',
festivalTicketPrice: 10.00,
gifStreamServerUrl: '',
isActivityStreamEnabled: true,
isAnonymizationEnabled: true,
isDerMarktEnabled: true,
isInboxEnabled: true,
isRandomMeetingEnabled: true,
isSignUpParticipantEnabled: true,
isSignUpVisitorEnabled: true,
mailAddressAdmin: 'admin@domain.com',
mailAddressRobot: 'noreply@domain.com',
maximumParticipantsCount: 30,
participationPrice: 25.00,
title: 'HOFFNUNG 3000',
transferBIC: '',
transferBankName: '',
transferIBAN: '',
transferReceiverName: '',
videoHomeId: '',
videoIntroductionId: '',
}])
},
down: queryInterface => {
return queryInterface.bulkDelete('configs', [])
},
}
|
module.exports = {
up: queryInterface => {
return queryInterface.bulkInsert('configs', [{
app: 'default',
baseUrl: 'https://domain.com',
currency: 'EUR',
defaultCity: 'Berlin',
defaultCountry: 'Germany',
defaultLatitude: 52.53647,
defaultLongitude: 13.40780,
description: 'HOFFNUNG 3000 is a festival',
festivalDateEnd: '2017-08-27',
festivalDateStart: '2017-08-24',
festivalTicketPrice: 10.00,
gifStreamServerUrl: '',
isActivityStreamEnabled: true,
isAnonymizationEnabled: true,
isInboxEnabled: true,
isRandomMeetingEnabled: true,
isSignUpParticipantEnabled: true,
isSignUpVisitorEnabled: true,
mailAddressAdmin: 'admin@domain.com',
mailAddressRobot: 'noreply@domain.com',
maximumParticipantsCount: 30,
participationPrice: 25.00,
title: 'HOFFNUNG 3000',
transferBIC: '',
transferBankName: '',
transferIBAN: '',
transferReceiverName: '',
videoHomeId: '',
videoIntroductionId: '',
}])
},
down: queryInterface => {
return queryInterface.bulkDelete('configs', [])
},
}
|
Insert dynamic data of the actual month
|
function randomValue () {
const value = [];
const lengthOfTheArray = 30*24*12;
for (var i=0; i <= lengthOfTheArray ; i++) {
value.push((Math.random() * 10).toFixed(1))
}
return value.join(",");
}
Meteor.startup(() => {
if (
process.env.ENVIRONMENT !== "production" &&
SiteMonthReadingsAggregates.find().count() === 0
) {
SiteMonthReadingsAggregates.insert({
podId: "podId",
month: moment().format("YYYY-MM"),
readings: {
"energia attiva": randomValue(),
"enregia reattiva": randomValue(),
"potenza massima": randomValue(),
"temperature": randomValue(),
"humidity": randomValue(),
"illuminance": randomValue(),
"co2": randomValue()
}
});
}
});
|
function randomValue () {
const value = [];
const lengthOfTheArray = 30*24*12;
for (var i=0; i <= lengthOfTheArray ; i++) {
value.push((Math.random() * 10).toFixed(1))
}
return value.join(",");
}
Meteor.startup(() => {
if (
process.env.ENVIRONMENT !== "production" &&
SiteMonthReadingsAggregates.find().count() === 0
) {
SiteMonthReadingsAggregates.insert({
podId: "podId",
month: "2015-10",
readings: {
"energia attiva": randomValue(),
"enregia reattiva": randomValue(),
"potenza massima": randomValue(),
"temperature": randomValue(),
"humidity": randomValue(),
"illuminance": randomValue(),
"co2": randomValue()
}
});
}
});
|
Fix bug in from location
|
(function() {
var BackgroundGeo = function($q) {
var from;
current()
.then(function(data){
from = new google.maps.LatLng(data.latitude, data.longitude);
});
var instance = {
current: current,
distance: distance
};
///////////////
function current(){
var locator = $q.defer();
locator.resolve(window.currLocation.coords);
return locator.promise;
};
function distance(lat, lng){
var dist, to;
to = new google.maps.LatLng(lat, lng);
from = new google.maps.LatLng(window.currLocation.coords.latitude, window.currLocation.coords.longitude);
dist = google.maps.geometry.spherical.computeDistanceBetween(from, to) * 0.000621371192;
return Math.floor((dist + 0.005)*100) / 100;
};
return instance;
};
BackgroundGeo
.$inject = ['$q'];
angular
.module('app.services.BackgroundGeo', [])
.factory('BackgroundGeo', BackgroundGeo);
})();
|
(function() {
var BackgroundGeo = function($q) {
var from;
current()
.then(function(data){
from = new google.maps.LatLng(data.latitude, data.longitude);
});
instance = {
current: current,
distance: distance
};
///////////////
function current(){
var locator = $q.defer();
locator.resolve(window.currLocation.coords);
return locator.promise;
}
function distance(lat, lng){
var dist, to;
to = new google.maps.LatLng(lat, lng);
dist = google.maps.geometry.spherical.computeDistanceBetween(from, to) * 0.000621371192;
return Math.floor((dist + 0.005)*100) / 100;
}
return instance;
};
BackgroundGeo
.$inject = ['$q'];
angular
.module('app.services.BackgroundGeo', [])
.factory('BackgroundGeo', BackgroundGeo);
})();
|
Add quick test of Backbone access to API endpoint
|
'use strict';
var Backbone = require('backbone');
var $ = require('jquery');
Backbone.$ = $;
// Test business collection
var BusinessCollection = require('../collections/business-collection');
var testCollection = new BusinessCollection();
testCollection.fetch();
var InitView = Backbone.View.extend({
tagName: 'div',
initialize: function() {
this.render();
},
render: function() {
// Add logic for finding current location!
// If current location exists, set #start to it; otherwise, leave a placeholder
var template = require('../templates/init-template.hbs');
this.$el.html(template());
return this;
},
events: {
'click #search': 'search'
},
search: function(e) {
e.preventDefault(); // Otherwise the page will reload!
// Grab start and destination from the form
var start = this.$el.closest('div').find('#start').val();
var destination = this.$el.closest('div').find('#destination').val();
// Encode the route as a URL
var routeUrl = 'start=' + encodeURI(start) + '&dest=' + encodeURI(destination);
// Navigate to #map with that URL
Backbone.history.navigate('#map' + '?' + routeUrl, {
trigger: true
});
}
});
module.exports = InitView;
|
'use strict';
var Backbone = require('backbone');
var $ = require('jquery');
Backbone.$ = $;
var InitView = Backbone.View.extend({
tagName: 'div',
initialize: function() {
this.render();
},
render: function() {
// Add logic for finding current location!
// If current location exists, set #start to it; otherwise, leave a placeholder
var template = require('../templates/init-template.hbs');
this.$el.html(template());
return this;
},
events: {
'click #search': 'search'
},
search: function(e) {
e.preventDefault(); // Otherwise the page will reload!
// Grab start and destination from the form
var start = this.$el.closest('div').find('#start').val();
var destination = this.$el.closest('div').find('#destination').val();
// Encode the route as a URL
var routeUrl = 'start=' + encodeURI(start) + '&dest=' + encodeURI(destination);
// Navigate to #map with that URL
Backbone.history.navigate('#map' + '?' + routeUrl, {
trigger: true
});
}
});
module.exports = InitView;
|
Remove obsolete code which stopped non-admins from editing.
|
<?php
namespace App\Providers;
use App\Models\Site;
use App\Models\Page;
use App\Models\Media;
use App\Policies\PagePolicy;
use App\Policies\SitePolicy;
use App\Policies\MediaPolicy;
use App\Models\Definitions\Block as BlockDefinition;
use App\Models\Definitions\Layout as LayoutDefinition;
use App\Models\Definitions\Region as RegionDefinition;
use App\Policies\Definitions\BlockPolicy as BlockDefinitionPolicy;
use App\Policies\Definitions\LayoutPolicy as LayoutDefinitionPolicy;
use App\Policies\Definitions\RegionPolicy as RegionDefinitionPolicy;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
Page::class => PagePolicy::class,
Site::class => SitePolicy::class,
Media::class => MediaPolicy::class,
BlockDefinition::class => BlockDefinitionPolicy::class,
LayoutDefinition::class => LayoutDefinitionPolicy::class,
RegionDefinition::class => RegionDefinitionPolicy::class,
];
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
//
}
}
|
<?php
namespace App\Providers;
use App\Models\Site;
use App\Models\Page;
use App\Models\Media;
use App\Policies\PagePolicy;
use App\Policies\SitePolicy;
use App\Policies\RoutePolicy;
use App\Policies\MediaPolicy;
use App\Models\Definitions\Block as BlockDefinition;
use App\Models\Definitions\Layout as LayoutDefinition;
use App\Models\Definitions\Region as RegionDefinition;
use App\Policies\Definitions\BlockPolicy as BlockDefinitionPolicy;
use App\Policies\Definitions\LayoutPolicy as LayoutDefinitionPolicy;
use App\Policies\Definitions\RegionPolicy as RegionDefinitionPolicy;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
Page::class => PagePolicy::class,
Page::class => RoutePolicy::class,
Site::class => SitePolicy::class,
Media::class => MediaPolicy::class,
BlockDefinition::class => BlockDefinitionPolicy::class,
LayoutDefinition::class => LayoutDefinitionPolicy::class,
RegionDefinition::class => RegionDefinitionPolicy::class,
];
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
//
}
}
|
Build eror complaining of blank lines?
Build error complaining of blank lines?
|
from django.contrib import admin
from sorl.thumbnail.admin import AdminImageMixin
from .models import Section, Group, Item, Image, Area, Profile
class ImageInline(AdminImageMixin, admin.StackedInline):
model = Image
extra = 5
class ItemAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',), }
list_display = ('title', 'group', 'area', 'user', 'is_active', 'posted', 'updated')
list_filter = ('area', 'group', 'is_active', 'posted',)
search_fields = ('title', 'description', 'user__email')
inlines = [ImageInline]
class GroupAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',), }
list_display = ('title', 'slug', 'section', 'count')
list_filter = ('section',)
search_fields = ('title', 'section__title')
class SectionAdmin(admin.ModelAdmin):
list_display = ('title',)
class AreaAdmin(admin.ModelAdmin):
list_display = (
'title',
)
prepopulated_fields = {'slug': ('title',)}
class ProfileAdmin(admin.ModelAdmin):
list_display = ('user', 'phone')
search_fields = ('user__username', 'phone')
admin.site.register(Area, AreaAdmin)
admin.site.register(Section, SectionAdmin)
admin.site.register(Group, GroupAdmin)
admin.site.register(Item, ItemAdmin)
admin.site.register(Profile, ProfileAdmin)
|
from django.contrib import admin
from sorl.thumbnail.admin import AdminImageMixin
from .models import Section, Group, Item, Image, Area, Profile
class ImageInline(AdminImageMixin, admin.StackedInline):
model = Image
extra = 5
class ItemAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',), }
list_display = ('title', 'group', 'area', 'user', 'is_active', 'posted', 'updated')
list_filter = ('area', 'group', 'is_active', 'posted',)
search_fields = ('title', 'description', 'user__email')
inlines = [ImageInline]
class GroupAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',), }
list_display = ('title', 'slug', 'section', 'count')
list_filter = ('section',)
search_fields = ('title', 'section__title')
class SectionAdmin(admin.ModelAdmin):
list_display = ('title',)
class AreaAdmin(admin.ModelAdmin):
list_display = (
'title',
)
prepopulated_fields = {'slug': ('title',)}
class ProfileAdmin(admin.ModelAdmin):
list_display = ('user', 'phone')
search_fields = ('user__username', 'phone')
admin.site.register(Area, AreaAdmin)
admin.site.register(Section, SectionAdmin)
admin.site.register(Group, GroupAdmin)
admin.site.register(Item, ItemAdmin)
admin.site.register(Profile, ProfileAdmin)
|
Improve flexibility, readability and performance
Extracting the operation of counting jobs into a single variable has many
advantages:
1. Flexibility: it's easier now to modify the statement and be sure that the
change will be propagated to the rest of the code
2. Readability: reading 'jobCount' inside an algorithm is much more readable
than 'Jobs.find({}).count()'
3. Performance: you just make one call to the database and then store the result,
which is not going to change throughout this code.
|
Jobs = new Mongo.Collection('jobs'); //both on client and server
Applications = new Mongo.Collection('applications');
// added repoz channel
Meteor.startup(function() {
// console.log('Jobs.remove({})');
// Jobs.remove({});
var jobCount = Jobs.find({}).count();
if (jobCount === 0) {
console.log('job count === ', jobCount, 'inserting jobs');
Jobs.insert({_id: '0', title: 'Select a job position...'});
Jobs.insert({_id: '1', title: 'Haiti Village Photographer'});
Jobs.insert({_id: '2', title: 'Rapallo On The Beach'});
} else {
console.log('server/getreel.js:', 'job count > 0 (', jobCount, '): no insert needed');
}
});
Meteor.methods({
apply: function(args) {
if (!Meteor.userId()) {
throw new Meteor.Error('not-authorized');
}
console.log(args);
Applications.insert({
createdAt: new Date(),
applicant: Meteor.userId(),
firstname: args.firstname,
lastname: args.lastname,
job: args.job,
resume: args.resume,
videofile: args.videofile,
videolink: args.videolink
});
}
});
|
Jobs = new Mongo.Collection('jobs'); //both on client and server
Applications = new Mongo.Collection('applications');
// added repoz channel
Meteor.startup(function() {
// console.log('Jobs.remove({})');
// Jobs.remove({});
if (Jobs.find({}).count() === 0) {
console.log('job count === ', Jobs.find({}).count(), 'inserting jobs');
Jobs.insert({_id: '0', title: 'Select a job position...'});
Jobs.insert({_id: '1', title: 'Haiti Village Photographer'});
Jobs.insert({_id: '2', title: 'Rapallo On The Beach'});
} else {
console.log('server/getreel.js:', 'job count > 0 (', Jobs.find({}).count(), '): no insert needed');
}
});
Meteor.methods({
apply: function(args) {
if (!Meteor.userId()) {
throw new Meteor.Error('not-authorized');
}
console.log(args);
Applications.insert({
createdAt: new Date(),
applicant: Meteor.userId(),
firstname: args.firstname,
lastname: args.lastname,
job: args.job,
resume: args.resume,
videofile: args.videofile,
videolink: args.videolink
});
}
});
|
Send text to wget/curl unless html content-type
|
#!/usr/bin/env python
import os
from flask import Flask, render_template, request, make_response
from names import get_full_name
app = Flask(__name__)
@app.route("/")
def index():
content_type = request.headers.get('Content-Type', '')
browser = request.headers.get('User-Agent', '').lower()
if browser[:4] in ('curl', 'wget') and content_type in ('text/plain', ''):
return make_response((u"{0}\n".format(get_full_name()), 200,
{'Content-Type': 'text/plain'}))
else:
return render_template('index.html', name=get_full_name())
if __name__ == "__main__":
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
|
#!/usr/bin/env python
import os
from flask import Flask, render_template, request, make_response
from names import get_full_name
app = Flask(__name__)
@app.route("/")
def index():
if (request.headers.get('User-Agent', '')[:4].lower() == 'curl' or
request.headers['Content-Type'] == 'text/plain'):
return make_response((u"{0}\n".format(get_full_name()), 200,
{'Content-Type': 'text/plain'}))
else:
return render_template('index.html', name=get_full_name())
if __name__ == "__main__":
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
|
Fix map undefined issue in welcome dialogue
|
angular.module('beam.controllers')
.controller('beamSettingsController', function($scope, configService) {
this.save = function() {
configService.set('host', $scope.settings.host);
configService.set('tls', $scope.settings.tls || false);
configService.set('nick', $scope.settings.nick);
var channels = [];
if ($scope.settings.channels != null) {
channels = $scope.settings.channels.map(function(item) {
return item.text;
});
}
configService.set('channels', channels);
if ($scope.settings.advanced) {
configService.set('port', $scope.settings.port);
configService.set('user', $scope.settings.user || 'beam');
configService.set('real', $scope.settings.real || 'Beam.io');
configService.set('ignoreSecure', $scope.settings.ignoreSecure || false);
} else {
configService.set('port', $scope.settings.tls ? 6697 : 6667);
}
configService.save();
require('ipc').send('welcome-done', true);
};
});
|
angular.module('beam.controllers')
.controller('beamSettingsController', function($scope, configService) {
this.save = function() {
configService.set('host', $scope.settings.host);
configService.set('tls', $scope.settings.tls === undefined ? false : $scope.settings.tls);
configService.set('nick', $scope.settings.nick);
var channels = $scope.settings.channels.map(function(item) {
return item.text;
});
configService.set('channels', channels);
if ($scope.settings.advanced) {
configService.set('port', $scope.settings.port);
configService.set('user', $scope.settings.user);
configService.set('real', $scope.settings.real);
configService.set('ignoreSecure', $scope.settings.ignoreSecure);
} else {
configService.set('port', $scope.settings.tls ? 6697 : 6667);
}
configService.save();
require('ipc').send('welcome-done', true);
};
});
|
Make cv path class attribute
|
import os
import yaml
from git import Repo
class GitCv:
def __init__(self, cv_path, repo_path):
self._repo_path = os.path.join(repo_path, 'cv')
self._cv_path = cv_path
self._load_cv()
def _load_cv(self):
with open(self._cv_path, "r") as f:
self._cv = yaml.load(f)
def _create_repo(self):
self._repo = Repo.init(self._repo_path)
def _create_branches(self):
for stream in self._cv:
for entry in stream:
self._create_branch(entry)
def _create_branch(self, branch_name):
self._repo.create_head(branch_name)
def _create_file_and_commit(self, file_name):
open(os.path.join(self._repo_path, file_name), 'w').close()
self._repo.index.add([file_name])
self._repo.index.commit('Add {0}'.format(file_name))
def create(self):
self._create_repo()
self._create_file_and_commit('dummy.txt')
self._create_branches()
if __name__ == '__main__':
GitCv('../cv.yaml', '../target').create()
|
import os
import yaml
from git import Repo
class GitCv:
def __init__(self, cv_path, repo_path):
self._cv = self._load_cv(cv_path)
self._repo_path = os.path.join(repo_path, 'cv')
def _load_cv(self, cv_path):
with open(cv_path, "r") as f:
cv = yaml.load(f)
return cv
def _create_repo(self):
self._repo = Repo.init(self._repo_path)
def _create_branches(self):
for stream in self._cv:
for entry in stream:
self._create_branch(entry)
def _create_branch(self, branch_name):
self._repo.create_head(branch_name)
def _create_file_and_commit(self, file_name):
open(os.path.join(self._repo_path, file_name), 'w').close()
self._repo.index.add([file_name])
self._repo.index.commit('Add {0}'.format(file_name))
def create(self):
self._create_repo()
self._create_file_and_commit('dummy.txt')
self._create_branches()
if __name__ == '__main__':
GitCv('../cv.yaml', '../target').create()
|
Remove batching code. (not in celery contrib)
|
import os
import sys
# Append .. to sys path
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import multiscanner
from celery import Celery
app = Celery('celery_worker', broker='pyamqp://guest@localhost//')
@app.task
def multiscanner_celery(filelist, config=multiscanner.CONFIG):
'''
TODO: Add other ars + config options...
This function essentially takes in a file list and runs
multiscanner on them. Results are stored in the
storage configured in storage.ini.
Usage:
from celery_worker import multiscanner_celery
multiscanner_celery.delay([list, of, files, to, scan])
'''
storage_conf = multiscanner.common.get_storage_config_path(config)
storage_handler = multiscanner.storage.StorageHandler(configfile=storage_conf)
resultlist = multiscanner.multiscan(filelist, configfile=config)
results = multiscanner.parse_reports(resultlist, python=True)
storage_handler.store(results, wait=False)
storage_handler.close()
return results
|
import os
import sys
# Append .. to sys path
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import multiscanner
from celery import Celery
from celery.contrib.batches import Batches
app = Celery('celery_worker', broker='pyamqp://guest@localhost//')
@app.task(base=Batches, flush_every=100, flush_interval=10)
def multiscanner_celery(filelist, config=multiscanner.CONFIG):
'''
TODO: Add other ars + config options...
This function essentially takes in a file list and runs
multiscanner on them. Results are stored in the
storage configured in storage.ini.
Usage:
from celery_worker import multiscanner_celery
multiscanner_celery.delay([list, of, files, to, scan])
'''
storage_conf = multiscanner.common.get_storage_config_path(config)
storage_handler = multiscanner.storage.StorageHandler(configfile=storage_conf)
resultlist = multiscanner.multiscan(filelist, configfile=config)
results = multiscanner.parse_reports(resultlist, python=True)
storage_handler.store(results, wait=False)
storage_handler.close()
return results
|
Revert version number to 0.2.10
|
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='Flask-RESTful',
version='0.2.10',
url='https://www.github.com/twilio/flask-restful/',
author='Kyle Conroy',
author_email='help@twilio.com',
description='Simple framework for creating REST APIs',
packages=find_packages(),
zip_safe=False,
include_package_data=True,
platforms='any',
test_suite = 'nose.collector',
install_requires=[
'aniso8601>=0.82',
'Flask>=0.8',
'six>=1.3.0',
'pytz',
],
# Install these with "pip install -e '.[paging]'" or '.[docs]'
extras_require={
'paging': 'pycrypto>=2.6',
'docs': 'sphinx',
}
)
|
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='Flask-RESTful',
version='0.2.11',
url='https://www.github.com/twilio/flask-restful/',
author='Kyle Conroy',
author_email='help@twilio.com',
description='Simple framework for creating REST APIs',
packages=find_packages(),
zip_safe=False,
include_package_data=True,
platforms='any',
test_suite = 'nose.collector',
install_requires=[
'aniso8601>=0.82',
'Flask>=0.8',
'six>=1.3.0',
'pytz',
],
# Install these with "pip install -e '.[paging]'" or '.[docs]'
extras_require={
'paging': 'pycrypto>=2.6',
'docs': 'sphinx',
}
)
|
Print tags out when scanning for URLs.
|
import re
import sys
from xml.sax import make_parser, handler
if len(sys.argv) < 3:
print "This script expects two arguments: \n1. The path to a posts.xml file from a Stack Overflow data dump.\n2. A URL prefix to search for."
else:
start_with = sys.argv[2]
class SOProcessor(handler.ContentHandler):
def startElement(self, name, attrs):
if name == "row":
if attrs["PostTypeId"] == "1":
body = attrs["Body"]
if start_with in body:
matches = re.findall(r'<a href="([^"]+)"', body)
for url in filter(lambda x: x.startswith(start_with), matches):
print url, attrs["Tags"]
parser = make_parser()
parser.setContentHandler(SOProcessor())
parser.parse(open(sys.argv[1]))
|
import re
import sys
from xml.sax import make_parser, handler
if len(sys.argv) < 3:
print "This script expects two arguments: \n1. The path to a posts.xml file from a Stack Overflow data dump.\n2. A URL prefix to search for."
else:
start_with = sys.argv[2]
class SOProcessor(handler.ContentHandler):
def startElement(self, name, attrs):
if name == "row":
if attrs["PostTypeId"] == "1":
body = attrs["Body"]
if start_with in body:
matches = re.findall(r'<a href="([^"]+)"', body)
for url in filter(lambda x: x.startswith(start_with), matches):
print url
parser = make_parser()
parser.setContentHandler(SOProcessor())
parser.parse(open(sys.argv[1]))
|
Enforce ordering on cluster nodes endpoint
|
from __future__ import absolute_import
from datetime import datetime, timedelta
from flask.ext.restful import reqparse
from changes.api.base import APIView
from changes.models import Cluster, JobStep, Node
class ClusterNodesAPIView(APIView):
parser = reqparse.RequestParser()
parser.add_argument('since', type=int, location='args')
def get(self, cluster_id):
cluster = Cluster.query.get(cluster_id)
if cluster is None:
return '', 404
queryset = Node.query.filter(
Node.clusters.contains(cluster),
).order_by(Node.label.asc())
args = self.parser.parse_args()
if args.since:
cutoff = datetime.utcnow() - timedelta(days=args.since)
queryset = queryset.join(
JobStep, JobStep.node_id == Node.id,
).filter(
JobStep.date_created > cutoff,
).group_by(Node)
return self.paginate(queryset)
|
from __future__ import absolute_import
from datetime import datetime, timedelta
from flask.ext.restful import reqparse
from changes.api.base import APIView
from changes.models import Cluster, JobStep, Node
class ClusterNodesAPIView(APIView):
parser = reqparse.RequestParser()
parser.add_argument('since', type=int, location='args')
def get(self, cluster_id):
cluster = Cluster.query.get(cluster_id)
if cluster is None:
return '', 404
queryset = Node.query.filter(
Node.clusters.contains(cluster),
)
args = self.parser.parse_args()
if args.since:
cutoff = datetime.utcnow() - timedelta(days=args.since)
queryset = queryset.join(
JobStep, JobStep.node_id == Node.id,
).filter(
JobStep.date_created > cutoff,
).group_by(Node)
return self.paginate(queryset)
|
Set folder name as m3u name
|
#!/usr/bin/env node
const fs = require('fs')
const path = require('path')
var fileName = process.argv[2]
console.log("Processing: " + fileName)
var PREFIX = "file://"
function createDir(folder) {
if (!fs.existsSync(folder)) {
fs.mkdirSync(folder, 0744)
}
}
function copyFiles(folderName) {
var lineReader = require('readline').createInterface({
input: require('fs').createReadStream(fileName)
})
var count = 0
lineReader.on('line', function (line) {
if (line.indexOf(PREFIX)!= -1){
var cleanedFile = decodeURIComponent(line.replace(PREFIX, ""))
count++
var paddedNumber = count > 9 ? count : "0" + count
var fileNameOnly = path.basename(cleanedFile)
var stripNonAsic = fileNameOnly.replace(/\s+/g,' ');
var newFileName = [folderName, "/", paddedNumber,"-", stripNonAsic].join("")
fs.copyFileSync(cleanedFile, newFileName, (err) => {
if (err) throw err;
});
}
})
}
var folderName = path.basename(fileName).replace(path.extname(fileName), "")
createDir(folderName)
var songCreated = copyFiles(folderName)
console.log("Done, created " + folderName + ".")
|
#!/usr/bin/env node
const fs = require('fs')
const path = require('path')
var fileName = process.argv[2]
console.log("Processing: " +fileName)
var PREFIX = "file://"
function createDir(folder) {
console.log("Create Lesson in " + folder)
if (!fs.existsSync(folder)) {
fs.mkdirSync(folder, 0744)
}
}
function copyFiles(folderName) {
var lineReader = require('readline').createInterface({
input: require('fs').createReadStream(fileName)
})
var count = 0
lineReader.on('line', function (line) {
if (line.indexOf(PREFIX)!= -1){
var cleanedFile = decodeURIComponent(line.replace(PREFIX, ""))
count++
var paddedNumber = count > 9 ? count : "0" + count
var fileNameOnly = path.basename(cleanedFile)
var stripNonAsic = fileNameOnly.replace(/\s+/g,' ');
var newFileName = [folderName, "/", paddedNumber,"-", stripNonAsic].join("")
fs.copyFileSync(cleanedFile, newFileName, (err) => {
if (err) throw err;
});
}
})
}
var folderName = new Date().toISOString().slice(0,10)
createDir(folderName)
var songCreated = copyFiles(folderName)
console.log("Done, created " + folderName + ".")
|
Fix issue with header IN wrap.
|
<?php
use Roots\Sage\Config;
use Roots\Sage\Wrapper;
?>
<!doctype html>
<html class="no-js" <?php language_attributes(); ?>>
<?php get_template_part('templates/head'); ?>
<body <?php body_class(); ?>>
<!--[if lt IE 9]>
<div class="alert alert-warning">
<?php _e('You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.', 'sage'); ?>
</div>
<![endif]-->
<?php
do_action('get_header');
get_template_part('templates/header');
?>
<div class="wrap container" role="document">
<div class="content row">
<main class="main" role="main">
<?php include Wrapper\template_path(); ?>
</main><!-- /.main -->
<?php if (Config\display_sidebar()) : ?>
<aside class="sidebar" role="complementary">
<?php include Wrapper\sidebar_path(); ?>
</aside><!-- /.sidebar -->
<?php endif; ?>
</div><!-- /.content -->
</div><!-- /.wrap -->
<?php
do_action('get_footer');
get_template_part('templates/footer');
wp_footer();
?>
</body>
</html>
|
<?php
use Roots\Sage\Config;
use Roots\Sage\Wrapper;
?>
<!doctype html>
<html class="no-js" <?php language_attributes(); ?>>
<?php get_template_part('templates/head'); ?>
<body <?php body_class(); ?>>
<!--[if lt IE 9]>
<div class="alert alert-warning">
<?php _e('You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.', 'sage'); ?>
</div>
<![endif]-->
<div class="wrap container" role="document">
<?php
do_action('get_header');
get_template_part('templates/header');
?>
<div class="content row">
<main class="main" role="main">
<?php include Wrapper\template_path(); ?>
</main><!-- /.main -->
<?php if (Config\display_sidebar()) : ?>
<aside class="sidebar" role="complementary">
<?php include Wrapper\sidebar_path(); ?>
</aside><!-- /.sidebar -->
<?php endif; ?>
</div><!-- /.content -->
</div><!-- /.wrap -->
<?php
do_action('get_footer');
get_template_part('templates/footer');
wp_footer();
?>
</body>
</html>
|
Set current version number to 0.13
|
from setuptools import setup, find_packages
__version_info__ = ('0', '1', '3')
__version__ = '.'.join(__version_info__)
setup(
name="staticjinja",
version=__version__,
description="jinja based static site generator",
author="Ceasar Bautista",
author_email="cbautista2010@gmail.com",
url="https://github.com/Ceasar/staticjinja",
keywords=["jinja", "static", "website"],
packages=["staticjinja"],
install_requires=["easywatch", "jinja2"],
classifiers=[
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2.5",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Topic :: Software Development :: Libraries :: Python Modules",
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
],
use_2to3=True,
)
|
from setuptools import setup, find_packages
__version_info__ = ('0', '1', '2')
__version__ = '.'.join(__version_info__)
setup(
name="staticjinja",
version=__version__,
description="jinja based static site generator",
author="Ceasar Bautista",
author_email="cbautista2010@gmail.com",
url="https://github.com/Ceasar/staticjinja",
keywords=["jinja", "static", "website"],
packages=["staticjinja"],
install_requires=["easywatch", "jinja2"],
classifiers=[
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2.5",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Topic :: Software Development :: Libraries :: Python Modules",
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
],
use_2to3=True,
)
|
Copy paste error leading to static and template folders not being properly installed along side the package
|
# coding=utf-8
import setuptools
def package_data_dirs(source, sub_folders):
import os
dirs = []
for d in sub_folders:
for dirname, _, files in os.walk(os.path.join(source, d)):
dirname = os.path.relpath(dirname, source)
for f in files:
dirs.append(os.path.join(dirname, f))
return dirs
def params():
name = "OctoPrint-Netconnectd"
version = "0.1"
description = "Client for netconnectd that allows configuration of netconnectd through OctoPrint's settings dialog. It's only available for Linux right now."
author = "Gina Häußge"
author_email = "osd@foosel.net"
url = "http://octoprint.org"
license = "AGPLv3"
packages = ["octoprint_netconnectd"]
package_data = {"octoprint_netconnectd": package_data_dirs('octoprint_netconnectd', ['static', 'templates'])}
include_package_data = True
zip_safe = False
install_requires = open("requirements.txt").read().split("\n")
entry_points = {
"octoprint.plugin": [
"netconnectd = octoprint_netconnectd"
]
}
return locals()
setuptools.setup(**params())
|
# coding=utf-8
import setuptools
def package_data_dirs(source, sub_folders):
import os
dirs = []
for d in sub_folders:
for dirname, _, files in os.walk(os.path.join(source, d)):
dirname = os.path.relpath(dirname, source)
for f in files:
dirs.append(os.path.join(dirname, f))
return dirs
def params():
name = "OctoPrint-Netconnectd"
version = "0.1"
description = "Client for netconnectd that allows configuration of netconnectd through OctoPrint's settings dialog. It's only available for Linux right now."
author = "Gina Häußge"
author_email = "osd@foosel.net"
url = "http://octoprint.org"
license = "AGPLv3"
packages = ["octoprint_netconnectd"]
package_data = {"octoprint": package_data_dirs('octoprint_netconnectd', ['static', 'templates'])}
include_package_data = True
zip_safe = False
install_requires = open("requirements.txt").read().split("\n")
entry_points = {
"octoprint.plugin": [
"netconnectd = octoprint_netconnectd"
]
}
return locals()
setuptools.setup(**params())
|
Fix some bugs in tests
|
from twisted.trial import unittest
from x256 import x256
class Testx256(unittest.TestCase):
"""
Test class for x256 module.
"""
def setUp(self):
self.rgb = [220, 40, 150]
self.xcolor = 162
self.hex = 'DC2896'
self.aprox_hex = 'D7087'
self.aprox_rgb = [215, 0, 135]
def test_from_rgb(self):
color = x256.from_rgb(self.rgb)
self.assertEqual(self.xcolor, color)
color = x256.from_rgb(self.rgb[0], self.rgb[1], self.rgb[2])
self.assertEqual(self.xcolor, color)
def test_from_hex(self):
color = x256.from_hex(self.hex)
self.assertEqual(self.xcolor, color)
def test_to_rgb(self):
color = x256.to_rgb(self.xcolor)
self.assertEqual(self.aprox_rgb, color)
def test_to_hex(self):
color = x256.to_hex(self.xcolor)
self.assertEqual(self.aprox_hex, color)
|
from twisted.trial import unittest
import x256
class Testx256(unittest.TestCase):
"""
Test class for x256 module.
"""
def setUp(self):
self.rgb = [220, 40, 150]
self.xcolor = 162
self.hex = 'DC2896'
self.aprox_hex = 'D7087'
self.aprox_rgb = [215, 0, 135]
def test_from_rgb(self):
color = x256.from_rgb(self.rgb)
self.assertEqual(self.xcolor, color)
color = x256.from_rgb(self.rgb[0], self.rgb[1], self.rgb[2])
self.assertEqual(self.xcolor, color)
def test_from_rgb(self):
color = x256.from_hex(self.hex)
self.assertEqual(self.xcolor, color)
def test_to_rgb(self):
color = x256.to_rgb(self.xcolor)
self.assertEqual(self.aprox_rgb, color)
def test_to_hex(self):
color = x256.to_hex(self.xcolor)
self.assertEqual(self.aprox_hex, color)
|
Fix use of raw type.
|
package net.domesdaybook.automata.base;
import net.domesdaybook.automata.State;
import net.domesdaybook.automata.Transition;
import net.domesdaybook.automata.TransitionFactory;
import net.domesdaybook.matcher.bytes.ByteMatcher;
/**
* @author Matt Palmer
*/
public class ByteMatcherTransitionFactory implements TransitionFactory<ByteMatcher, ByteMatcher>{
public Transition<ByteMatcher> create(final ByteMatcher source,
final boolean ignoreInversion,
final State<ByteMatcher> toState) {
return new ByteMatcherTransition<ByteMatcher>(source, toState);
}
}
|
package net.domesdaybook.automata.base;
import net.domesdaybook.automata.State;
import net.domesdaybook.automata.Transition;
import net.domesdaybook.automata.TransitionFactory;
import net.domesdaybook.matcher.bytes.ByteMatcher;
/**
* @author Matt Palmer
*/
public class ByteMatcherTransitionFactory implements TransitionFactory<ByteMatcher, ByteMatcher>{
public Transition<ByteMatcher> create(final ByteMatcher source,
final boolean ignoreInversion,
final State<ByteMatcher> toState) {
return new ByteMatcherTransition(source, toState);
}
}
|
Comment out no-unused-vars eslint warnings back.
src/ButtonInput.js
9:9 warning bsStyle is defined but never used no-unused-vars
9:18 warning value is defined but never used no-unused-vars
Alas, that was a bug, not a feature.
|
import React from 'react';
import Button from './Button';
import FormGroup from './FormGroup';
import InputBase from './InputBase';
import childrenValueValidation from './utils/childrenValueInputValidation';
class ButtonInput extends InputBase {
renderFormGroup(children) {
let {bsStyle, value, ...other} = this.props; // eslint-disable-line object-shorthand, no-unused-vars
return <FormGroup {...other}>{children}</FormGroup>;
}
renderInput() {
let {children, value, ...other} = this.props; // eslint-disable-line object-shorthand
let val = children ? children : value;
return <Button {...other} componentClass="input" ref="input" key="input" value={val} />;
}
}
ButtonInput.types = ['button', 'reset', 'submit'];
ButtonInput.defaultProps = {
type: 'button'
};
ButtonInput.propTypes = {
type: React.PropTypes.oneOf(ButtonInput.types),
bsStyle(props) {
//defer to Button propTypes of bsStyle
return null;
},
children: childrenValueValidation,
value: childrenValueValidation
};
export default ButtonInput;
|
import React from 'react';
import Button from './Button';
import FormGroup from './FormGroup';
import InputBase from './InputBase';
import childrenValueValidation from './utils/childrenValueInputValidation';
class ButtonInput extends InputBase {
renderFormGroup(children) {
let {bsStyle, value, ...other} = this.props; // eslint-disable-line object-shorthand
return <FormGroup {...other}>{children}</FormGroup>;
}
renderInput() {
let {children, value, ...other} = this.props; // eslint-disable-line object-shorthand
let val = children ? children : value;
return <Button {...other} componentClass="input" ref="input" key="input" value={val} />;
}
}
ButtonInput.types = ['button', 'reset', 'submit'];
ButtonInput.defaultProps = {
type: 'button'
};
ButtonInput.propTypes = {
type: React.PropTypes.oneOf(ButtonInput.types),
bsStyle(props) {
//defer to Button propTypes of bsStyle
return null;
},
children: childrenValueValidation,
value: childrenValueValidation
};
export default ButtonInput;
|
Handle output passthrou from the cli
|
'''
Used to manage the outputter system. This package is the modular system used
for managing outputters.
'''
# Import salt utils
import salt.loader
STATIC = (
'yaml_out',
'txt_out',
'raw_out',
'json_out',
)
def display_output(data, out, opts=None):
'''
Print the passed data using the desired output
'''
get_printout(out, opts)(data)
def get_printout(out, opts=None, **kwargs):
'''
Return a printer function
'''
for outputter in STATIC:
if outputter in opts:
if opts[outputter]:
out = outputter
if out.endswith('_out'):
out = out[:-4]
if opts is None:
opts = {}
opts.update(kwargs)
if not 'color' in opts:
opts['color'] = not bool(opts.get('no_color', False))
outputters = salt.loader.outputters(opts)
if not out in outputters:
return outputters['pprint']
return outputters[out]
|
'''
Used to manage the outputter system. This package is the modular system used
for managing outputters.
'''
# Import salt utils
import salt.loader
def display_output(data, out, opts=None):
'''
Print the passed data using the desired output
'''
get_printout(out, opts)(data)
def get_printout(out, opts=None, **kwargs):
'''
Return a printer function
'''
if out.endswith('_out'):
out = out[:-4]
if opts is None:
opts = {}
opts.update(kwargs)
if not 'color' in opts:
opts['color'] = not bool(opts.get('no_color', False))
outputters = salt.loader.outputters(opts)
if not out in outputters:
return outputters['pprint']
return outputters[out]
|
Change files to be Pintfiles so as not to conflict with Grunt
|
"use strict"
var _ = require('underscore'),
fs = require('fs'),
sys = require('sys'),
exec = require('child_process').exec,
program = require('commander'),
path = require('path');
var pintPath = path.join(__dirname, '..'),
targetPath = process.cwd()
// CLI
program.version('0.0.1')
.parse(process.argv);
// Exec new Gruntfile
var execGrunt = function () {
var pintConfig = require(path.join(process.cwd(), 'Pint.js'));
var gruntfileTemplate = fs.readFileSync(path.join(pintPath, 'lib/templates/Gruntfile.tmpl'), 'utf8');
// Stringify config but remove open and closing braces
var config=JSON.stringify(pintConfig.build.config);
config = config.substring(1, config.length - 1)
fs.writeFileSync(path.join(targetPath, "Pintfile.js"), _.template(gruntfileTemplate)({
gruntTasks : config
}))
exec("grunt --gruntfile Pintfile.js", function(err, stdout) {
sys.puts(stdout.trim());
exec("rm -rf Pintfile.js", function(err, stdout) {
sys.puts(stdout.trim());
});
});
};
exports.drink = execGrunt;
|
"use strict"
var _ = require('underscore'),
fs = require('fs'),
sys = require('sys'),
exec = require('child_process').exec,
program = require('commander');
var path = require('path'),
fs = require('fs'),
lib = path.join(path.dirname(fs.realpathSync(__filename)), '../lib');
// CLI
program.version('0.0.1')
.parse(process.argv);
// Exec new Gruntfile
var execGrunt = function () {
var pintConfig = require(path.join(process.cwd(), 'Pint.js'));
var gruntfileTemplate = fs.readFileSync(path.join(lib, 'templates/Gruntfile.tmpl'), 'utf8');
// Stringify config but remove open and closing braces
var config=JSON.stringify(pintConfig.build.config);
config = config.substring(1, config.length - 1)
fs.writeFileSync("./Gruntfile.js", _.template(gruntfileTemplate)({
gruntTasks : config
}))
exec("grunt", function(err, stdout) {
sys.puts(stdout.trim());
exec("rm -rf Gruntfile.js", function(err, stdout) {
sys.puts(stdout.trim());
});
});
};
exports.drink = execGrunt;
|
Use unittest2 when python version is less than 2.7.
In Google App Engine (GAE) you have to use unittest2 if the unit test code uses any of
the capabilities added in Python 2.7 to the unittest module.
|
import sys
if sys.version_info < (2, 7):
import unittest2 as unittest
else:
import unittest as unittest
import os
import battlenet
PUBLIC_KEY = os.environ.get('BNET_PUBLIC_KEY')
PRIVATE_KEY = os.environ.get('BNET_PRIVATE_KEY')
class ExceptionTest(unittest.TestCase):
def setUp(self):
self.connection = battlenet.Connection(public_key=PUBLIC_KEY, private_key=PRIVATE_KEY)
def test_character_not_found(self):
self.assertRaises(battlenet.CharacterNotFound,
lambda: self.connection.get_character(battlenet.UNITED_STATES, 'Fake Realm', 'Fake Character'))
def test_guild_not_found(self):
self.assertRaises(battlenet.GuildNotFound,
lambda: self.connection.get_guild(battlenet.UNITED_STATES, 'Fake Realm', 'Fake Guild'))
def test_realm_not_found(self):
self.assertRaises(battlenet.RealmNotFound, lambda: self.connection.get_realm(battlenet.EUROPE, 'Fake Realm'))
def tearDown(self):
del self.connection
if __name__ == '__main__':
unittest.main()
|
import unittest
import os
import battlenet
PUBLIC_KEY = os.environ.get('BNET_PUBLIC_KEY')
PRIVATE_KEY = os.environ.get('BNET_PRIVATE_KEY')
class ExceptionTest(unittest.TestCase):
def setUp(self):
self.connection = battlenet.Connection(public_key=PUBLIC_KEY, private_key=PRIVATE_KEY)
def test_character_not_found(self):
self.assertRaises(battlenet.CharacterNotFound,
lambda: self.connection.get_character(battlenet.UNITED_STATES, 'Fake Realm', 'Fake Character'))
def test_guild_not_found(self):
self.assertRaises(battlenet.GuildNotFound,
lambda: self.connection.get_guild(battlenet.UNITED_STATES, 'Fake Realm', 'Fake Guild'))
def test_realm_not_found(self):
self.assertRaises(battlenet.RealmNotFound, lambda: self.connection.get_realm(battlenet.EUROPE, 'Fake Realm'))
def tearDown(self):
del self.connection
if __name__ == '__main__':
unittest.main()
|
Fix loading more posts on UserActivity tab
|
Hummingbird.DashboardController = Ember.Controller.extend({
currentTab: "dashboard",
highlightDasboard: function() { return this.get('currentTab') == "dashboard" }.property('currentTab'),
highlightPosts: function() { return this.get('currentTab') == "posts" }.property('currentTab'),
highlightMedia: function() { return this.get('currentTab') == "media" }.property('currentTab'),
actualContent: function(){
var tab = this.get('currentTab');
if(tab == "posts") return this.get('postsOnly');
if(tab == "media") return this.get('mediaOnly');
return this.get('content');
}.property('currentTab', 'content'),
postsOnly: Em.computed.filter('content', function(item){
return (item.get('type') == "comment" || item.get('type') == "followed");
}),
mediaOnly: Em.computed.filterBy('content', 'type', "media_story"),
actions: {
setCurrentTab: function(newTab){
this.set('currentTab', newTab);
}
}
});
|
Hummingbird.DashboardController = Ember.Controller.extend({
currentTab: "dashboard",
highlightDasboard: function() { return this.get('currentTab') == "dashboard" }.property('currentTab'),
highlightPosts: function() { return this.get('currentTab') == "posts" }.property('currentTab'),
highlightMedia: function() { return this.get('currentTab') == "media" }.property('currentTab'),
actualContent: function(){
var tab = this.get('currentTab');
if(tab == "posts") return this.get('postsOnly');
if(tab == "media") return this.get('mediaOnly');
return this.get('content');
}.property('currentTab', 'content'),
postsOnly: function(){
return this.get('content').filter(function(item, index, enumr){
return (item.get('type') == "comment" || item.get('type') == "followed");
});
}.property('content'),
mediaOnly: Em.computed.filterBy('content', 'type', "media_story"),
actions: {
setCurrentTab: function(newTab){
this.set('currentTab', newTab);
}
}
});
|
Revert "Use PDO in the local cellid script"
|
<?php
require_once("config.php");
if(!@mysql_connect("$DBIP","$DBUSER","$DBPASS"))
{
echo "Result:4";
die();
}
mysql_select_db("$DBNAME");
if ($_REQUEST["myl"] != "")
{
$temp = split(":", $_REQUEST["myl"]);
$mcc = $temp[0];
$mnc = $temp[1];
$lac = $temp[2];
$cid = $temp[3];
} else
{
$mcc = $_REQUEST["mcc"];
$mnc = $_REQUEST["mnc"];
$lac = $_REQUEST["lac"];
$cid = $_REQUEST["cid"];
}
if ( $mcc == "" || $mnc == "" || $lac == "" || $cid == "" )
{
echo "Result:7"; // CellID not specified
die();
}
$result=mysql_query("Select latitude,longitude FROM cellids WHERE cellid='$mcc-$mnc-$lac-$cid' order by dateadded desc limit 0,1");
if ( $row=mysql_fetch_array($result) )
echo "Result:0|".$row['latitude']."|".$row['longitude'];
else
echo "Result:6"; // No lat/long for specified CellID
die();
?>
|
<?php
require_once("database.php");
$db = connect_save();
if ($db === null)
{
echo "Result:4";
die();
}
if ($_REQUEST["myl"] != "")
{
$temp = split(":", $_REQUEST["myl"]);
$mcc = $temp[0];
$mnc = $temp[1];
$lac = $temp[2];
$cid = $temp[3];
} else
{
$mcc = $_REQUEST["mcc"];
$mnc = $_REQUEST["mnc"];
$lac = $_REQUEST["lac"];
$cid = $_REQUEST["cid"];
}
if ( $mcc == "" || $mnc == "" || $lac == "" || $cid == "" )
{
echo "Result:7"; // CellID not specified
die();
}
$result = $db->exec_sql("SELECT Latitude, Longitude FROM cellids WHERE CellID=? ORDER BY DateAdded DESC LIMIT 0,1", "$mcc-$mnc-$lac-$cid");
if ( $row=$result->fetch() )
echo "Result:0|$row[Latitude]|$row[Longitude]";
else
echo "Result:6"; // No lat/long for specified CellID
die();
?>
|
[FIX] Change product types are really dangerous!!!
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2012 OpenERP - Team de Localización Argentina.
# https://launchpad.net/~openerp-l10n-ar-localization
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import test
import afip
import invoice
import config
import partner
import account
import country
import report
import currency
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2012 OpenERP - Team de Localización Argentina.
# https://launchpad.net/~openerp-l10n-ar-localization
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import test
import afip
import invoice
import config
import partner
import account
import country
import report
import currency
import product
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
Fix error on loading other languages
|
# Copyright (C) 2016 Adam Schubert <adam.schubert@sg1-game.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import locale
import gettext
import os
import logging
class GetText(object):
"""
Handles language translations and Initializes global _() function
"""
def __init__(self):
"""Initialize GetText
"""
code, encoding = locale.getlocale()
try:
filename = os.path.join(os.path.abspath(__file__),
'locale', '{}.mo'.format(code))
trans = gettext.GNUTranslations(open(filename, "rb"))
logging.debug('{} Loaded'.format(filename))
except IOError:
trans = gettext.NullTranslations()
trans.install()
|
# Copyright (C) 2016 Adam Schubert <adam.schubert@sg1-game.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import locale
import gettext
import os
import logging
class GetText(object):
"""
Handles language translations and Initializes global _() function
"""
def __init__(self):
"""Initialize GetText
"""
code, encoding = locale.getlocale()
try:
filename = os.path.join('locale', '{}.mo'.format(code))
trans = gettext.GNUTranslations(open(filename, "rb"))
logging.debug('{} Loaded'.format(filename))
except IOError:
trans = gettext.NullTranslations()
trans.install()
|
Use initial state exported by reducer.
|
import expect from 'expect';
import sessionReducer, { initialState } from '../../js/reducers/sessionReducer';
import * as AppConstants from '../../js/constants/AppConstants';
describe('sessionReducer', () => {
it('should return initial state on init', () => {
expect(sessionReducer(undefined, {})).toEqual(initialState);
});
it('should set current user on APP_LOGIN_SUCCESS action', () => {
const user = { id: 42, isAdmin: true };
const expected = { currentUserId: 42, isAdmin: true, isProfileFilled: false};
expect(sessionReducer({}, {type: AppConstants.APP_LOGIN_SUCCESS, user})).toEqual(expected);
});
it('should remove current user on APP_LOGIN_FAILURE action', () => {
const state = { currentUserId: 42, isAdmin: false, teamsLoaded: false, usersLoaded: false };
const expected = { currentUserId: null, isAdmin: false, teamsLoaded: false, usersLoaded: false};
expect(sessionReducer(state, {type: AppConstants.APP_LOGIN_FAILURE})).toEqual(expected);
});
it('should remove current user on APP_LOGOUT action', () => {
const state = { currentUserId: 42, isAdmin: false, teamsLoaded: false, usersLoaded: false };
const expected = { currentUserId: null, isAdmin: false, teamsLoaded: false, usersLoaded: false};
expect(sessionReducer(state, {type: AppConstants.APP_LOGOUT})).toEqual(expected);
});
});
|
import expect from 'expect';
import sessionReducer from '../../js/reducers/sessionReducer';
import * as AppConstants from '../../js/constants/AppConstants';
const initialState = {
activeUserIds: [],
mapMode: AppConstants.MAP_MODE_SHOW,
isSignedIn: true,
currentUserId: null
};
describe('sessionReducer', () => {
it('should return initial state on init', () => {
expect(sessionReducer(undefined, {})).toEqual(initialState);
});
it('should set current user on APP_LOGIN_SUCCESS action', () => {
const user = { id: 42, isAdmin: true };
const expected = { currentUserId: 42, isAdmin: true, isProfileFilled: false};
expect(sessionReducer({}, {type: AppConstants.APP_LOGIN_SUCCESS, user})).toEqual(expected);
});
it('should remove current user on APP_LOGIN_FAILURE action', () => {
const state = { currentUserId: 42, isAdmin: false, teamsLoaded: false, usersLoaded: false };
const expected = { currentUserId: null, isAdmin: false, teamsLoaded: false, usersLoaded: false};
expect(sessionReducer(state, {type: AppConstants.APP_LOGIN_FAILURE})).toEqual(expected);
});
it('should remove current user on APP_LOGOUT action', () => {
const state = { currentUserId: 42, isAdmin: false, teamsLoaded: false, usersLoaded: false };
const expected = { currentUserId: null, isAdmin: false, teamsLoaded: false, usersLoaded: false};
expect(sessionReducer(state, {type: AppConstants.APP_LOGOUT})).toEqual(expected);
});
});
|
Make sure all .h5 files are closed before trying to remove them while testing
|
# re-enable deprecation warnings
import warnings
warnings.simplefilter('default')
from nilmtk import *
from nilmtk.version import version as __version__
from nilmtk.timeframe import TimeFrame
from nilmtk.elecmeter import ElecMeter
from nilmtk.datastore import DataStore, HDFDataStore, CSVDataStore, Key
from nilmtk.metergroup import MeterGroup
from nilmtk.appliance import Appliance
from nilmtk.building import Building
from nilmtk.dataset import DataSet
global_meter_group = MeterGroup()
def teardown_package():
"""Nosetests package teardown function (run when tests are done).
See http://nose.readthedocs.org/en/latest/writing_tests.html#test-packages
Uses git to reset data_dir after tests have run.
"""
from nilmtk.tests.testingtools import data_dir
import subprocess
#Workaround for open .h5 files on Windows
from tables.file import _open_files
_open_files.close_all()
cmd = "git checkout -- {}".format(data_dir())
try:
subprocess.check_output(cmd, shell=True, cwd=data_dir())
except Exception:
print("Failed to run '{}'".format(cmd))
raise
else:
print("Succeeded in running '{}'".format(cmd))
|
# re-enable deprecation warnings
import warnings
warnings.simplefilter('default')
from nilmtk import *
from nilmtk.version import version as __version__
from nilmtk.timeframe import TimeFrame
from nilmtk.elecmeter import ElecMeter
from nilmtk.datastore import DataStore, HDFDataStore, CSVDataStore, Key
from nilmtk.metergroup import MeterGroup
from nilmtk.appliance import Appliance
from nilmtk.building import Building
from nilmtk.dataset import DataSet
global_meter_group = MeterGroup()
def teardown_package():
"""Nosetests package teardown function (run when tests are done).
See http://nose.readthedocs.org/en/latest/writing_tests.html#test-packages
Uses git to reset data_dir after tests have run.
"""
from nilmtk.tests.testingtools import data_dir
import subprocess
cmd = "git checkout -- {}".format(data_dir())
try:
subprocess.check_output(cmd, shell=True, cwd=data_dir())
except Exception:
print("Failed to run '{}'".format(cmd))
raise
else:
print("Succeeded in running '{}'".format(cmd))
|
Fix another py27-ism which Black can't handle
Not sure how I missed this one last time.
|
DEFAULT_NUM_MONTHS = 60
def generate_dates(end_str, months=None):
"""
Given an end date as a string in YYYY-MM form (or the underscore separated
equivalent), return a list of N consecutive months as strings in YYYY-MM-01
form, with that month as the final member
"""
if months is None:
months = DEFAULT_NUM_MONTHS
end_date = parse_date(end_str)
assert months > 0
dates = []
for offset in range(1-months, 1):
date = increment_months(end_date, offset)
dates.append('{:04d}-{:02d}-01'.format(date[0], date[1]))
return dates
def parse_date(date_str):
"""
Given a date string in YYYY-MM form (or the underscore separated
equivalent), return a pair of (year, month) integers
"""
year_str, month_str = date_str.replace('_', '-').split('-')[:2]
assert len(year_str) == 4
assert len(month_str) == 2
return int(year_str), int(month_str)
def increment_months(year_month, months):
"""
Given a pair of (year, month) integers return the (year, month) pair N
months in the future
"""
year, month = year_month
i = (year*12) + (month - 1)
i += months
return int(i/12), (i % 12) + 1
|
DEFAULT_NUM_MONTHS = 60
def generate_dates(end_str, months=None):
"""
Given an end date as a string in YYYY-MM form (or the underscore separated
equivalent), return a list of N consecutive months as strings in YYYY-MM-01
form, with that month as the final member
"""
if months is None:
months = DEFAULT_NUM_MONTHS
end_date = parse_date(end_str)
assert months > 0
dates = []
for offset in range(1-months, 1):
date = increment_months(end_date, offset)
dates.append('{:04d}-{:02d}-01'.format(date[0], date[1]))
return dates
def parse_date(date_str):
"""
Given a date string in YYYY-MM form (or the underscore separated
equivalent), return a pair of (year, month) integers
"""
year_str, month_str = date_str.replace('_', '-').split('-')[:2]
assert len(year_str) == 4
assert len(month_str) == 2
return int(year_str), int(month_str)
def increment_months((year, month), months):
"""
Given a pair of (year, month) integers return the (year, month) pair N
months in the future
"""
i = (year*12) + (month - 1)
i += months
return int(i/12), (i % 12) + 1
|
ADD id must be implement Serializable
|
package at.splendit.example.hibernate.domain;
import java.io.Serializable;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Transient;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
@MappedSuperclass
public abstract class AbstractEntityObject<T extends Serializable> implements Serializable {
protected static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
protected T id;
public T getId() {
return id;
}
public void setId(T id) {
this.id = id;
}
@Override
@Transient
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(17, 37, this, false, AbstractEntityObject.class);
}
@Override
@Transient
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj, false, AbstractEntityObject.class);
}
@Override
@Transient
public String toString() {
return ReflectionToStringBuilder.toString(this, null, false, false, AbstractEntityObject.class);
}
}
|
package at.splendit.example.hibernate.domain;
import java.io.Serializable;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Transient;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
@MappedSuperclass
public abstract class AbstractEntityObject<T> implements Serializable {
protected static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
protected T id;
public T getId() {
return id;
}
public void setId(T id) {
this.id = id;
}
@Override
@Transient
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(17, 37, this, false, AbstractEntityObject.class);
}
@Override
@Transient
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj, false, AbstractEntityObject.class);
}
@Override
@Transient
public String toString() {
return ReflectionToStringBuilder.toString(this, null, false, false, AbstractEntityObject.class);
}
}
|
Change the project name to glue, add the new public download_url
|
"""
Glue
-----
Glue is a simple command line tool to generate CSS sprites.
"""
try:
from setuptools import setup
kw = {'entry_points':
"""[console_scripts]\nglue = glue:main\n""",
'zip_safe': False}
except ImportError:
from distutils.core import setup
kw = {'scripts': ['glue.py']}
setup(
name='glue',
version='0.1.1',
url='https://github.com/jorgebastida/glue',
dowload_url='https://nodeload.github.com/jorgebastida/glue/zipball/master',
license='BSD',
author='Jorge Bastida',
author_email='me@jorgebastida.com',
description='Glue is a simple command line tool to generate CSS sprites.',
long_description=('Glue is a simple command line tool to generate CSS '
'sprites.'),
py_modules=['glue'],
include_package_data=True,
platforms='any',
install_requires=[
'PIL>=1.1.6'
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Utilities'
],
**kw
)
|
"""
Glue
-----
Glue is a simple command line tool to generate CSS sprites.
"""
try:
from setuptools import setup
kw = {'entry_points':
"""[console_scripts]\nglue = glue:main\n""",
'zip_safe': False}
except ImportError:
from distutils.core import setup
kw = {'scripts': ['glue.py']}
setup(
name='Glue',
version='0.1',
url='http://glue.github.com/',
license='BSD',
author='Jorge Bastida',
author_email='me@jorgebastida.com',
description='Glue is a simple command line tool to generate CSS sprites.',
long_description=('Glue is a simple command line tool to generate CSS '
'sprites.'),
py_modules=['glue'],
include_package_data=True,
platforms='any',
install_requires=[
'PIL>=1.1.6'
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Utilities'
],
**kw
)
|
Remove useless conversion in remove row code
|
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.uic import loadUi
class MainWindow(QMainWindow):
def __init__(self, *args):
super(MainWindow, self).__init__(*args)
loadUi("ui_files/main.ui", self)
self.tbAdd.clicked.connect(self.addRow)
self.tbRemove.clicked.connect(self.removeRow)
def addRow(self):
rowPos = self.twSettings.rowCount()
self.twSettings.insertRow(rowPos)
def removeRow(self):
rows = sorted(set(index.row() for index in self.twSettings.selectedIndexes()))
rows.reverse()
for row in rows:
self.twSettings.removeRow(row)
if __name__ == "__main__":
app = QApplication(sys.argv)
mw = MainWindow()
mw.show()
sys.exit(app.exec_())
|
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.uic import loadUi
class MainWindow(QMainWindow):
def __init__(self, *args):
super(MainWindow, self).__init__(*args)
loadUi("ui_files/main.ui", self)
self.tbAdd.clicked.connect(self.addRow)
self.tbRemove.clicked.connect(self.removeRow)
def addRow(self):
rowPos = self.twSettings.rowCount()
self.twSettings.insertRow(rowPos)
def removeRow(self):
rows = sorted(set(index.row() for index in self.twSettings.selectedIndexes()))
rows.reverse()
for row in rows:
self.twSettings.removeRow(int(row))
if __name__ == "__main__":
app = QApplication(sys.argv)
mw = MainWindow()
mw.show()
sys.exit(app.exec_())
|
Make DotDict dict methods return those objects
|
class DotDict(object):
"""
Immutable dict-like objects accessible by dot notation
Used because the amount of configuration access is very high and just using
dots instead of the dict notation feels good.
"""
def __init__(self, data):
self.data = data
def __repr__(self): # pragma: nocover
return '<DotDict {}>'.format(self.data)
def __getattr__(self, key):
if key in ('values', 'keys', 'items'):
# Dict methods, just return and run them.
return getattr(self.data, key)
val = self.data[key]
if isinstance(val, dict):
val = DotDict(val)
return val
def __eq__(self, other):
return self.data == other.data
# So that we can still access as dicts
__getitem__ = __getattr__
def dynamic_load(target):
"""
Dynamically import a class and return it
This is used by the core parts of the main configuration file since
one of the main features is to let the user specify which class to use.
"""
split = target.split('.')
module_name = '.'.join(split[:-1])
class_name = split[-1]
mod = __import__(module_name, fromlist=[class_name])
return getattr(mod, class_name)
|
class DotDict(object):
"""
Immutable dict-like objects accessible by dot notation
Used because the amount of configuration access is very high and just using
dots instead of the dict notation feels good.
"""
def __init__(self, data):
self.data = data
def __repr__(self): # pragma: nocover
return '<DotDict {}>'.format(self.data)
def __getattr__(self, key):
val = self.data[key]
if isinstance(val, dict):
val = DotDict(val)
return val
def values(self):
return self.data.values()
def __eq__(self, other):
return self.data == other.data
# So that we can still access as dicts
__getitem__ = __getattr__
def dynamic_load(target):
"""
Dynamically import a class and return it
This is used by the core parts of the main configuration file since
one of the main features is to let the user specify which class to use.
"""
split = target.split('.')
module_name = '.'.join(split[:-1])
class_name = split[-1]
mod = __import__(module_name, fromlist=[class_name])
return getattr(mod, class_name)
|
Fix compile error due to new forge version
|
package info.u_team.u_team_test.init;
import info.u_team.u_team_test.TestMod;
import net.minecraftforge.event.entity.EntityTravelToDimensionEvent;
import net.minecraftforge.event.entity.player.PlayerEvent.PlayerChangedDimensionEvent;
import net.minecraftforge.event.world.RegisterDimensionsEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus;
@EventBusSubscriber(modid = TestMod.MODID, bus = Bus.FORGE)
public class TestDimensions {
@SubscribeEvent
public static void on(RegisterDimensionsEvent event) {
// Dimension are broken currently
// if (!DimensionManager.getRegistry().containsKey(TestModDimensions.BASIC.getRegistryName())) { // How do we know when
// the dimension needs to be registered??
// DimensionManager.registerDimension(TestModDimensions.BASIC.getRegistryName(), TestModDimensions.BASIC, null, true);
// }
}
@SubscribeEvent
public static void on(EntityTravelToDimensionEvent event) {
System.out.println("START TRAVELING TO " + event.getDimension() + " AS " + event.getEntity());
}
@SubscribeEvent
public static void on(PlayerChangedDimensionEvent event) {
System.out.println("FINISHED TRAVELING TO: " + event.getTo() + " FROM " + event.getFrom() + " AS " + event.getPlayer());
}
}
|
package info.u_team.u_team_test.init;
import info.u_team.u_team_test.TestMod;
import net.minecraftforge.event.entity.EntityTravelToDimensionEvent;
import net.minecraftforge.event.world.RegisterDimensionsEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus;
import net.minecraftforge.fml.common.gameevent.PlayerEvent.PlayerChangedDimensionEvent;
@EventBusSubscriber(modid = TestMod.MODID, bus = Bus.FORGE)
public class TestDimensions {
@SubscribeEvent
public static void on(RegisterDimensionsEvent event) {
// Dimension are broken currently
// if (!DimensionManager.getRegistry().containsKey(TestModDimensions.BASIC.getRegistryName())) { // How do we know when
// the dimension needs to be registered??
// DimensionManager.registerDimension(TestModDimensions.BASIC.getRegistryName(), TestModDimensions.BASIC, null, true);
// }
}
@SubscribeEvent
public static void on(EntityTravelToDimensionEvent event) {
System.out.println("START TRAVELING TO " + event.getDimension() + " AS " + event.getEntity());
}
@SubscribeEvent
public static void on(PlayerChangedDimensionEvent event) {
System.out.println("FINISHED TRAVELING TO: " + event.getTo() + " FROM " + event.getFrom() + " AS " + event.getPlayer());
}
}
|
Fix detection of HEADLESS_ONLY environment variable
|
package integration_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/sclevine/agouti/core"
. "github.com/sclevine/agouti/internal/integration"
"os"
"testing"
)
var (
phantomDriver WebDriver
chromeDriver WebDriver
seleniumDriver WebDriver
headlessOnly = os.Getenv("HEADLESS_ONLY") == "true"
)
func TestIntegration(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Integration Suite")
}
var _ = BeforeSuite(func() {
phantomDriver, _ = PhantomJS()
Expect(phantomDriver.Start()).To(Succeed())
if !headlessOnly {
seleniumDriver, _ = Selenium()
chromeDriver = ChromeDriver()
Expect(seleniumDriver.Start()).To(Succeed())
Expect(chromeDriver.Start()).To(Succeed())
}
Server.Start()
})
var _ = AfterSuite(func() {
Server.Close()
phantomDriver.Stop()
if !headlessOnly {
chromeDriver.Stop()
seleniumDriver.Stop()
}
})
|
package integration_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/sclevine/agouti/core"
. "github.com/sclevine/agouti/internal/integration"
"os"
"testing"
)
var (
phantomDriver WebDriver
chromeDriver WebDriver
seleniumDriver WebDriver
headlessOnly bool
)
func TestIntegration(t *testing.T) {
headlessOnly = os.Getenv("HEADLESS_ONLY") == "true"
RegisterFailHandler(Fail)
RunSpecs(t, "Integration Suite")
}
var _ = BeforeSuite(func() {
phantomDriver, _ = PhantomJS()
Expect(phantomDriver.Start()).To(Succeed())
if !headlessOnly {
seleniumDriver, _ = Selenium()
chromeDriver = ChromeDriver()
Expect(seleniumDriver.Start()).To(Succeed())
Expect(chromeDriver.Start()).To(Succeed())
}
Server.Start()
})
var _ = AfterSuite(func() {
Server.Close()
phantomDriver.Stop()
if !headlessOnly {
chromeDriver.Stop()
seleniumDriver.Stop()
}
})
|
Read credentials from the command directory.
|
#!/usr/bin/env node
'use strict';
/**
* Binary to run the main server.
* (C) 2015 Alex Fernández.
*/
// requires
var stdio = require('stdio');
var Log = require('log');
var reviewServer = require('../lib/reviewServer');
// globals
var log = new Log('info');
var credentials = {};
// init
try
{
credentials = require(process.cwd() + '/credentials.json');
}
catch(exception)
{
log.info('Please enter default values in a file credentials.json in the current directory');
}
var options = stdio.getopt({
token: {key: 't', args: 1, description: 'Consumer token for Trello'},
key: {key: 'k', args: 1, description: 'Key for Trello'},
secret: {key: 's', args: 1, description: 'Secret value to access the server'},
port: {key: 'p', args: 1, description: 'Port to start the server'},
quiet: {key: 'q', description: 'Do not log any messages'},
debug: {key: 'd', description: 'Log debug messages'},
});
credentials.overwriteWith(options);
reviewServer.start(credentials);
|
#!/usr/bin/env node
'use strict';
/**
* Binary to run the main server.
* (C) 2015 Alex Fernández.
*/
// requires
var stdio = require('stdio');
var Log = require('log');
var reviewServer = require('../lib/reviewServer');
// globals
var log = new Log('info');
var credentials = {};
// init
try
{
credentials = require('../credentials.json');
}
catch(exception)
{
log.info('Please enter default values in a file called credentials.json');
}
var options = stdio.getopt({
token: {key: 't', args: 1, description: 'Consumer token for Trello'},
key: {key: 'k', args: 1, description: 'Key for Trello'},
secret: {key: 's', args: 1, description: 'Secret value to access the server'},
port: {key: 'p', args: 1, description: 'Port to start the server'},
quiet: {key: 'q', description: 'Do not log any messages'},
debug: {key: 'd', description: 'Log debug messages'},
});
credentials.overwriteWith(options);
reviewServer.start(credentials);
|
[IMP] payment_redsys: Put real package on pypi
|
# Copyright 2017 Tecnativa - Sergio Teruel
# Copyright 2020 Tecnativa - João Marques
{
"name": "Pasarela de pago Redsys",
"category": "Payment Acquirer",
"summary": "Payment Acquirer: Redsys Implementation",
"version": "14.0.2.0.0",
"author": "Tecnativa," "Odoo Community Association (OCA)",
"website": "https://github.com/OCA/l10n-spain",
"depends": ["payment", "website_sale"],
"external_dependencies": {"python": ["pycrypto"]},
"data": [
"views/redsys.xml",
"views/payment_acquirer.xml",
"views/payment_redsys_templates.xml",
"data/payment_redsys.xml",
],
"license": "AGPL-3",
"installable": True,
}
|
# Copyright 2017 Tecnativa - Sergio Teruel
# Copyright 2020 Tecnativa - João Marques
{
"name": "Pasarela de pago Redsys",
"category": "Payment Acquirer",
"summary": "Payment Acquirer: Redsys Implementation",
"version": "14.0.2.0.0",
"author": "Tecnativa," "Odoo Community Association (OCA)",
"website": "https://github.com/OCA/l10n-spain",
"depends": ["payment", "website_sale"],
"external_dependencies": {"python": ["Crypto.Cipher.DES3"]},
"data": [
"views/redsys.xml",
"views/payment_acquirer.xml",
"views/payment_redsys_templates.xml",
"data/payment_redsys.xml",
],
"license": "AGPL-3",
"installable": True,
}
|
Add an option to handle language: default to en
|
package config
import (
"log"
"os"
"path/filepath"
"code.google.com/p/gcfg"
)
const Version = "0.1a"
const DEFAULT_LANG = "en"
const DEFAULT_NICKNAME = "perpetua"
const DEFAULT_USER = "perpetua"
var BASE_DIR = filepath.Join(os.ExpandEnv("$HOME"), ".perpetua")
var CONFIG_FILE = filepath.Join(BASE_DIR, "perpetua.gcfg")
var DATABASE_FILE = filepath.Join(BASE_DIR, "perpetua.sqlite3")
// Options is used by Gcfg to store data read from CONFIG_FILE.
type Options struct {
Server struct {
Hostname string
Port uint16
UseTLS, SkipVerify bool
}
IRC struct {
Nickname, User string
Channel []string
}
I18N struct {
Lang string
}
}
// Read configuration from default config file specified by
// CONFIG_FILE and set default values for not provided entries.
func (o *Options) Read() {
err := gcfg.ReadFileInto(o, CONFIG_FILE)
if err != nil {
log.Fatal(err)
}
if o.IRC.Nickname == "" {
o.IRC.Nickname = DEFAULT_NICKNAME
}
if o.IRC.User == "" {
o.IRC.User = DEFAULT_USER
}
if o.I18N.Lang == "" {
o.I18N.Lang = DEFAULT_LANG
}
}
|
package config
import (
"log"
"os"
"path/filepath"
"code.google.com/p/gcfg"
)
const Version = "0.1a"
const DEFAULT_NICKNAME = "perpetua"
const DEFAULT_USER = "perpetua"
var BASE_DIR = filepath.Join(os.ExpandEnv("$HOME"), ".perpetua")
var CONFIG_FILE = filepath.Join(BASE_DIR, "perpetua.gcfg")
var DATABASE_FILE = filepath.Join(BASE_DIR, "perpetua.sqlite3")
type Options struct {
Server struct {
Hostname string
Port uint16
UseTLS, SkipVerify bool
}
IRC struct {
Nickname, User string
Channel []string
}
}
func (o *Options) Read() {
err := gcfg.ReadFileInto(o, CONFIG_FILE)
if o.IRC.Nickname == "" {
o.IRC.Nickname = DEFAULT_NICKNAME
}
if o.IRC.User == "" {
o.IRC.User = DEFAULT_USER
}
if err != nil {
log.Fatal(err)
}
}
|
Update 'get_current_usersettings' to catch 'DoesNotExist' error
|
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
def get_usersettings_model():
"""
Returns the ``UserSettings`` model that is active in this project.
"""
from django.db.models import get_model
try:
app_label, model_name = settings.USERSETTINGS_MODEL.split('.')
except ValueError:
raise ImproperlyConfigured('USERSETTINGS_MODEL must be of the '
'form "app_label.model_name"')
usersettings_model = get_model(app_label, model_name)
if usersettings_model is None:
raise ImproperlyConfigured('USERSETTINGS_MODEL refers to model "%s" that has '
'not been installed' % settings.USERSETTINGS_MODEL)
return usersettings_model
def get_current_usersettings():
"""
Returns the current ``UserSettings`` based on
the SITE_ID in the project's settings
"""
USERSETTINGS_MODEL = get_usersettings_model()
try:
current_usersettings = USERSETTINGS_MODEL.objects.get_current()
except USERSETTINGS_MODEL.DoesNotExist:
current_usersettings = None
return current_usersettings
|
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
def get_usersettings_model():
"""
Returns the ``UserSettings`` model that is active in this project.
"""
from django.db.models import get_model
try:
app_label, model_name = settings.USERSETTINGS_MODEL.split('.')
except ValueError:
raise ImproperlyConfigured('USERSETTINGS_MODEL must be of the '
'form "app_label.model_name"')
usersettings_model = get_model(app_label, model_name)
if usersettings_model is None:
raise ImproperlyConfigured('USERSETTINGS_MODEL refers to model "%s" that has '
'not been installed' % settings.USERSETTINGS_MODEL)
return usersettings_model
def get_current_usersettings():
"""
Returns the current ``UserSettings`` based on
the SITE_ID in the project's settings
"""
USERSETTINGS_MODEL = get_usersettings_model()
current_usersettings = USERSETTINGS_MODEL.objects.get_current()
return current_usersettings
|
Use identity as counter id
|
'use strict'
const Store = require('orbit-db-store')
const CounterIndex = require('./CounterIndex')
const Counter = require('crdts/src/G-Counter')
class CounterStore extends Store {
constructor(ipfs, id, dbname, options = {}) {
if(!options.Index) Object.assign(options, { Index: CounterIndex })
super(ipfs, id, dbname, options)
this._type = 'counter'
}
get value() {
return this._index.get().value
}
inc(amount) {
const counter = new Counter(this.identity.publicKey, Object.assign({}, this._index.get()._counters))
counter.increment(amount)
return this._addOperation({
op: 'COUNTER',
key: null,
value: counter.toJSON(),
})
}
}
module.exports = CounterStore
|
'use strict'
const Store = require('orbit-db-store')
const CounterIndex = require('./CounterIndex')
const Counter = require('crdts/src/G-Counter')
class CounterStore extends Store {
constructor(ipfs, id, dbname, options = {}) {
if(!options.Index) Object.assign(options, { Index: CounterIndex })
super(ipfs, id, dbname, options)
this._type = 'counter'
}
get value() {
return this._index.get().value
}
inc(amount) {
const counter = new Counter(this.uid, Object.assign({}, this._index.get()._counters))
counter.increment(amount)
return this._addOperation({
op: 'COUNTER',
key: null,
value: counter.toJSON(),
})
}
}
module.exports = CounterStore
|
Fix data attribute usage for external links
|
$(document).on('click', 'a', function(event) {
var lnk = event.currentTarget;
//for backwards compatibility
var rels = lnk.rel.split(' ');
$.each(rels, function() {
if (this.match(/^popup/)) {
var relProperties = this.split('_');
//$(lnk).addClass('webLinkPopup');
if (relProperties[1] == 'blank') {
window.open(lnk.href, '_blank');
} else {
window.open(lnk.href, '_blank', relProperties[1]);
}
event.preventDefault();
}
});
if ($(lnk).data('kwc-popup')) {
if ($(lnk).data('kwc-popup') == 'blank') {
window.open(lnk.href, '_blank');
} else {
window.open(lnk.href, '_blank', $(lnk).data('kwc-popup'));
}
}
});
|
$(document).on('click', 'a', function(event) {
var lnk = event.currentTarget;
//for backwards compatibility
var rels = lnk.rel.split(' ');
$.each(rels, function() {
if (this.match(/^popup/)) {
var relProperties = this.split('_');
//$(lnk).addClass('webLinkPopup');
if (relProperties[1] == 'blank') {
window.open(lnk.href, '_blank');
} else {
window.open(lnk.href, '_blank', relProperties[1]);
}
event.preventDefault();
}
});
if (lnk.data('kwc-popup')) {
if (lnk.data('kwc-popup') == 'blank') {
window.open(lnk.href, '_blank');
} else {
window.open(lnk.href, '_blank', lnk.data('kwc-popup'));
}
}
});
|
Use packaging instead of a module
|
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
requires = [
'requests',
'rauth'
]
setup(
name='fatsecret',
version='0.2.1',
description='Python wrapper for FatSecret REST API',
url='github.com/walexnelson/pyfatsecret',
license='MIT',
author='Alex Nelson',
author_email='w.alexnelson@gmail.com',
install_requires=requires,
packages=["fatsecret"],
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3'
]
)
|
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
requires = [
'requests',
'rauth'
]
setup(
name='fatsecret',
version='0.2.1',
description='Python wrapper for FatSecret REST API',
url='github.com/walexnelson/pyfatsecret',
license='MIT',
author='Alex Nelson',
author_email='w.alexnelson@gmail.com',
install_requires=requires,
py_modules=("fatsecret",),
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3'
]
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.