text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Refactor run configuration into decorator | angular.module('resourceSolver', ['ui.router'])
.provider('resourceSolver', function ResourceSolver() {
var baseUrl = '';
this.setBaseUrl = function(url) {
baseUrl = url;
};
this.$get = function() {
return {
getBaseUrl: function() {
return baseUrl;
}
};
};
}).config(['$provide', function($provide) {
$provide.decorator("$state", function($delegate, $rootScope) {
$rootScope.$on('$stateChangeStart', function(event, toState, toParams) {
$delegate.next = toState;
$delegate.nextParams = toParams;
});
return $delegate;
});
}])
.constant('rs', function(res) {
function Solver($resource, resourceSolver, $state) {
var baseUrl = resourceSolver.getBaseUrl();
var action = res.action || 'get';
return $resource(baseUrl+res.url, $state.nextParams)[action]().$promise;
};
return ['$resource', 'resourceSolver', '$state', Solver];
});
| angular.module('resourceSolver', [])
.provider('resourceSolver', function ResourceSolver() {
var baseUrl = '';
this.setBaseUrl = function(url) {
baseUrl = url;
};
this.$get = function() {
return {
getBaseUrl: function() {
return baseUrl;
}
};
};
}).run(function($rootScope, $state) {
$rootScope.$on('$stateChangeStart', function(event, state, params) {
$state.next = state;
$state.nextParams = params;
});
})
.constant('rs', function(res) {
function Solver($resource, resourceSolver, $state) {
var baseUrl = resourceSolver.getBaseUrl();
var action = res.action || 'get';
return $resource(baseUrl+res.url, $state.nextParams)[action]().$promise;
};
return ['$resource', 'resourceSolver', '$state', Solver];
});
|
Add a -clean flag to the cmd | package main
import (
// import plugins to ensure they're bound into the executable
_ "github.com/30x/apidApigeeSync"
//_ "github.com/30x/apidVerifyAPIKey"
_ "github.com/30x/apidGatewayDeploy"
// other imports
"github.com/30x/apid"
"github.com/30x/apid/factory"
"flag"
"os"
)
func main() {
configFlag := flag.String("config", "", "path to the yaml config file [./apid_config.yaml]")
cleanFlag := flag.Bool("clean", false, "start clean, deletes all existing data from local_storage_path")
configFile := *configFlag
if configFile != "" {
os.Setenv("APID_CONFIG_FILE", configFile)
}
flag.Parse()
apid.Initialize(factory.DefaultServicesFactory())
log := apid.Log()
config := apid.Config()
if *cleanFlag {
localStorage := config.GetString("local_storage_path")
log.Infof("removing existing data from: %s", localStorage)
err := os.RemoveAll(localStorage)
if err != nil {
log.Panic("Failed to clean data directory: %v", err)
}
}
log.Debug("initializing...")
apid.InitializePlugins()
// start client API listener
log.Debug("listening...")
api := apid.API()
err := api.Listen()
if err != nil {
log.Print(err)
}
}
| package main
import (
// import plugins to ensure they're bound into the executable
_ "github.com/30x/apidApigeeSync"
_ "github.com/30x/apidVerifyAPIKey"
_ "github.com/30x/apidGatewayDeploy"
// other imports
"github.com/30x/apid"
"github.com/30x/apid/factory"
"flag"
"os"
)
func main() {
configFlag := flag.String("config", "", "path to the yaml config file [./apid_config.yaml]")
flag.Parse()
configFile := *configFlag
if configFile != "" {
os.Setenv("APID_CONFIG_FILE", configFile)
}
apid.Initialize(factory.DefaultServicesFactory())
log := apid.Log()
log.Debug("initializing...")
apid.InitializePlugins()
// start client API listener
log.Debug("listening...")
api := apid.API()
err := api.Listen()
if err != nil {
log.Print(err)
}
}
|
Fix some characters messing up the SECRET_KEY | from __future__ import unicode_literals
import os, re
import tenma
from django.conf import settings
from django.core import management
from django.utils.crypto import get_random_string
from shutil import copyfile, move
BASE_DIR = os.path.dirname(tenma.__file__)
class Command(management.BaseCommand):
help = 'Generates a random secret key.'
@staticmethod
def _generate_secret_key():
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_=+'
return get_random_string(50, chars)
def handle(self, *args, **options):
orig = os.path.join(BASE_DIR, 'settings.py')
temp = os.path.join(BASE_DIR, 'temp.py')
copyfile(orig, temp)
with open(temp, 'w') as new_file:
with open(orig) as old_file:
for line in old_file:
secret_key = re.match(r'^SECRET_KEY ?=', line)
if secret_key:
line = "SECRET_KEY = '{0}'".format(Command._generate_secret_key()) + '\n'
new_file.write(line)
new_file.close()
os.remove(orig)
os.rename(temp, orig)
| from __future__ import unicode_literals
import os, re
import tenma
from django.conf import settings
from django.core import management
from django.utils.crypto import get_random_string
from shutil import copyfile, move
BASE_DIR = os.path.dirname(tenma.__file__)
class Command(management.BaseCommand):
help = 'Generates a random secret key.'
@staticmethod
def _generate_secret_key():
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_=+[\{]\{;:,<.>/?'
return get_random_string(50, chars)
def handle(self, *args, **options):
orig = os.path.join(BASE_DIR, 'settings.py')
temp = os.path.join(BASE_DIR, 'temp.py')
copyfile(orig, temp)
with open(temp, 'w') as new_file:
with open(orig) as old_file:
for line in old_file:
secret_key = re.match(r'^SECRET_KEY ?=', line)
if secret_key:
line = "SECRET_KEY = '{0}'".format(Command._generate_secret_key()) + '\n'
new_file.write(line)
new_file.close()
os.remove(orig)
os.rename(temp, orig)
|
Add unit test for edge case that wasn't covered | package stats
import (
"testing"
)
func TestCorrelation(t *testing.T) {
s1 := []float64{1, 2, 3, 4, 5}
s2 := []float64{10, -51.2, 8}
s3 := []float64{1, 2, 3, 5, 6}
s4 := []float64{}
s5 := []float64{0, 0, 0}
a, err := Correlation(s5, s5)
if err != nil {
t.Errorf("Should not have returned an error")
}
if a != 0 {
t.Errorf("Should have returned 0")
}
_, err = Correlation(s1, s2)
if err == nil {
t.Errorf("Mismatched slice lengths should have returned an error")
}
a, err = Correlation(s1, s3)
if err != nil {
t.Errorf("Should not have returned an error")
}
if a != 0.9912407071619302 {
t.Errorf("Correlation %v != %v", a, 0.9912407071619302)
}
_, err = Correlation(s1, s4)
if err == nil {
t.Errorf("Empty slice should have returned an error")
}
a, err = Pearson(s1, s3)
if err != nil {
t.Errorf("Should not have returned an error")
}
if a != 0.9912407071619302 {
t.Errorf("Correlation %v != %v", a, 0.9912407071619302)
}
}
| package stats
import (
"testing"
)
func TestCorrelation(t *testing.T) {
s1 := []float64{1, 2, 3, 4, 5}
s2 := []float64{10, -51.2, 8}
s3 := []float64{1, 2, 3, 5, 6}
s4 := []float64{}
_, err := Correlation(s1, s2)
if err == nil {
t.Errorf("Mismatched slice lengths should have returned an error")
}
a, err := Correlation(s1, s3)
if err != nil {
t.Errorf("Should not have returned an error")
}
if a != 0.9912407071619302 {
t.Errorf("Correlation %v != %v", a, 0.9912407071619302)
}
_, err = Correlation(s1, s4)
if err == nil {
t.Errorf("Empty slice should have returned an error")
}
}
|
BUG: Fix tests on old MPL
Old MPL do not have function-defined colormaps, so the corresponding
code path cannot be tested. | # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
""" Smoke testing the cm module
"""
from nose import SkipTest
try:
import matplotlib as mp
# Make really sure that we don't try to open an Xserver connection.
mp.use('svg', warn=False)
import pylab as pl
pl.switch_backend('svg')
except ImportError:
raise SkipTest('Could not import matplotlib')
from ..cm import dim_cmap, replace_inside
def test_dim_cmap():
# This is only a smoke test
mp.use('svg', warn=False)
import pylab as pl
dim_cmap(pl.cm.jet)
def test_replace_inside():
# This is only a smoke test
mp.use('svg', warn=False)
import pylab as pl
pl.switch_backend('svg')
replace_inside(pl.cm.jet, pl.cm.hsv, .2, .8)
# We also test with gnuplot, which is defined using function
if hasattr(pl.cm, 'gnuplot'):
# gnuplot is only in recent version of MPL
replace_inside(pl.cm.gnuplot, pl.cm.gnuplot2, .2, .8)
| # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
""" Smoke testing the cm module
"""
from nose import SkipTest
try:
import matplotlib as mp
# Make really sure that we don't try to open an Xserver connection.
mp.use('svg', warn=False)
import pylab as pl
pl.switch_backend('svg')
except ImportError:
raise SkipTest('Could not import matplotlib')
from ..cm import dim_cmap, replace_inside
def test_dim_cmap():
# This is only a smoke test
mp.use('svg', warn=False)
import pylab as pl
dim_cmap(pl.cm.jet)
def test_replace_inside():
# This is only a smoke test
mp.use('svg', warn=False)
import pylab as pl
pl.switch_backend('svg')
replace_inside(pl.cm.jet, pl.cm.hsv, .2, .8)
# We also test with gnuplot, which is defined using function
replace_inside(pl.cm.gnuplot, pl.cm.gnuplot2, .2, .8)
|
Fix method call of sessionService.sessionExists | (function () {
'use strict';
angular
.module('scrum_retroboard')
.controller('UserController', ['$scope', '$http', 'sessionService', 'userService', UserController]);
function UserController($scope, $http, sessionService, userService) {
var userVm = this;
//scope models
userVm.newSession = false;
userVm.username = "";
userVm.sessionId = sessionService.getSessionId();
sessionService
.sessionExists(userVm.sessionId)
.then(function(data) {
userVm.newSession = data;
});
console.log(userVm.newSession);
//scope method assignments
userVm.createAndJoinSession = createAndJoinSession;
userVm.joinExistingSession = joinExistingSession;
//scope method definitions
function createAndJoinSession() {
sessionService.createSession();
userService.addUserToSession(userVm.username, userVm.sessionId);
}
function joinExistingSession() {
userService.addUserToSession(userVm.username, userVm.sessionId);
}
}
})();
| (function () {
'use strict';
angular
.module('scrum_retroboard')
.controller('UserController', ['$scope', '$http', 'sessionService', 'userService', UserController]);
function UserController($scope, $http, sessionService, userService) {
var userVm = this;
//scope models
userVm.newSession = false;
userVm.username = "";
userVm.sessionId = sessionService.getSessionId();
userVm.newSession = sessionService.sessionExists(userVm.sessionId);
console.log(userVm.newSession);
//scope method assignments
userVm.createAndJoinSession = createAndJoinSession;
userVm.joinExistingSession = joinExistingSession;
//scope method definitions
function createAndJoinSession() {
sessionService.createSession();
userService.addUserToSession(userVm.username, userVm.sessionId);
}
function joinExistingSession() {
userService.addUserToSession(userVm.username, userVm.sessionId);
}
}
})();
|
Put the `key` on the right element, to shut up React. | import React, { PropTypes } from 'react';
import slug from 'slug';
export default class MapPOILegend extends React.Component {
constructor (props) {
super(props);
}
render () {
let pois = [
{
icon: 'icon_bench',
iconSize: [30, 20],
label: 'benches'
},
{
icon: 'icon_picnic-table',
iconSize: [30, 20],
label: 'picnic tables'
},
{
icon: 'icon_boat-launch',
iconSize: [30, 20],
label: 'boat launch - existing'
},
{
icon: 'icon_boat-launch',
iconSize: [30, 20],
label: 'boat launch - planned'
}
];
return (
<div className='map-poi-legend'>
{ pois.map(poi =>
<div key={ poi.label }>
<svg
width={ poi.iconSize[0] }
height={ poi.iconSize[1] }
className={ slug(poi.label) }
>
<use xlinkHref={ '#' + poi.icon } />
</svg>
<div className='label'>{ poi.label }</div>
</div>
)}
</div>
);
}
}
| import React, { PropTypes } from 'react';
import slug from 'slug';
export default class MapPOILegend extends React.Component {
constructor (props) {
super(props);
}
render () {
let pois = [
{
icon: 'icon_bench',
iconSize: [30, 20],
label: 'benches'
},
{
icon: 'icon_picnic-table',
iconSize: [30, 20],
label: 'picnic tables'
},
{
icon: 'icon_boat-launch',
iconSize: [30, 20],
label: 'boat launch - existing'
},
{
icon: 'icon_boat-launch',
iconSize: [30, 20],
label: 'boat launch - planned'
}
];
return (
<div className='map-poi-legend'>
{ pois.map(poi =>
<div>
<svg
key={ poi.label }
width={ poi.iconSize[0] }
height={ poi.iconSize[1] }
className={ slug(poi.label) }
>
<use xlinkHref={ '#' + poi.icon } />
</svg>
<div className='label'>{ poi.label }</div>
</div>
)}
</div>
);
}
}
|
Clean config and update it form twig call | <?php
namespace HeyDoc;
class Config
{
protected $config;
/**
*
*
* @param array $config The container
*/
public function __construct(array $config)
{
$this->config = new \ArrayObject(array_replace($this->getDefaults(), $config));
}
public function has($key)
{
return $this->config->offsetExists($key);
}
public function get($key)
{
if (! $this->has($key)) {
throw new \RuntimeException(sprintf('%s does not contain value for key "%s"', __CLASS__, $key));
}
return $this->config->offsetGet($key);
}
public function getDefaults()
{
return array(
'theme' => 'default',
'debug' => false,
'title' => 'HeyDoc',
'theme_dirs' => array(),
// 'cache_dir' => getcwd() . '/cache',
);
}
public function __call($name, $arguments)
{
return $this->get($name);
}
}
| <?php
namespace HeyDoc;
class Config
{
protected $config;
/**
*
*
* @param array $config The container
*/
public function __construct(array $config)
{
$this->config = new \ArrayObject(array_replace($this->getDefaults(), $config));
}
public function has($key)
{
return $this->config->offsetExists($key);
}
public function get($key)
{
return $this->config->offsetGet($key);
}
public function getDefaults()
{
return array(
'theme' => 'default',
'debug' => false,
'title' => 'HeyDoc',
'theme_dirs' => array(),
// 'cache_dir' => getcwd() . '/cache',
);
}
}
|
Fix bug in primitive name string put -> insert | package org.spoofax.interpreter.library.ssl;
import io.usethesource.capsule.BinaryRelation;
import org.spoofax.interpreter.core.IContext;
import org.spoofax.interpreter.library.AbstractPrimitive;
import org.spoofax.interpreter.stratego.Strategy;
import org.spoofax.interpreter.terms.IStrategoTerm;
public class SSL_immutable_relation_insert extends AbstractPrimitive {
protected SSL_immutable_relation_insert() {
super("SSL_immutable_relation_insert", 0, 2);
}
@Override
public boolean call(IContext env, Strategy[] sargs, IStrategoTerm[] targs) {
if(!(env.current() instanceof StrategoImmutableRelation)) {
return false;
}
final StrategoImmutableRelation map = (StrategoImmutableRelation) env.current();
final IStrategoTerm key = targs[0];
final IStrategoTerm value = targs[1];
env.setCurrent(new StrategoImmutableRelation(
(BinaryRelation.Immutable<IStrategoTerm, IStrategoTerm>) map.backingRelation.__insert(key, value)));
return true;
}
}
| package org.spoofax.interpreter.library.ssl;
import io.usethesource.capsule.BinaryRelation;
import org.spoofax.interpreter.core.IContext;
import org.spoofax.interpreter.library.AbstractPrimitive;
import org.spoofax.interpreter.stratego.Strategy;
import org.spoofax.interpreter.terms.IStrategoTerm;
public class SSL_immutable_relation_insert extends AbstractPrimitive {
protected SSL_immutable_relation_insert() {
super("SSL_immutable_relation_put", 0, 2);
}
@Override
public boolean call(IContext env, Strategy[] sargs, IStrategoTerm[] targs) {
if(!(env.current() instanceof StrategoImmutableRelation)) {
return false;
}
final StrategoImmutableRelation map = (StrategoImmutableRelation) env.current();
final IStrategoTerm key = targs[0];
final IStrategoTerm value = targs[1];
env.setCurrent(new StrategoImmutableRelation(
(BinaryRelation.Immutable<IStrategoTerm, IStrategoTerm>) map.backingRelation.__insert(key, value)));
return true;
}
}
|
Change to didUpdateAttrs() from observers
Changed to use didUpdateAttrs instead of observers.
Not only is this the standard ember way now, this also prevent firing update() multiple times if multiple changes occur in a single render cycle.
Also added a animate property to allow the user to decide when to animte.
This allows disabling animations on update renders if they don't want a reanimation (like a onClick selection of an element in my case). | /* global Chart */
import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'canvas',
attributeBindings: ['width', 'height'],
didInsertElement() {
this._super(...arguments);
let context = this.get('element');
let data = this.get('data');
let type = this.get('type');
let options = this.get('options');
let chart = new Chart(context, {
type: type,
data: data,
options: options
});
this.set('chart', chart);
},
willDestroyElement() {
this._super(...arguments);
this.get('chart').destroy();
},
didUpdateAttrs() {
this._super(...arguments);
let chart = this.get('chart');
let data = this.get('data');
let options = this.get('options');
let animate = this.get('animate');
chart.config.data = data;
chart.config.options = options;
if (animate) {
chart.update();
} else {
chart.update(0);
}
}
});
| /* global Chart */
import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'canvas',
attributeBindings: ['width', 'height'],
didInsertElement: function(){
var context = this.get('element');
var data = this.get('data');
var type = this.get('type');
var options = this.get('options');
var chart = new Chart(context, {
type: type,
data: data,
options: options
});
this.set('chart', chart);
this.addObserver('data', this, this.updateChart);
this.addObserver('data.[]', this, this.updateChart);
this.addObserver('options', this, this.updateChart);
},
willDestroyElement: function(){
this.get('chart').destroy();
this.removeObserver('data', this, this.updateChart);
this.removeObserver('data.[]', this, this.updateChart);
this.removeObserver('options', this, this.updateChart);
},
updateChart: function(){
var chart = this.get('chart');
var data = this.get('data');
var options = this.get('options');
chart.config.data = data;
chart.config.options = options;
chart.update();
}
});
|
Embed required non python files in packaging : html and js files for report | #!/usr/bin/env python
"""Tuttle"""
import sys
from tuttle import __version__
try:
from setuptools import setup, find_packages
except ImportError:
print("Tuttle needs setuptools in order to build. Install it using"
" your package manager (usually python-setuptools) or via pip (pip"
" install setuptools).")
sys.exit(1)
setup(name='tuttle',
version=__version__,
author='Lexman',
author_email='tuttle@lexman.org',
description='Make for data',
long_description='Reliably create data from source as a team in an industrial environment... A tool for '
'continuous data processing',
platforms=['Linux', 'Windows'],
url='http://tuttle.lexman.org/',
license='MIT',
packages=['tuttle', 'tuttle.report'],
#data_files=[],
scripts=[
'bin/tuttle',
],
include_package_data = True,
package_data = {
'tuttle.report' : ['*.html', 'html_report_assets/*'],
},
) | #!/usr/bin/env python
"""Tuttle"""
import sys
from tuttle import __version__
try:
from setuptools import setup, find_packages
except ImportError:
print("Tuttle needs setuptools in order to build. Install it using"
" your package manager (usually python-setuptools) or via pip (pip"
" install setuptools).")
sys.exit(1)
setup(name='tuttle',
version=__version__,
author='Lexman',
author_email='tuttle@lexman.org',
description='Make for data',
long_description='Reliably create data from source as a team in an industrial environment... A tool for '
'continuous data processing',
platforms=['Linux', 'Windows'],
url='http://tuttle.lexman.org/',
install_requires=['nose'],
license='MIT',
packages=find_packages(),
data_files=[],
scripts=[
'bin/tuttle',
],
package_data={
#'': ['module_utils/*.ps1', 'modules/core/windows/*.ps1', 'modules/extras/windows/*.ps1'],
},
) |
Change comment to indicate choice of alphanum order by uri | """A set of Resource objects used for Capability List
Indexes and ResourceSync Description documents.
Ordinging is currently alphanumeric (using sorted(..)) on the
uri which is the key.
"""
class ResourceSet(dict):
"""Implementation of class to store resources in Capability List
Indexes and ResourceSync Description documents.
Key properties of this class are:
- has add(resource) method
- is iterable and results given in alphanumeric order by resource.uri
"""
def __iter__(self):
"""Iterator over all the resources in this resource_list"""
self._iter_next_list = sorted(self.keys())
self._iter_next_list.reverse()
return(iter(self._iter_next, None))
def _iter_next(self):
if (len(self._iter_next_list)>0):
return(self[self._iter_next_list.pop()])
else:
return(None)
def add(self, resource, replace=False):
"""Add just a single resource"""
uri = resource.uri
if (uri in self and not replace):
raise ResourceSetDupeError("Attempt to add resource already in this set")
self[uri]=resource
class ResourceSetDupeError(Exception):
pass
| """A set of Resource objects used for Capability List
Indexes and ResourceSync Description documents.
FIXME - what should the ordering be?
"""
class ResourceSet(dict):
"""Implementation of class to store resources in Capability List
Indexes and ResourceSync Description documents.
Key properties of this class are:
- has add(resource) method
- is iterable and results given in alphanumeric order by resource.uri
"""
def __iter__(self):
"""Iterator over all the resources in this resource_list"""
self._iter_next_list = sorted(self.keys())
self._iter_next_list.reverse()
return(iter(self._iter_next, None))
def _iter_next(self):
if (len(self._iter_next_list)>0):
return(self[self._iter_next_list.pop()])
else:
return(None)
def add(self, resource, replace=False):
"""Add just a single resource"""
uri = resource.uri
if (uri in self and not replace):
raise ResourceSetDupeError("Attempt to add resource already in this set")
self[uri]=resource
class ResourceSetDupeError(Exception):
pass
|
Fix println statement to write a string | package main
import (
"bytes"
"encoding/json"
"fmt"
"github.com/beard1ess/gauss/parsing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"io/ioutil"
"reflect"
"testing"
)
func TestDiff(t *testing.T) {
var expected, actual parsing.ConsumableDifference
assert := assert.New(t)
require := require.New(t)
testBuffer := bytes.NewBuffer(nil) // A testing writer
diff(
"./tests/one.json",
"./tests/two.json",
"machine",
testBuffer,
)
result, err := ioutil.ReadAll(testBuffer)
require.Nil(err, "The test buffer should be readable")
testData, err := ioutil.ReadFile("./tests/diff.json")
require.Nil(err, "The test diff should be readable.")
json.Unmarshal(testData, &expected)
require.Nil(err, "The test data should be unmarshaled without error.")
temp, _ := json.Marshal(expected)
fmt.Println(string(temp))
json.Unmarshal(result, &actual)
assert.Nil(err, "The result should be unmarshaled without error.")
assert.Equal(
reflect.DeepEqual(expected, actual),
true,
"The diff of one.json and two.json should equal the test diff.",
)
}
| package main
import (
"bytes"
"encoding/json"
"fmt"
"github.com/beard1ess/gauss/parsing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"io/ioutil"
"reflect"
"testing"
)
func TestDiff(t *testing.T) {
var expected, actual parsing.ConsumableDifference
assert := assert.New(t)
require := require.New(t)
testBuffer := bytes.NewBuffer(nil) // A testing writer
diff(
"./tests/one.json",
"./tests/two.json",
"machine",
testBuffer,
)
result, err := ioutil.ReadAll(testBuffer)
require.Nil(err, "The test buffer should be readable")
testData, err := ioutil.ReadFile("./tests/diff.json")
require.Nil(err, "The test diff should be readable.")
json.Unmarshal(testData, &expected)
require.Nil(err, "The test data should be unmarshaled without error.")
temp, _ := json.Marshal(expected)
fmt.Println(temp)
json.Unmarshal(result, &actual)
assert.Nil(err, "The result should be unmarshaled without error.")
assert.Equal(
reflect.DeepEqual(expected, actual),
true,
"The diff of one.json and two.json should equal the test diff.",
)
}
|
Add '--quiet' option for standalone usage
What
===
Add '--quiet' option for standalone usage. When provided the logger will
be turned off resulting in no information writing to stderr.
Why
===
When using standalone with IDEs like vim and plugins like vim-lsc the
stderr of the command will be outputted into the terminal. This tool is
pretty noisy and writes a lot of information which is great for
development of the tool but not when using it day-to-day. | package org.javacs;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.javacs.lsp.*;
public class Main {
private static final Logger LOG = Logger.getLogger("main");
public static void setRootFormat() {
var root = Logger.getLogger("");
for (var h : root.getHandlers()) h.setFormatter(new LogFormat());
}
private JavaLanguageServer createServer(LanguageClient client) {
return new JavaLanguageServer(client);
}
public static void main(String[] args) {
boolean quiet = Arrays.stream(args).anyMatch("--quiet"::equals);
if (quiet) {
LOG.setLevel(Level.OFF);
}
try {
// Logger.getLogger("").addHandler(new FileHandler("javacs.%u.log", false));
setRootFormat();
LSP.connect(JavaLanguageServer::new, System.in, System.out);
} catch (Throwable t) {
LOG.log(Level.SEVERE, t.getMessage(), t);
System.exit(1);
}
}
}
| package org.javacs;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.javacs.lsp.*;
public class Main {
private static final Logger LOG = Logger.getLogger("main");
public static void setRootFormat() {
var root = Logger.getLogger("");
for (var h : root.getHandlers()) h.setFormatter(new LogFormat());
}
private JavaLanguageServer createServer(LanguageClient client) {
return new JavaLanguageServer(client);
}
public static void main(String[] args) {
try {
// Logger.getLogger("").addHandler(new FileHandler("javacs.%u.log", false));
setRootFormat();
LSP.connect(JavaLanguageServer::new, System.in, System.out);
} catch (Throwable t) {
LOG.log(Level.SEVERE, t.getMessage(), t);
System.exit(1);
}
}
}
|
Change error message of the weight validator. | # -*- coding: utf-8 -*-
from schematics.exceptions import ConversionError, ValidationError
def validate(schema, data):
try:
schema.import_data(data)
schema.validate()
except (ConversionError, ValidationError) as e:
raise InvalidInputError(details=e.messages)
def weight_validator(value):
if abs(value.as_tuple().exponent) > 1:
raise ValidationError('Only one decimal point is allowed.')
return value
class DomainError(Exception):
def __init__(self, message=None, details=None):
if message: self.message = message
if details: self.details = details
class EntityNotFoundError(DomainError):
"""Raised when an entity does not exist."""
message = 'Entity does not exist.'
class InvalidInputError(DomainError):
"""Raised when input data is invalid."""
message = 'Input data is invalid.'
| # -*- coding: utf-8 -*-
from schematics.exceptions import ConversionError, ValidationError
def validate(schema, data):
try:
schema.import_data(data)
schema.validate()
except (ConversionError, ValidationError) as e:
raise InvalidInputError(details=e.messages)
def weight_validator(value):
if abs(value.as_tuple().exponent) > 1:
raise ValidationError('More than one decimal exponent not allowed')
return value
class DomainError(Exception):
def __init__(self, message=None, details=None):
if message: self.message = message
if details: self.details = details
class EntityNotFoundError(DomainError):
"""Raised when an entity does not exist."""
message = 'Entity does not exist.'
class InvalidInputError(DomainError):
"""Raised when input data is invalid."""
message = 'Input data is invalid.'
|
Add method to find first by parameter stable id | /*******************************************************************************
* Copyright © 2019 EMBL - European Bioinformatics Institute
* <p/>
* 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
* <p/>
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License.
******************************************************************************/
package org.mousephenotype.cda.db.repositories;
import org.mousephenotype.cda.db.pojo.Parameter;
import org.springframework.data.repository.CrudRepository;
public interface ParameterRepository extends CrudRepository<Parameter, Long> {
Parameter getByStableId(String stableId);
Parameter getFirstByStableId(String stableId);
} | /*******************************************************************************
* Copyright © 2019 EMBL - European Bioinformatics Institute
* <p/>
* 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
* <p/>
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License.
******************************************************************************/
package org.mousephenotype.cda.db.repositories;
import org.mousephenotype.cda.db.pojo.Parameter;
import org.springframework.data.repository.CrudRepository;
public interface ParameterRepository extends CrudRepository<Parameter, Long> {
Parameter getByStableId(String stableId);
} |
Fix a problem that lister cannot get resource correctly | package io.kubernetes.client.informer.cache;
import com.google.common.base.Strings;
import java.util.List;
/** Lister interface is used to list cached items from a running informer. */
public class Lister<ApiType> {
private String namespace;
private String indexName;
private Indexer<ApiType> indexer;
public Lister(Indexer<ApiType> indexer) {
this(indexer, null, Cache.NAMESPACE_INDEX);
}
public Lister(Indexer<ApiType> indexer, String namespace) {
this(indexer, namespace, Cache.NAMESPACE_INDEX);
}
public Lister(Indexer<ApiType> indexer, String namespace, String indexName) {
this.indexer = indexer;
this.namespace = namespace;
this.indexName = indexName;
}
public List<ApiType> list() {
if (Strings.isNullOrEmpty(namespace)) {
return indexer.list();
} else {
return indexer.byIndex(this.indexName, namespace);
}
}
public ApiType get(String name) {
String key = name;
if (!Strings.isNullOrEmpty(namespace)) {
key = namespace + "/" + name;
}
return indexer.getByKey(key);
}
public Lister<ApiType> namespace(String namespace) {
return new Lister<ApiType>(this.indexer, namespace, Cache.NAMESPACE_INDEX);
}
}
| package io.kubernetes.client.informer.cache;
import com.google.common.base.Strings;
import java.util.List;
/** Lister interface is used to list cached items from a running informer. */
public class Lister<ApiType> {
private String namespace;
private String indexName;
private Indexer<ApiType> indexer;
public Lister(Indexer<ApiType> indexer) {
this(indexer, null, Cache.NAMESPACE_INDEX);
}
public Lister(Indexer<ApiType> indexer, String namespace) {
this(indexer, namespace, Cache.NAMESPACE_INDEX);
}
public Lister(Indexer<ApiType> indexer, String namespace, String indexName) {
this.indexer = indexer;
this.namespace = namespace;
this.indexName = indexName;
}
public List<ApiType> list() {
if (Strings.isNullOrEmpty(namespace)) {
return indexer.list();
} else {
return indexer.byIndex(this.indexName, namespace);
}
}
public ApiType get(String name) {
String key = name;
if (Strings.isNullOrEmpty(namespace)) {
key = namespace + "/" + name;
}
return indexer.getByKey(key);
}
public Lister<ApiType> namespace(String namespace) {
return new Lister<ApiType>(this.indexer, namespace, Cache.NAMESPACE_INDEX);
}
}
|
Update function to get player stats using base_url | import json
import csv
import requests
from requests.auth import HTTPBasicAuth
import secret
base_url = 'https://www.mysportsfeeds.com/api/feed/pull/nfl/2016-2017-regular/'
def main():
division_standings()
playoff_standings()
playoff_standings()
player_stats()
points_for()
tiebreaker()
player_score()
# Get Division Standings for each team
def division_standings():
pass
# Get Playoff Standings for each team (need number 5 & 6 in each conference)
def playoff_standings():
pass
# Get individual statistics for each category
def player_stats():
url = base_url + 'cumulative_player_stats.json?playerstats=Yds,Sacks,Int'
response = requests.get((url),
auth=HTTPBasicAuth(secret.msf_username, secret.msf_pw))
all_stats = response.json()
stats = all_stats["cumulativeplayerstats"]["playerstatsentry"]
# Get points for for the number one team in each conference:
def points_for():
pass
# Get the tiebreaker information
def tiebreaker():
pass
# Calculate the player scores
def player_score():
pass
if __name__ == '__main__':
main()
| import json
import csv
import requests
import secret
base_url = https://www.mysportsfeeds.com/api/feed/pull/nfl/2016-2017-regular/
def main():
division_standings()
playoff_standings()
playoff_standings()
player_stats()
points_for()
tiebreaker()
player_score()
# Get Division Standings for each team
def division_standings():
pass
# Get Playoff Standings for each team (need number 5 & 6 in each conference)
def playoff_standings():
pass
# Get individual statistics for each category
def player_stats():
response = requests.get('base_url/cumulative_player_stats.json',
auth=HTTPBasicAuth(secret.msf_username, secret.msf_pw))
all_stats = response.json()
stats = all_stats["cumulativeplayerstats"]["playerstatsentry"]
# Get points for for the number one team in each conference:
def points_for():
pass
# Get the tiebreaker information
def tiebreaker():
pass
# Calculate the player scores
def player_score():
pass
if __name__ == '__main__':
main()
|
Use Opcodes.ASM7_EXPERIMENTAL if system property spotbugs.experimental=true | /*
* FindBugs - Find Bugs in Java programs
* Copyright (C) 2003-2008 University of Maryland
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.umd.cs.findbugs.classfile.engine.asm;
import org.objectweb.asm.Opcodes;
/**
* @author pugh
*/
public class FindBugsASM {
private static final boolean USE_EXPERIMENTAL = Boolean.parseBoolean(System.getProperty("spotbugs.experimental"));
public static final int ASM_VERSION = USE_EXPERIMENTAL ? Opcodes.ASM7_EXPERIMENTAL : Opcodes.ASM6;
}
| /*
* FindBugs - Find Bugs in Java programs
* Copyright (C) 2003-2008 University of Maryland
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.umd.cs.findbugs.classfile.engine.asm;
import org.objectweb.asm.Opcodes;
/**
* @author pugh
*/
public class FindBugsASM {
public static final int ASM_VERSION = Opcodes.ASM7_EXPERIMENTAL;
}
|
Make create_tokenizer work with Japanese | # encoding: utf8
from __future__ import unicode_literals, print_function
from os import path
from ..language import Language, BaseDefaults
from ..tokenizer import Tokenizer
from ..attrs import LANG
from ..tokens import Doc
from .language_data import *
class JapaneseTokenizer(object):
def __init__(self, cls, nlp=None):
self.vocab = nlp.vocab if nlp is not None else cls.create_vocab(nlp)
try:
from janome.tokenizer import Tokenizer
except ImportError:
raise ImportError("The Japanese tokenizer requires the Janome library: "
"https://github.com/mocobeta/janome")
self.tokenizer = Tokenizer()
def __call__(self, text):
words = [x.surface for x in self.tokenizer.tokenize(text)]
return Doc(self.vocab, words=words, spaces=[False]*len(words))
class JapaneseDefaults(BaseDefaults):
@classmethod
def create_tokenizer(cls, nlp=None):
return JapaneseTokenizer(cls, nlp)
class Japanese(Language):
lang = 'ja'
Defaults = JapaneseDefaults
def make_doc(self, text):
words = self.tokenizer(text)
return Doc(self.vocab, words=words, spaces=[False]*len(words))
| # encoding: utf8
from __future__ import unicode_literals, print_function
from os import path
from ..language import Language
from ..attrs import LANG
from ..tokens import Doc
from .language_data import *
class Japanese(Language):
lang = 'ja'
def make_doc(self, text):
try:
from janome.tokenizer import Tokenizer
except ImportError:
raise ImportError("The Japanese tokenizer requires the Janome library: "
"https://github.com/mocobeta/janome")
words = [x.surface for x in Tokenizer().tokenize(text)]
return Doc(self.vocab, words=words, spaces=[False]*len(words))
|
Fix migration to run on mysql 5.6 version | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateRolesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('slug')->unique();
$table->text('permissions');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('roles');
}
}
| <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateRolesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('slug')->unique();
$table->jsonb('permissions');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('roles');
}
}
|
Add sleep in custom action | const Promise = require('bluebird');
const ld = require('lodash');
const moment = require('moment');
const setMetadata = require('../utils/updateMetadata.js');
/**
* Adds metadata from billing into usermix
* @param {String} username
* @return {Promise}
*/
module.exports = function mixPlan(username, audience) {
const { amqp, config } = this;
const { payments } = config;
const route = [payments.prefix, payments.routes.planGet].join('.');
const id = 'free';
// make sure that ms-payments is launched before
return Promise
.delay(10000)
.then(() => {
return amqp
.publishAndWait(route, id, { timeout: 5000 })
.bind(this)
.then(function mix(plan) {
const subscription = ld.findWhere(plan.subs, { name: id });
const nextCycle = moment().add(1, 'month').format();
const update = {
username,
audience,
metadata: {
'$set': {
plan: id,
nextCycle,
models: subscription.models,
modelPrice: subscription.price,
},
},
};
return setMetadata.call(this, update);
});
});
};
| const ld = require('lodash');
const moment = require('moment');
const setMetadata = require('../utils/updateMetadata.js');
/**
* Adds metadata from billing into usermix
* @param {String} username
* @return {Promise}
*/
module.exports = function mixPlan(username, audience) {
const { amqp, config } = this;
const { payments } = config;
const route = [payments.prefix, payments.routes.planGet].join('.');
const id = 'free';
return amqp
.publishAndWait(route, id, { timeout: 5000 })
.bind(this)
.then(function mix(plan) {
const subscription = ld.findWhere(plan.subs, { name: id });
const nextCycle = moment().add(1, 'month').format();
const update = {
username,
audience,
metadata: {
'$set': {
plan: id,
nextCycle,
models: subscription.models,
modelPrice: subscription.price,
},
},
};
return setMetadata.call(this, update);
});
};
|
Use sha256 instead of sha1 to fix lint | package forgotpwdemail
import (
"crypto/sha256"
"fmt"
"io"
"time"
"github.com/skygeario/skygear-server/pkg/auth/dependency/userprofile"
"github.com/skygeario/skygear-server/pkg/core/auth/authinfo"
)
type CodeGenerator struct {
MasterKey string
}
func (c *CodeGenerator) Generate(
authInfo authinfo.AuthInfo,
userProfile userprofile.UserProfile,
hashedPassword []byte,
expireAt time.Time,
) string {
h := sha256.New()
io.WriteString(h, c.MasterKey)
io.WriteString(h, authInfo.ID)
if email, ok := userProfile.Data["email"].(string); ok {
io.WriteString(h, email)
}
io.WriteString(h, expireAt.Format(time.RFC3339))
if len(hashedPassword) > 0 {
h.Write(hashedPassword)
}
if authInfo.LastLoginAt != nil && !authInfo.LastLoginAt.IsZero() {
io.WriteString(h, authInfo.LastLoginAt.Format(time.RFC3339))
}
bs := h.Sum(nil)
return fmt.Sprintf("%x", bs)[0:8]
}
| package forgotpwdemail
import (
"crypto/sha1"
"fmt"
"io"
"time"
"github.com/skygeario/skygear-server/pkg/auth/dependency/userprofile"
"github.com/skygeario/skygear-server/pkg/core/auth/authinfo"
)
type CodeGenerator struct {
MasterKey string
}
func (c *CodeGenerator) Generate(
authInfo authinfo.AuthInfo,
userProfile userprofile.UserProfile,
hashedPassword []byte,
expireAt time.Time,
) string {
h := sha1.New()
io.WriteString(h, c.MasterKey)
io.WriteString(h, authInfo.ID)
if email, ok := userProfile.Data["email"].(string); ok {
io.WriteString(h, email)
}
io.WriteString(h, expireAt.Format(time.RFC3339))
if len(hashedPassword) > 0 {
h.Write(hashedPassword)
}
if authInfo.LastLoginAt != nil && !authInfo.LastLoginAt.IsZero() {
io.WriteString(h, authInfo.LastLoginAt.Format(time.RFC3339))
}
bs := h.Sum(nil)
return fmt.Sprintf("%x", bs)[0:8]
}
|
Add backwards compatibility for Node.js 0.10 | var banner = require('./');
let chai = require('chai');
let expect = chai.expect;
describe('banner', () => {
let filepath = 'test-target.js';
context('without options (using defaults)', () => {
let expectation = `/*!
* add-banner <https://github.com/jonschlinkert/add-banner>
*
* Copyright (c) 2018 Jon Schlinkert, contributors.
* Licensed under the MIT license.
*/
`;
it('expected to populate banner', () => {
expect(banner(filepath)).to.eql(expectation);
});
});
context('with specific options', () => {
let options = {
name: 'addbanner',
author: 'Jon Schlinkert (https://github.com/jonschlinkert)',
homepage: 'https://github.com/jonschlinkert/add-banner',
banner: 'banner.tmpl',
year: '2017',
license: 'GPL-3'
};
let expectation = `/*!
* addbanner <https://github.com/jonschlinkert/add-banner>
*
* Copyright (c) 2017 Jon Schlinkert, contributors.
* Licensed under the GPL-3 license.
*/
`;
it('expected to populate banner', () => {
expect(banner(filepath, options)).to.eql(expectation);
});
});
});
| var banner = require('./');
let chai = require('chai');
let expect = chai.expect;
describe('banner', () => {
const FILEPATH = 'test-target.js';
context('without options (using defaults)', () => {
let expectation = `/*!
* add-banner <https://github.com/jonschlinkert/add-banner>
*
* Copyright (c) 2018 Jon Schlinkert, contributors.
* Licensed under the MIT license.
*/
`;
it('expected to populate banner', () => {
expect(banner(FILEPATH)).to.eql(expectation);
});
});
context('with specific options', () => {
let options = {
name: 'addbanner',
author: 'Jon Schlinkert (https://github.com/jonschlinkert)',
homepage: 'https://github.com/jonschlinkert/add-banner',
banner: 'banner.tmpl',
year: '2017',
license: 'GPL-3'
};
let expectation = `/*!
* addbanner <https://github.com/jonschlinkert/add-banner>
*
* Copyright (c) 2017 Jon Schlinkert, contributors.
* Licensed under the GPL-3 license.
*/
`;
it('expected to populate banner', () => {
expect(banner(FILEPATH, options)).to.eql(expectation);
});
});
});
|
Use constant resource to be replaced on reconnect
Network failures may leave the "ghost" bot in the MUC, and unless
it receives a MUC stanza while a replacement is offline, it may
hang in the room forever. Messages are sent to the new resource in
that case.
https://xmpp.org/extensions/xep-0045.html#impl-service-ghosts | #!/usr/bin/env python2.7
# coding: utf-8
import inspect
import logging
logging.basicConfig(level=logging.DEBUG)
import os
import time
import uuid
from comicsbot import ComicsBot
from dokuwiki import DokuWiki
from roomlogger import RoomLogger
execfile("config.py")
w = DokuWiki()
if w.dokuwiki.login(config["dokuwiki"]["username"],
config["dokuwiki"]["password"]):
welcome_message = "Hello! I've connected to wiki %s version %s, " \
"xmlrpc %s" % (w.dokuwiki.getTitle(), w.dokuwiki.getVersion(),
w.dokuwiki.getXMLRPCAPIVersion())
else:
welcome_message = "Hi! I cannot authorize to the wiki."
w = None
room_logger = RoomLogger(config["jabber"]["logdir"])
bot = ComicsBot(config["jabber"]["username"],
config["jabber"]["password"], wiki=w,
room_logger=room_logger, res="ReplaceMe",
debug=True, # log XMPP messages
markov_file=os.path.join(config["jabber"]["logdir"], "markov.json"))
bot.join_room(config["jabber"]["room"], config["jabber"]["nick"])
time.sleep(1)
#bot.send(config["jabber"]["room"], welcome_message, message_type="groupchat")
bot.serve_forever()
| #!/usr/bin/env python2.7
# coding: utf-8
import inspect
import logging
logging.basicConfig(level=logging.DEBUG)
import os
import time
import uuid
from comicsbot import ComicsBot
from dokuwiki import DokuWiki
from roomlogger import RoomLogger
execfile("config.py")
w = DokuWiki()
if w.dokuwiki.login(config["dokuwiki"]["username"],
config["dokuwiki"]["password"]):
welcome_message = "Hello! I've connected to wiki %s version %s, " \
"xmlrpc %s" % (w.dokuwiki.getTitle(), w.dokuwiki.getVersion(),
w.dokuwiki.getXMLRPCAPIVersion())
else:
welcome_message = "Hi! I cannot authorize to the wiki."
w = None
room_logger = RoomLogger(config["jabber"]["logdir"])
bot = ComicsBot(config["jabber"]["username"],
config["jabber"]["password"], wiki=w,
room_logger=room_logger, res=uuid.uuid1(),
debug=True, # log XMPP messages
markov_file=os.path.join(config["jabber"]["logdir"], "markov.json"))
bot.join_room(config["jabber"]["room"], config["jabber"]["nick"])
time.sleep(1)
#bot.send(config["jabber"]["room"], welcome_message, message_type="groupchat")
bot.serve_forever()
|
Fix bug with updated auth backend
Now it checks to see if an email is being submitted. | from django.contrib.auth.models import User
from django.contrib.auth.backends import ModelBackend
class Emailbackend(ModelBackend):
def authenticate(self, email=None, password=None, *args, **kwargs):
if email is None:
if not 'username' in kwargs or kwargs['username'] is None:
return None
email = kwargs['username']
# Check if we're dealing with an email address
if '@' not in email:
return None
# We lowercase the host part as this is what Django does when saving a
# user
local, host = email.split('@')
clean_email = local + '@' + host.lower()
try:
user = User.objects.get(email=clean_email)
except User.DoesNotExist:
return None
if user.check_password(password):
return user
| from django.contrib.auth.models import User
from django.contrib.auth.backends import ModelBackend
class Emailbackend(ModelBackend):
def authenticate(self, email=None, password=None, *args, **kwargs):
if email is None:
if not 'username' in kwargs or kwargs['username'] is None:
return None
email = kwargs['username']
# We lowercase the host part as this is what Django does when saving a
# user
local, host = email.split('@')
clean_email = local + '@' + host.lower()
try:
user = User.objects.get(email=clean_email)
except User.DoesNotExist:
return None
if user.check_password(password):
return user
|
FIX Values return type comment | <?php
/**
* Created by PhpStorm.
* User: ahmetturk
* Date: 19/03/2017
* Time: 09:04
*/
namespace Fabs\CouchDB2\Response;
use Fabs\Serialize\SerializableObject;
class ViewResponseElement extends SerializableObject
{
protected $id = null;
protected $key = null;
protected $value = null;
protected $doc = null;
/**
* @param $type string
* @return SerializableObject
*/
public function getValueWithType($type)
{
return SerializableObject::create($this->getValue(), $type);
}
/**
* @param $type string
* @return SerializableObject
*/
public function getDocWithType($type)
{
return SerializableObject::create($this->getDoc(), $type);
}
/**
* @return mixed
*/
public function getValue()
{
return $this->value;
}
/**
* @return array
*/
public function getDoc()
{
return $this->doc;
}
/**
* @return string
*/
public function getID()
{
return $this->id;
}
/**
* @return array|string
*/
public function getKey()
{
return $this->key;
}
} | <?php
/**
* Created by PhpStorm.
* User: ahmetturk
* Date: 19/03/2017
* Time: 09:04
*/
namespace Fabs\CouchDB2\Response;
use Fabs\Serialize\SerializableObject;
class ViewResponseElement extends SerializableObject
{
protected $id = null;
protected $key = null;
protected $value = null;
protected $doc = null;
/**
* @param $type string
* @return SerializableObject
*/
public function getValueWithType($type)
{
return SerializableObject::create($this->getValue(), $type);
}
/**
* @param $type string
* @return SerializableObject
*/
public function getDocWithType($type)
{
return SerializableObject::create($this->getDoc(), $type);
}
/**
* @return array
*/
public function getValue()
{
return $this->value;
}
/**
* @return array
*/
public function getDoc()
{
return $this->doc;
}
/**
* @return string
*/
public function getID()
{
return $this->id;
}
/**
* @return array|string
*/
public function getKey()
{
return $this->key;
}
} |
Add missing import for HttpResponse | from django.conf import settings
from django.conf.urls.defaults import patterns, include
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.http import HttpResponse
from funfactory.monkeypatches import patch
patch()
from events.api import EventResource
event_resource = EventResource()
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
(r'', include('mozcal.events.urls')),
(r'^api/', include(event_resource.urls)),
(r'^admin/', include('mozcal.admin.urls')),
(r'^browserid/', include('django_browserid.urls')),
# Generate a robots.txt
(r'^robots\.txt$', lambda r: HttpResponse(
"User-agent: *\n%s: /" % 'Allow' if settings.ENGAGE_ROBOTS else 'Disallow' ,
mimetype="text/plain")
)
# Uncomment the admin/doc line below to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# (r'^admin/', include(admin.site.urls)),
)
## In DEBUG mode, serve media files through Django.
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
| from django.conf import settings
from django.conf.urls.defaults import patterns, include
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from funfactory.monkeypatches import patch
patch()
from events.api import EventResource
event_resource = EventResource()
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
(r'', include('mozcal.events.urls')),
(r'^api/', include(event_resource.urls)),
(r'^admin/', include('mozcal.admin.urls')),
(r'^browserid/', include('django_browserid.urls')),
# Generate a robots.txt
(r'^robots\.txt$', lambda r: HttpResponse(
"User-agent: *\n%s: /" % 'Allow' if settings.ENGAGE_ROBOTS else 'Disallow' ,
mimetype="text/plain")
)
# Uncomment the admin/doc line below to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# (r'^admin/', include(admin.site.urls)),
)
## In DEBUG mode, serve media files through Django.
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
|
Validate redirect for logout tests | package handlers
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestLogoutHandler(t *testing.T) {
setUp("/config/testing/handler_logout_url.yml")
handler := http.HandlerFunc(LogoutHandler)
tests := []struct {
name string
url string
wantcode int
}{
{"allowed", "http://myapp.example.com/login", http.StatusFound},
{"allowed", "https://oauth2.googleapis.com/revoke", http.StatusFound},
{"not allowed", "http://myapp.example.com/loginagain", http.StatusBadRequest},
{"not allowed", "http://google.com/", http.StatusBadRequest},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req, err := http.NewRequest("GET", "/logout?url="+tt.url, nil)
if err != nil {
t.Fatal(err)
}
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)
if rr.Code != tt.wantcode {
t.Errorf("LogoutHandler() status = %v, want %v", rr.Code, tt.wantcode)
}
if (rr.Code == http.StatusFound && rr.Header().Get("Location") != tt.url) {
t.Errorf("LogoutHandler() redirect = %s, want %s", rr.Header().Get("Location"), tt.url)
}
})
}
}
| package handlers
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestLogoutHandler(t *testing.T) {
setUp("/config/testing/handler_logout_url.yml")
handler := http.HandlerFunc(LogoutHandler)
tests := []struct {
name string
url string
wantcode int
}{
{"allowed", "http://myapp.example.com/login", http.StatusFound},
{"allowed", "https://oauth2.googleapis.com/revoke", http.StatusFound},
{"not allowed", "http://myapp.example.com/loginagain", http.StatusBadRequest},
{"not allowed", "http://google.com/", http.StatusBadRequest},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req, err := http.NewRequest("GET", "/logout?url="+tt.url, nil)
if err != nil {
t.Fatal(err)
}
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)
if rr.Code != tt.wantcode {
t.Errorf("LogoutHandler() = %v, want %v", rr.Code, tt.wantcode)
}
})
}
}
|
Fix agent class after merging | package com.kiselev.reflection.ui.bytecode.agent;
import java.lang.instrument.Instrumentation;
/**
* Created by Vadim Kiselev on 6/12/2017.
*/
public class Agent {
public static void agentmain(String args, Instrumentation instrumentation) {
try {
instrumentation.addTransformer(new Transformer(), true);
Class[] allLoadedClasses = instrumentation.getAllLoadedClasses();
for (Class loadedClass : allLoadedClasses) {
if (!loadedClass.isArray()) {
instrumentation.retransformClasses(loadedClass);
}
}
} catch (Exception exception) {
// sin
}
}
}
| package com.kiselev.reflection.ui.bytecode.agent;
import com.kiselev.reflection.ui.bytecode.holder.ByteCodeHolder;
import java.lang.instrument.Instrumentation;
import java.util.List;
/**
* Created by Vadim Kiselev on 6/12/2017.
*/
public class Agent {
public static void agentmain(String args, Instrumentation instrumentation) {
try {
instrumentation.addTransformer(new Transformer(), true);
Class[] allLoadedClasses = instrumentation.getAllLoadedClasses();
for (Class loadedClass : allLoadedClasses) {
if (!loadedClass.isArray()) {
instrumentation.retransformClasses(loadedClass);
}
}
} catch (Exception exception) {
// sin
}
}
}
|
Create the anonymous user server side instead | App.Router.map(function () {
this.resource('projects', {path: '/'}, function() {
this.resource('user-welcome');
this.resource('project', {path: '/:project_id'}, function() {
this.resource('investigation', {path: '/:investigation_id'}, function() {
this.resource('chart', {path: '/:chart_id'}, function(){
this.route('edit');
});
});
});
});
});
App.Router.reopen({
rootURL: '/portal'
});
App.ApplicationRoute = Ember.Route.extend({
model: function () {
var self = this;
return this.store.find('user').then(function(user) {
return user.get('firstObject');
}, function(error){
console.log();
});
}
});
App.ProjectRoute = Ember.Route.extend({
model: function(params) {
return this.store.find('project', params.project_id);
},
renderTemplate: function() {
this.render('project');
this.render('project-title', {
outlet: 'title'
});
}
}); | App.Router.map(function () {
this.resource('projects', {path: '/'}, function() {
this.resource('user-welcome');
this.resource('project', {path: '/:project_id'}, function() {
this.resource('investigation', {path: '/:investigation_id'}, function() {
this.resource('chart', {path: '/:chart_id'}, function(){
this.route('edit');
});
});
});
});
});
App.Router.reopen({
rootURL: '/portal'
});
App.ApplicationRoute = Ember.Route.extend({
model: function () {
var self = this;
return this.store.find('user').then(function(user) {
if (user) {
return user.get('firstObject');
} else {
return new App.User();
}
}, function(error){
console.log();
});
}
});
App.ProjectRoute = Ember.Route.extend({
model: function(params) {
return this.store.find('project', params.project_id);
},
renderTemplate: function() {
this.render('project');
this.render('project-title', {
outlet: 'title'
});
}
}); |
Update click handler for setting current channel | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { getChannels, setChannel } from '../../actions/items';
class ChannelDropdown extends Component {
componentWillMount() {
this.props.getChannels();
}
renderChannels(channelData) {
const name = channelData.channel.name;
// const url = `https://www.twitch.tv/${name}`;
return (
<li key={name} onClick={() => this.props.setChannel(name)}>{name}</li>
);
}
render() {
return (
<div className="btn-group">
<button type="button" className="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Top Channels <span className="caret"></span>
</button>
<ul className="dropdown-menu">
{this.props.channels.list.map(this.renderChannels, this)}
</ul>
</div>
);
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ getChannels, setChannel }, dispatch);
}
function mapStateToProps({ channels }) {
return { channels };
}
export default connect(mapStateToProps, mapDispatchToProps)(ChannelDropdown);
| import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { getChannels } from '../../actions/items';
class ChannelDropdown extends Component {
componentWillMount() {
this.props.getChannels();
}
setChannel(channel) {
this.props.setChannel(channel);
}
renderChannels(channelData) {
const name = channelData.channel.name;
const url = `https://www.twitch.tv/${name}`;
return (
<li key={name} onClick={this.setChannel(name).bind(this)}><a href={url}>{name}</a></li>
);
}
render() {
return (
<div className="btn-group">
<button type="button" className="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Top Channels <span className="caret"></span>
</button>
<ul className="dropdown-menu">
{this.props.channels.list.map(this.renderChannels)}
</ul>
</div>
);
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ getChannels }, dispatch);
}
function mapStateToProps({ channels }) {
return { channels };
}
export default connect(mapStateToProps, mapDispatchToProps)(ChannelDropdown);
|
Add support for actions to remote dropdown | import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'div',
classNames: ['ui', 'search', 'selection', 'dropdown', 'fluid'],
value: null,
text: null,
bindAttributes: ['value', 'text'],
setup: function () {
this.$().dropdown({
apiSettings: {
url: this.get('query-url'),
onResponse: function (response) {
var documents = Ember.ArrayProxy.create({content: Ember.A(response.documents)});
var results = documents.map(function (item, index, enumerable) {
return {name: item.navn, value: item._id};
});
return {success: true, results: results};
}
},
onChange: Ember.run.bind(this, this.onChange)
});
}.on('didInsertElement'),
onChange: function (value, text, $choice) {
if (this.get('attrs.action')) {
if (!this.get('attrs.value')) {
this.$().dropdown('clear');
}
this.sendAction('action', value);
} else {
this.set('value', value);
}
},
updateDropdownValue: function () {
this.$().dropdown('set value', this.get('value'));
}.observes('value'),
updateDropdownText: function () {
this.$().dropdown('set text', this.get('text'));
}.observes('text')
});
| import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'div',
classNames: ['ui', 'search', 'selection', 'dropdown', 'fluid'],
value: null,
text: null,
bindAttributes: ['value', 'text'],
setup: function () {
this.$().dropdown({
apiSettings: {
url: this.get('query-url'),
onResponse: function (response) {
var documents = Ember.ArrayProxy.create({content: Ember.A(response.documents)});
var results = documents.map(function (item, index, enumerable) {
return {name: item.navn, value: item._id};
});
return {success: true, results: results};
}
},
onChange: Ember.run.bind(this, this.onChange)
});
}.on('didInsertElement'),
onChange: function (value, text, $choice) {
this.set('value', value);
},
updateDropdownValue: function () {
this.$().dropdown('set value', this.get('value'));
}.observes('value'),
updateDropdownText: function () {
this.$().dropdown('set text', this.get('text'));
}.observes('text')
});
|
pyecmd: Make fapi2 test conditional on fapi2 being built into ecmd | from pyecmd import *
extensions = {}
if hasattr(ecmd, "fapi2InitExtension"):
extensions["fapi2"] = "ver1"
with Ecmd(**extensions):
t = loopTargets("pu", ECMD_SELECTED_TARGETS_LOOP)[0]
data = t.getScom(0x1234)
t.putScom(0x1234, 0x10100000)
# These interfaces may not be defined for some plugins
# Pull them to prevent compile issues
#core_id, thread_id = t.targetToSequenceId()
#unit_id_string = unitIdToString(2)
#clock_state = t.queryClockState("SOMECLOCK")
t.relatedTargets("pu.c")
retval = t.queryFileLocationHidden2(ECMD_FILE_SCANDEF, "")
for loc in retval.fileLocations:
testval = loc.textFile + loc.hashFile + retval.version
if "fapi2" in extensions:
try:
t.fapi2GetAttr("ATTR_DOES_NOT_EXIST")
assert(""=="That was supposed to throw!")
except KeyError:
pass
t.fapi2SetAttr("ATTR_CHIP_ID", 42)
assert(42 == t.fapi2GetAttr("ATTR_CHIP_ID"))
| from pyecmd import *
with Ecmd(fapi2="ver1"):
t = loopTargets("pu", ECMD_SELECTED_TARGETS_LOOP)[0]
data = t.getScom(0x1234)
t.putScom(0x1234, 0x10100000)
# These interfaces may not be defined for some plugins
# Pull them to prevent compile issues
#core_id, thread_id = t.targetToSequenceId()
#unit_id_string = unitIdToString(2)
#clock_state = t.queryClockState("SOMECLOCK")
t.relatedTargets("pu.c")
retval = t.queryFileLocationHidden2(ECMD_FILE_SCANDEF, "")
for loc in retval.fileLocations:
testval = loc.textFile + loc.hashFile + retval.version
try:
t.fapi2GetAttr("ATTR_DOES_NOT_EXIST")
assert(""=="That was supposed to throw!")
except KeyError:
pass
t.fapi2SetAttr("ATTR_CHIP_ID", 42)
assert(42 == t.fapi2GetAttr("ATTR_CHIP_ID"))
|
Clear output buffer only if it's not empty
Former-commit-id: 622fddc8c4d547ec1853d0b8cffe61d102215216 | <? defined('C5_EXECUTE') or die('Access Denied.');
class Concrete5_Helper_Ajax {
/** Sends a result to the client and ends the execution.
* @param mixed $result
*/
public function sendResult($result) {
if(@ob_get_length()) {
@ob_end_clean();
}
header('Content-Type: application/json; charset=' . APP_CHARSET, true);
echo Loader::helper('json')->encode($result);
die();
}
/** Sends an error to the client and ends the execution.
* @param string|Exception $result The error to send to the client.
*/
public function sendError($error) {
if(@ob_get_length()) {
@ob_end_clean();
}
header($_SERVER['SERVER_PROTOCOL'] . ' 400 Bad Request', true, 400);
header('Content-Type: text/plain; charset=' . APP_CHARSET, true);
echo ($error instanceof Exception) ? $error->getMessage() : $error;
die();
}
} | <? defined('C5_EXECUTE') or die('Access Denied.');
class Concrete5_Helper_Ajax {
/** Sends a result to the client and ends the execution.
* @param mixed $result
*/
public function sendResult($result) {
@ob_end_clean();
header('Content-Type: application/json; charset=' . APP_CHARSET, true);
echo Loader::helper('json')->encode($result);
die();
}
/** Sends an error to the client and ends the execution.
* @param string|Exception $result The error to send to the client.
*/
public function sendError($error) {
@ob_end_clean();
header($_SERVER['SERVER_PROTOCOL'] . ' 400 Bad Request', true, 400);
header('Content-Type: text/plain; charset=' . APP_CHARSET, true);
echo ($error instanceof Exception) ? $error->getMessage() : $error;
die();
}
} |
Fix changes in the registry of tile entity renderer in the latest forge updates (30.0.19) | package info.u_team.u_team_core.util.registry;
import java.util.function.Function;
import net.minecraft.client.renderer.tileentity.*;
import net.minecraft.client.settings.KeyBinding;
import net.minecraft.entity.*;
import net.minecraft.tileentity.*;
import net.minecraftforge.api.distmarker.*;
import net.minecraftforge.fml.client.registry.*;
@OnlyIn(Dist.CLIENT)
public class ClientRegistry {
public static <T extends Entity> void registerEntityRenderer(EntityType<T> clazz, IRenderFactory<? super T> rendererFactory) {
RenderingRegistry.registerEntityRenderingHandler(clazz, rendererFactory);
}
public static <T extends TileEntity> void registerSpecialTileEntityRenderer(TileEntityType<T> clazz, TileEntityRenderer<? super T> renderer) {
registerSpecialTileEntityRenderer(clazz, dispatcher -> renderer);
}
public static <T extends TileEntity> void registerSpecialTileEntityRenderer(TileEntityType<T> clazz, Function<? super TileEntityRendererDispatcher, ? extends TileEntityRenderer<? super T>> rendererFactory) {
net.minecraftforge.fml.client.registry.ClientRegistry.bindTileEntityRenderer(clazz, rendererFactory);
}
public static void registerKeybinding(KeyBinding key) {
net.minecraftforge.fml.client.registry.ClientRegistry.registerKeyBinding(key);
}
}
| package info.u_team.u_team_core.util.registry;
import net.minecraft.client.renderer.tileentity.TileEntityRenderer;
import net.minecraft.client.settings.KeyBinding;
import net.minecraft.entity.*;
import net.minecraft.tileentity.*;
import net.minecraftforge.api.distmarker.*;
import net.minecraftforge.fml.client.registry.*;
@OnlyIn(Dist.CLIENT)
public class ClientRegistry {
public static <T extends Entity> void registerEntityRenderer(EntityType<T> clazz, IRenderFactory<? super T> rendererFactory) {
RenderingRegistry.registerEntityRenderingHandler(clazz, rendererFactory);
}
public static <T extends TileEntity> void registerSpecialTileEntityRenderer(TileEntityType<T> clazz, TileEntityRenderer<? super T> renderer) {
net.minecraftforge.fml.client.registry.ClientRegistry.bindTileEntityRenderer(clazz, renderer);
}
public static void registerKeybinding(KeyBinding key) {
net.minecraftforge.fml.client.registry.ClientRegistry.registerKeyBinding(key);
}
}
|
Add "i have a problem" as new trigger | // Description
// Get an inspiring question form serenize.me
//
// Commands:
// hubot <serenize me> - <fetches a question>
// hubot <serenize.me> - <fetches a question>
// hubot <i have a problem> - <fetches a question>
//
// Author:
// Serenize
module.exports = function(robot) {
'use strict';
robot.respond(/serenize me/i, function(res) {
getQuestion(res);
});
robot.respond(/serenize\.me/i, function(res) {
getQuestion(res);
});
robot.respond(/i have a problem/i, function(res) {
getQuestion(res);
});
var getQuestion = function(res) {
robot.http('http://www.serenize.me/api/question')
.header('Accept', 'application/json')
.get()(function(err, resp, body) {
if (err) {
res.send('Warum ist serenize.me offline? ' + err);
return;
}
var data = JSON.parse(body);
res.send(data.question);
});
};
};
| // Description
// Get an inspiring question form serenize.me
//
// Commands:
// hubot <serenize me> - <fetches a question>
// hubot <serenize.me> - <fetches a question>
//
// Author:
// Serenize
module.exports = function(robot) {
'use strict';
robot.respond(/serenize me/i, function(res) {
getQuestion(res);
});
robot.respond(/serenize\.me/i, function(res) {
getQuestion(res);
});
var getQuestion = function(res) {
robot.http('http://www.serenize.me/api/question')
.header('Accept', 'application/json')
.get()(function(err, resp, body) {
if (err) {
res.send('Warum ist serenize.me offline? ' + err);
return;
}
var data = JSON.parse(body);
res.send(data.question);
});
};
};
|
Add construction counts to the qualities catalog. | @section('title')
Qualities - Cataclysm: Dark Days Ahead
@endsection
<h1>Qualities</h1>
<div class="row">
<div class="col-md-3">
<ul class="nav nav-pills nav-stacked">
@foreach($qualities as $quality)
<li class="@if($quality->id==$id) active @endif"><a href="{{ route(Route::currentRouteName(), $quality->id) }}">{{{$quality->name}}}</a></li>
@endforeach
</ul>
</div>
<div class="col-md-9">
@if (!$id)
Please select an entry from the menu on the left.
@else
<table class="table table-bordered table-hover tablesorter">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Level</th>
<th>Recipes</th>
<th>Construction</th>
</tr>
</thead>
@foreach($items as $item)
<tr>
<td>{{ $item->symbol }}</td>
<td><a href="{{route('item.view', $item->id)}}">{{ $item->name }}</a></td>
<td>{{{ $item->qualityLevel($id) }}}</td>
<td>{{{ $item->count("toolFor") }}}</td>
<td>{{{ $item->count("construction") }}}</td>
</tr>
</tr>
@endforeach
</table>
<script>
$(function() {
$(".tablesorter").tablesorter({
sortList: [[2,0]]
});
});
</script>
@endif
</div>
</div>
| @section('title')
Qualities - Cataclysm: Dark Days Ahead
@endsection
<h1>Qualities</h1>
<div class="row">
<div class="col-md-3">
<ul class="nav nav-pills nav-stacked">
@foreach($qualities as $quality)
<li class="@if($quality->id==$id) active @endif"><a href="{{ route(Route::currentRouteName(), $quality->id) }}">{{{$quality->name}}}</a></li>
@endforeach
</ul>
</div>
<div class="col-md-9">
@if (!$id)
Please select an entry from the menu on the left.
@else
<table class="table table-bordered table-hover tablesorter">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Level</th>
<th>Recipes</th>
</tr>
</thead>
@foreach($items as $item)
<tr>
<td>{{ $item->symbol }}</td>
<td><a href="{{route('item.view', $item->id)}}">{{ $item->name }}</a></td>
<td>{{{ $item->qualityLevel($id) }}}</td>
<td>{{{ $item->count("toolFor") }}}</td>
</tr>
</tr>
@endforeach
</table>
<script>
$(function() {
$(".tablesorter").tablesorter({
sortList: [[2,0]]
});
});
</script>
@endif
</div>
</div>
|
system: Fix style for controller class | <?php
/**
* This file contains the base abstract controller class.
*
* PHP Version 5.3
*
* @category Libraries
* @package Core
* @subpackage Libraries
* @author M2Mobi <info@m2mobi.com>
* @author Heinz Wiesinger <heinz@m2mobi.com>
*/
/**
* Base Controller class
*
* @category Libraries
* @package Core
* @subpackage Libraries
* @author M2Mobi <info@m2mobi.com>
* @author Heinz Wiesinger <heinz@m2mobi.com>
*/
abstract class Controller
{
/**
* Constructor.
*/
public function __construct()
{
}
/**
* Destructor.
*/
public function __destruct()
{
}
/**
* Handle unimplemented calls.
*
* @param String $name Method name
* @param array $arguments Arguments passed to the method
*
* @return String JSON encoded error String
*/
public function __call($name, $arguments)
{
return Json::error("not_implemented");
}
/**
* Default method as defined in conf.application.inc.php.
*
* @return void
*/
abstract public function index();
}
?>
| <?php
/**
* This file contains the base abstract controller class.
*
* PHP Version 5.3
*
* @category Libraries
* @package Core
* @subpackage Libraries
* @author M2Mobi <info@m2mobi.com>
* @author Heinz Wiesinger <heinz@m2mobi.com>
*/
/**
* Base Controller class
*
* @category Libraries
* @package Core
* @subpackage Libraries
* @author M2Mobi <info@m2mobi.com>
* @author Heinz Wiesinger <heinz@m2mobi.com>
*/
abstract class Controller
{
/**
* Constructor
*/
public function __construct()
{
}
/**
* Destructor
*/
public function __destruct()
{
}
/**
* Handle unimplemented calls
*
* @param String $name Method name
* @param array $arguments Arguments passed to the method
*
* @return String JSON encoded error String
*/
public function __call($name, $arguments)
{
return Json::error("not_implemented");
}
/**
* Default method as defined in conf.application.inc.php
*
* @return void
*/
abstract public function index();
}
?>
|
Add target to aui-button links | export default {
render(createComponent) {
const attrs = {
disabled: this.disabled,
href: this.href,
target: this.target
};
const elementType = this.href ? 'a' : 'button'
return createComponent(elementType, {
class: this.classObject,
attrs
}, this.$slots.default)
},
props: {
compact: Boolean,
disabled: Boolean,
href: String,
light: Boolean,
subtle: Boolean,
target: String,
type: {
type: String,
validator(value) {
return 'primary' === value
|| 'link' === value
}
},
},
computed: {
classObject() {
return {
'aui-button': true,
'aui-button-primary': this.type === 'primary',
'aui-button-link': this.type === 'link',
'aui-button-light': this.light,
'aui-button-subtle': this.subtle,
'aui-button-compact': this.compact,
}
}
},
}
| export default {
render(createComponent) {
const attrs = {
disabled: this.disabled,
href: this.href
};
const elementType = this.href ? 'a' : 'button'
return createComponent(elementType, {
class: this.classObject,
attrs
}, this.$slots.default)
},
props: {
compact: Boolean,
disabled: Boolean,
href: String,
light: Boolean,
subtle: Boolean,
type: {
type: String,
validator(value) {
return 'primary' === value
|| 'link' === value
}
},
},
computed: {
classObject() {
return {
'aui-button': true,
'aui-button-primary': this.type === 'primary',
'aui-button-link': this.type === 'link',
'aui-button-light': this.light,
'aui-button-subtle': this.subtle,
'aui-button-compact': this.compact,
}
}
},
}
|
Reduce the slugify rebounce to 250ms instead of 1000ms. | var seo = {
init: function() {
this.sluggable_input().on('keyup', $.debounce(250, this.keyup_listener));
},
data: function(key) {
return $('[data-seo]').data(key);
},
keyup_listener: function(e) {
if(seo.slug_input().attr('disabled')) return;
$.ajax({
url: seo.data('path'),
data: { value: $(this).val() },
type: 'GET'
}).done(function(data){
seo.slug_input().val(data.result);
});
},
slug_input: function() {
return $('input[id*="seo_slug"]');
},
sluggable_input: function() {
return $($('[data-seo]').data('sluggable-input'));
}
};
$(function(){ seo.init(); });
| var seo = {
init: function() {
this.sluggable_input().on('keyup', $.debounce(1000, this.keyup_listener));
},
data: function(key) {
return $('[data-seo]').data(key);
},
keyup_listener: function(e) {
if(seo.slug_input().attr('disabled')) return;
$.ajax({
url: seo.data('path'),
data: { value: $(this).val() },
type: 'GET'
}).done(function(data){
seo.slug_input().val(data.result);
});
},
slug_input: function() {
return $('input[id*="seo_slug"]');
},
sluggable_input: function() {
return $($('[data-seo]').data('sluggable-input'));
}
};
$(function(){ seo.init(); });
|
Move status to database instead of status file (server side) | from __future__ import unicode_literals
import os
import logging
import sqlite3
from . import helper
def readStatus(config, student):
database = getStatusTable(config)
cursor = database.cursor()
cursor.execute("SELECT status FROM status WHERE identifier = ?", (student,))
statusRow = cursor.fetchone()[0] # just get first status
if statusRow:
return statusRow
else:
return "Unbearbeitet"
def writeStatus(config, student, status):
database = getStatusTable(config)
cursor = database.cursor()
# Check if we need to create a new row first
cursor.execute("SELECT status FROM status WHERE identifier = ?", (student,))
statusRow = cursor.fetchone()[0]
if statusRow:
cursor.execute("UPDATE status SET status = ? WHERE identifier = ?", (status, student,))
else:
cursor.execute("INSERT INTO status VALUES(?, ?)", (student, status, ))
database.commit()
def getStatusTable(config):
statusDatabasePath = config("database_path")
statusDatabase = sqlite3.connect(statusDatabasePath)
cursor = statusDatabase.cursor()
cursor.execute("""CREATE TABLE IF NOT EXISTS status
(`identifier` text UNIQUE, `status` text, PRIMARY KEY (`identifier`));""")
return statusDatabase
| from __future__ import unicode_literals
import os
import logging
from . import helper
def readStatus(config, student):
student = student.lower()
path = config("attachment_path")
if not os.path.exists(path):
return
path = os.path.join(path, student)
if not os.path.exists(path):
return "Student ohne Abgabe"
path = os.path.join(path, "korrekturstatus.txt")
if not os.path.exists(path):
return "Unbearbeitet"
statusfile = open(path, "r")
status = statusfile.read()
statusfile.close()
return status
def writeStatus(config, student, status):
student = student.lower()
status = status.lower()
path = os.path.join(config("attachment_path"), student)
if not os.path.exists(path):
logging.error("Requested student '%s' hasn't submitted anything yet.")
return
path = os.path.join(path, "korrekturstatus.txt")
with open(path, "w") as statusfile:
statusfile.write(status)
|
Fix code as int test | package errors
import (
nativeErrors "errors"
"net/http"
"testing"
)
func TestHTTPStatusCode(t *testing.T) {
if HTTPStatusCode(nil) != http.StatusOK {
t.Error("Status code does not match")
}
if HTTPStatusCode(New(INTERNAL, "internal error")) != http.StatusInternalServerError {
t.Error("Status code does not match")
}
if HTTPStatusCode(New(FORBIDDEN, "status map")) != errorCodeToHTTPStatusMap[FORBIDDEN] {
t.Error("Status code does not match")
}
if HTTPStatusCode(Wrap(New(INTERNAL, "status map"), "", "")) != errorCodeToHTTPStatusMap[INTERNAL] {
t.Error("Status code does not match")
}
if HTTPStatusCode(New("unknown_code", "internal error")) != http.StatusInternalServerError {
t.Error("Status code does not match")
}
if HTTPStatusCode(New("400", "code as int")) != http.StatusBadRequest {
t.Error("Status code does not match")
}
if HTTPStatusCode(nativeErrors.New("native error")) != http.StatusInternalServerError {
t.Error("Status code does not match")
}
}
| package errors
import (
nativeErrors "errors"
"net/http"
"testing"
)
func TestHTTPStatusCode(t *testing.T) {
if HTTPStatusCode(nil) != http.StatusOK {
t.Error("Status code does not match")
}
if HTTPStatusCode(New(INTERNAL, "internal error")) != http.StatusInternalServerError {
t.Error("Status code does not match")
}
if HTTPStatusCode(New(FORBIDDEN, "status map")) != errorCodeToHTTPStatusMap[FORBIDDEN] {
t.Error("Status code does not match")
}
if HTTPStatusCode(Wrap(New(INTERNAL, "status map"), "", "")) != errorCodeToHTTPStatusMap[INTERNAL] {
t.Error("Status code does not match")
}
if HTTPStatusCode(New("unknown_code", "internal error")) != http.StatusInternalServerError {
t.Error("Status code does not match")
}
if HTTPStatusCode(New("123", "code as int")) != 123 {
t.Error("Status code does not match")
}
if HTTPStatusCode(nativeErrors.New("native error")) != http.StatusInternalServerError {
t.Error("Status code does not match")
}
}
|
Make isAdmin method more readable. | <?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Phragile\PhabricatorAPI;
class User extends Eloquent implements UserInterface {
// This is used for password authentication, recovery etc which we don't need.
// Only using this because Auth::login won't work otherwise.
use UserTrait;
protected $fillable = ['phid', 'username'];
public function setRememberToken($token) {
// Workaround: Auth::logout breaks with the default behavior since we're using OAuth.
}
public function certificateValid($certificate = null)
{
try
{
$phabricator = new PhabricatorAPI(new ConduitClient($_ENV['PHABRICATOR_URL']));
$phabricator->connect($this->username, $certificate ?: $this->conduit_certificate);
} catch (ConduitClientException $e)
{
return false;
}
return true;
}
public function isAdmin()
{
return in_array(
strtolower($this->username),
array_map('trim', explode(',', $_ENV['PHRAGILE_ADMINS']))
);
}
}
| <?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Phragile\PhabricatorAPI;
class User extends Eloquent implements UserInterface {
// This is used for password authentication, recovery etc which we don't need.
// Only using this because Auth::login won't work otherwise.
use UserTrait;
protected $fillable = ['phid', 'username'];
public function setRememberToken($token) {
// Workaround: Auth::logout breaks with the default behavior since we're using OAuth.
}
public function certificateValid($certificate = null)
{
try
{
$phabricator = new PhabricatorAPI(new ConduitClient($_ENV['PHABRICATOR_URL']));
$phabricator->connect($this->username, $certificate ?: $this->conduit_certificate);
} catch (ConduitClientException $e)
{
return false;
}
return true;
}
public function isAdmin()
{
return in_array(strtolower($this->username), array_map('trim', explode(',', $_ENV['PHRAGILE_ADMINS'])));
}
}
|
Swap the arguments being passed to trigger_error().
Fixes issue #247
http://symphony-cms.com/discuss/issues/view/247/ | <?php
Class DateTimeObj{
public static function setDefaultTimezone($timezone){
if(!@date_default_timezone_set($timezone)) trigger_error("Invalid timezone '{$timezone}'", E_USER_WARNING);
}
public static function getGMT($format, $timestamp=NULL){
return self::get($format, $timestamp, 'GMT');
}
public static function getTimeAgo($format){
return '<abbr class="timeago" title="'.self::get('r').'">'.self::get($format).'</abbr>';
}
public static function get($format, $timestamp=NULL, $timezone=NULL){
if(!$timestamp || $timestamp == 'now') $timestamp = time();
if(!$timezone) $timezone = date_default_timezone_get();
$current_timezone = date_default_timezone_get();
if($current_timezone != $timezone) self::setDefaultTimezone($timezone);
$ret = date($format, $timestamp);
if($current_timezone != $timezone) self::setDefaultTimezone($current_timezone);
return $ret;
}
}
| <?php
Class DateTimeObj{
public static function setDefaultTimezone($timezone){
if(!@date_default_timezone_set($timezone)) trigger_error(E_USER_WARNING, "Invalid timezone '{$timezone}'");
}
public static function getGMT($format, $timestamp=NULL){
return self::get($format, $timestamp, 'GMT');
}
public static function getTimeAgo($format){
return '<abbr class="timeago" title="'.self::get('r').'">'.self::get($format).'</abbr>';
}
public static function get($format, $timestamp=NULL, $timezone=NULL){
if(!$timestamp || $timestamp == 'now') $timestamp = time();
if(!$timezone) $timezone = date_default_timezone_get();
$current_timezone = date_default_timezone_get();
if($current_timezone != $timezone) self::setDefaultTimezone($timezone);
$ret = date($format, $timestamp);
if($current_timezone != $timezone) self::setDefaultTimezone($current_timezone);
return $ret;
}
}
|
Change the way golang packages are built | package buildcfg
import (
"net/url"
"strings"
)
func goImportPath(remote string) string {
if strings.Contains(remote, ":") && strings.Contains(remote, "@") {
rem := remote[strings.Index(remote, "@")+1:]
return strings.Replace(strings.Replace(rem, ".git", "", 1), ":", "/", 1)
}
u, err := url.Parse(remote)
if err != nil {
return remote
}
return u.Hostname() + strings.Replace(u.Path, ".git", "", 1)
}
func loadGoConfig(remote string, c *Config) {
importPath := goImportPath(remote)
// Most part of this just moves everything from builddir to the correct go-import-path
setup := []string{
"export GOPATH=/build/.gopath",
"export PATH=$PATH:/build/bin",
"mkdir -p /build/.gopath/src/" + importPath,
"mount -o bind /build /build/.gopath/src/" + importPath,
"cd /build/.gopath/src/" + importPath,
}
c.Setup.V = append(setup, c.Setup.V...)
c.Addons.Apt.Packages = append(c.Addons.Apt.Packages, "rsync")
if len(c.Script.V) == 0 && len(c.Install.V) == 0 {
c.Script.V = []string{
"go get -t -v ./...",
"go test -v ./...",
}
}
c.DockerImage = "golang"
}
| package buildcfg
import (
"net/url"
"strings"
)
func loadGoConfig(remote string, c *Config) {
u, _ := url.Parse(remote)
importPath := u.Hostname() + strings.Replace(u.Path, ".git", "", 1)
// Most part of this just moves everything from builddir to the correct go-import-path
setup := []string{
"export GOPATH=/build",
"export PATH=$PATH:/build/bin",
"mkdir /tmp/dat",
"rsync -az . /tmp/dat",
"rm -rf *",
"mkdir -p src/" + importPath,
"rsync -az /tmp/dat/ src/" + importPath,
"rm -rf /tmp/dat",
"cd src/" + importPath,
}
c.Setup.V = append(setup, c.Setup.V...)
c.Addons.Apt.Packages = append(c.Addons.Apt.Packages, "rsync")
if len(c.Script.V) == 0 && len(c.Install.V) == 0 {
c.Script.V = []string{
"go get -t -v ./...",
"go test -v ./...",
}
}
c.DockerImage = "golang"
}
|
Read current version from `package.json` | var VERSION = require('../package.json').version;
var _ = require('lodash');
var DEFAULT_API_URL = 'https://api.podio.com:443';
var utils = require('./utils');
var GeneralLib = require('./general');
var AuthLib = require('./auth');
var TransportLib = require('./transport');
var PodioJS = function(authOptions, options) {
this.VERSION = VERSION;
utils._validateAuthOptions(authOptions);
this.authType = authOptions.authType;
this.clientId = authOptions.clientId;
this.clientSecret = authOptions.clientSecret;
this.apiURL = DEFAULT_API_URL;
if (!_.isUndefined(options)) {
if (!_.isUndefined(options.sessionStore)) {
this.sessionStore = options.sessionStore;
this._getAuthFromStore();
}
if (_.isFunction(options.onTokenWillRefresh)) {
this.onTokenWillRefresh = options.onTokenWillRefresh;
}
if (!_.isUndefined(options.apiURL)) {
this.apiURL = options.apiURL;
}
}
};
PodioJS.prototype = _.extend({}, AuthLib, TransportLib, GeneralLib);
module.exports = PodioJS;
| var VERSION = '1.0.0';
var _ = require('lodash');
var DEFAULT_API_URL = 'https://api.podio.com:443';
var utils = require('./utils');
var GeneralLib = require('./general');
var AuthLib = require('./auth');
var TransportLib = require('./transport');
var PodioJS = function(authOptions, options) {
this.VERSION = VERSION;
utils._validateAuthOptions(authOptions);
this.authType = authOptions.authType;
this.clientId = authOptions.clientId;
this.clientSecret = authOptions.clientSecret;
this.apiURL = DEFAULT_API_URL;
if (!_.isUndefined(options)) {
if (!_.isUndefined(options.sessionStore)) {
this.sessionStore = options.sessionStore;
this._getAuthFromStore();
}
if (_.isFunction(options.onTokenWillRefresh)) {
this.onTokenWillRefresh = options.onTokenWillRefresh;
}
if (!_.isUndefined(options.apiURL)) {
this.apiURL = options.apiURL;
}
}
};
PodioJS.prototype = _.extend({}, AuthLib, TransportLib, GeneralLib);
module.exports = PodioJS;
|
Remove use of deprecated `scan_plugins` method
`scan_plugins` has been deprecated in favour of `scan_plugins_regex`. This
is causing warnings to be logged.
The new method takes a regular expression as its first argument, rather than a
simple prefix string. This commit adds a regular expression which does the same
thing as the prefix argument used to do.
For source code see: https://lml.readthedocs.io/en/latest/_modules/lml/loader.html | """
pyexcel.internal
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Pyexcel internals that subjected to change
:copyright: (c) 2015-2017 by Onni Software Ltd.
:license: New BSD License
"""
from lml.loader import scan_plugins
from pyexcel.internal.plugins import PARSER, RENDERER # noqa
from pyexcel.internal.source_plugin import SOURCE # noqa
from pyexcel.internal.generators import SheetStream, BookStream # noqa
BLACK_LIST = [
"pyexcel_io",
"pyexcel_webio",
"pyexcel_xlsx",
"pyexcel_xls",
"pyexcel_ods3",
"pyexcel_ods",
"pyexcel_odsr",
"pyexcel_xlsxw",
]
WHITE_LIST = [
"pyexcel.plugins.parsers",
"pyexcel.plugins.renderers",
"pyexcel.plugins.sources",
]
scan_plugins_regex("^pyexcel_.+$", "pyexcel", BLACK_LIST, WHITE_LIST)
| """
pyexcel.internal
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Pyexcel internals that subjected to change
:copyright: (c) 2015-2017 by Onni Software Ltd.
:license: New BSD License
"""
from lml.loader import scan_plugins
from pyexcel.internal.plugins import PARSER, RENDERER # noqa
from pyexcel.internal.source_plugin import SOURCE # noqa
from pyexcel.internal.generators import SheetStream, BookStream # noqa
BLACK_LIST = [
"pyexcel_io",
"pyexcel_webio",
"pyexcel_xlsx",
"pyexcel_xls",
"pyexcel_ods3",
"pyexcel_ods",
"pyexcel_odsr",
"pyexcel_xlsxw",
]
WHITE_LIST = [
"pyexcel.plugins.parsers",
"pyexcel.plugins.renderers",
"pyexcel.plugins.sources",
]
scan_plugins("pyexcel_", "pyexcel", BLACK_LIST, WHITE_LIST)
|
Add default values to Build variables | package main
import (
"fmt"
"github.com/almighty/almighty-core/app"
"github.com/almighty/almighty-core/swagger"
"github.com/goadesign/goa"
"github.com/goadesign/goa/middleware"
)
var (
// Commit current build commit set by build script
Commit = "0"
// BuildTime set by build script
BuildTime = "0"
)
func main() {
// Create service
service := goa.New("API")
// Setup middleware
service.Use(middleware.RequestID())
service.Use(middleware.LogRequest(true))
service.Use(middleware.ErrorHandler(service, true))
service.Use(middleware.Recover())
// Mount "version" controller
c := NewVersionController(service)
app.MountVersionController(service, c)
// Mount Swagger spec provider controller
swagger.MountController(service)
fmt.Println("Git Commit SHA: ", Commit)
fmt.Println("UTC Build Time: ", BuildTime)
service.ListenAndServe(":8080")
}
| package main
import (
"fmt"
"github.com/almighty/almighty-core/app"
"github.com/almighty/almighty-core/swagger"
"github.com/goadesign/goa"
"github.com/goadesign/goa/middleware"
)
var (
// Commit current build commit set by build script
Commit string
// BuildTime set by build script
BuildTime string
)
func main() {
// Create service
service := goa.New("API")
// Setup middleware
service.Use(middleware.RequestID())
service.Use(middleware.LogRequest(true))
service.Use(middleware.ErrorHandler(service, true))
service.Use(middleware.Recover())
// Mount "version" controller
c := NewVersionController(service)
app.MountVersionController(service, c)
// Mount Swagger spec provider controller
swagger.MountController(service)
fmt.Println("Git Commit SHA: ", Commit)
fmt.Println("UTC Build Time: ", BuildTime)
service.ListenAndServe(":8080")
}
|
Add version constraint for easy-meteor-settings | Package.describe({
name: 'hubaaa:endpoint-puller',
version: '0.1.0',
// Brief, one-line summary of the package.
summary: 'Pulls API endpoints, checking for new data and passing it through json pipes.',
// URL to the Git repository containing the source code for this package.
git: 'https://github.com/hubaaa/meteor-endpoint-puller',
// By default, Meteor will default to using README.md for documentation.
// To avoid submitting documentation, set this field to null.
documentation: 'README.md'
});
Package.onUse(function(api) {
api.versionsFrom('1.1.0.2');
api.use([
'meteor',
'underscore',
'coffeescript',
'http',
'practicalmeteor:loglevel@1.2.0_2',
'practicalmeteor:chai@2.1.0_1',
'hubaaa:easy-meteor-settings@0.1.1',
'hubaaa:json-pipes@0.1.1'
], 'server');
api.addFiles('EndpointPuller.coffee', 'server');
});
Package.onTest(function(api) {
api.use([
'underscore',
'coffeescript',
'practicalmeteor:mocha@2.1.0_3'
], 'server');
api.use('hubaaa:endpoint-puller@0.1.0', 'server');
api.addFiles('EndpointPullerTest.coffee', 'server');
});
| Package.describe({
name: 'hubaaa:endpoint-puller',
version: '0.1.0',
// Brief, one-line summary of the package.
summary: 'Pulls API endpoints, checking for new data and passing it through json pipes.',
// URL to the Git repository containing the source code for this package.
git: 'https://github.com/hubaaa/meteor-endpoint-puller',
// By default, Meteor will default to using README.md for documentation.
// To avoid submitting documentation, set this field to null.
documentation: 'README.md'
});
Package.onUse(function(api) {
api.versionsFrom('1.1.0.2');
api.use([
'meteor',
'underscore',
'coffeescript',
'http',
'practicalmeteor:loglevel@1.2.0_2',
'practicalmeteor:chai@2.1.0_1',
'hubaaa:easy-meteor-settings',
'hubaaa:json-pipes@0.1.1'
], 'server');
api.addFiles('EndpointPuller.coffee', 'server');
});
Package.onTest(function(api) {
api.use([
'underscore',
'coffeescript',
'practicalmeteor:mocha@2.1.0_3'
], 'server');
api.use('hubaaa:endpoint-puller@0.1.0', 'server');
api.addFiles('EndpointPullerTest.coffee', 'server');
});
|
[Feature] Create BucketList & BucketLists endpoints. | """This module runs the api server."""
import os
from app import flask_app, db
from app.models import User, BucketList, BucketListItem
from flask.ext.script import Manager, Shell
from flask.ext.migrate import Migrate, MigrateCommand
from flask.ext.restful import Resource, Api
from app.api_v1.resources import TestResource, \
BucketListsApi, BucketListApi, UserLogin, UserRegister
app = flask_app
api = Api(app=app, prefix='/api/v1.0')
manager = Manager(app)
migrate = Migrate(app, db)
# add resources
api.add_resource(TestResource, '/')
api.add_resource(BucketListsApi, '/bucketlists/')
api.add_resource(BucketListApi, '/bucketlists/<id>/')
api.add_resource(UserLogin, '/auth/login/')
api.add_resource(UserRegister, '/auth/register/')
def make_shell_context():
"""Add app, database and models to the shell."""
return dict(app=app, db=db, User=User, BucketList=BucketList,
BucketListItem=BucketListItem)
manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)
@manager.command
def run_tests():
"""Run tests."""
import unittest
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)
if __name__ == '__main__':
manager.run()
| """This module runs the api server."""
import os
from app import flask_app, db
from app.models import User, BucketList, BucketListItem
from flask.ext.script import Manager, Shell
from flask.ext.migrate import Migrate, MigrateCommand
from flask.ext.restful import Resource, Api
from app.api_v1.resources import TestResource, \
BucketListApi, UserLogin, UserRegister
app = flask_app
api = Api(app=app, prefix='/api/v1.0')
manager = Manager(app)
migrate = Migrate(app, db)
# add resources
api.add_resource(TestResource, '/')
api.add_resource(BucketListApi, '/bucketlists/')
api.add_resource(UserLogin, '/auth/login/')
api.add_resource(UserRegister, '/auth/register/')
def make_shell_context():
"""Add app, database and models to the shell."""
return dict(app=app, db=db, User=User, BucketList=BucketList,
BucketListItem=BucketListItem)
manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)
@manager.command
def run_tests():
"""Run tests."""
import unittest
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)
if __name__ == '__main__':
manager.run()
|
Add generated code in exe_module. | // GENERATED BY grunt make_dir_module.
export var dir = {};
export default dir;
import m0 from "wash/exe/cat";
dir["cat"] = m0;
import m1 from "wash/exe/clear";
dir["clear"] = m1;
import m2 from "wash/exe/cp";
dir["cp"] = m2;
import m3 from "wash/exe/echo";
dir["echo"] = m3;
import m4 from "wash/exe/eval";
dir["eval"] = m4;
import m5 from "wash/exe/import";
dir["import"] = m5;
import m6 from "wash/exe/ls";
dir["ls"] = m6;
import m7 from "wash/exe/mkdir";
dir["mkdir"] = m7;
import m8 from "wash/exe/mount.gdrive";
dir["mount.gdrive"] = m8;
import m9 from "wash/exe/mount";
dir["mount"] = m9;
import m10 from "wash/exe/mv";
dir["mv"] = m10;
import m11 from "wash/exe/pwd";
dir["pwd"] = m11;
import m12 from "wash/exe/readline";
dir["readline"] = m12;
import m13 from "wash/exe/rm";
dir["rm"] = m13;
import m14 from "wash/exe/touch";
dir["touch"] = m14;
import m15 from "wash/exe/wash";
dir["wash"] = m15;
| // GENERATED BY grunt make_dir_module.
export var dir = {};
export default dir;
import m0 from "wash/exe/cat";
dir["cat"] = m0;
import m1 from "wash/exe/clear";
dir["clear"] = m1;
import m2 from "wash/exe/cp";
dir["cp"] = m2;
import m3 from "wash/exe/echo";
dir["echo"] = m3;
import m4 from "wash/exe/import";
dir["import"] = m4;
import m5 from "wash/exe/ls";
dir["ls"] = m5;
import m6 from "wash/exe/mkdir";
dir["mkdir"] = m6;
import m7 from "wash/exe/mount.gdrive";
dir["mount.gdrive"] = m7;
import m8 from "wash/exe/mount";
dir["mount"] = m8;
import m9 from "wash/exe/mv";
dir["mv"] = m9;
import m10 from "wash/exe/pwd";
dir["pwd"] = m10;
import m11 from "wash/exe/readline";
dir["readline"] = m11;
import m12 from "wash/exe/rm";
dir["rm"] = m12;
import m13 from "wash/exe/touch";
dir["touch"] = m13;
import m14 from "wash/exe/wash";
dir["wash"] = m14;
|
Support usage when size = 0
I got an error when encoding an empty message (`{}`).
When the message is empty, the size is 0 and `slab` is null, so`slice.call(slab, offset, offset += size);` gave me
```
Uncaught TypeError: Method get TypedArray.prototype.subarray called on incompatible receiver null
```
Adding this solved the issue for me. Please correct me if I was using it all wrong. :joy: | "use strict";
module.exports = pool;
/**
* An allocator as used by {@link util.pool}.
* @typedef PoolAllocator
* @type {function}
* @param {number} size Buffer size
* @returns {Uint8Array} Buffer
*/
/**
* A slicer as used by {@link util.pool}.
* @typedef PoolSlicer
* @type {function}
* @param {number} start Start offset
* @param {number} end End offset
* @returns {Uint8Array} Buffer slice
* @this {Uint8Array}
*/
/**
* A general purpose buffer pool.
* @memberof util
* @function
* @param {PoolAllocator} alloc Allocator
* @param {PoolSlicer} slice Slicer
* @param {number} [size=8192] Slab size
* @returns {PoolAllocator} Pooled allocator
*/
function pool(alloc, slice, size) {
var SIZE = size || 8192;
var MAX = SIZE >>> 1;
var slab = null;
var offset = SIZE;
return function pool_alloc(size) {
if (size > MAX || size === 0)
return alloc(size);
if (offset + size > SIZE) {
slab = alloc(SIZE);
offset = 0;
}
var buf = slice.call(slab, offset, offset += size);
if (offset & 7) // align to 32 bit
offset = (offset | 7) + 1;
return buf;
};
}
| "use strict";
module.exports = pool;
/**
* An allocator as used by {@link util.pool}.
* @typedef PoolAllocator
* @type {function}
* @param {number} size Buffer size
* @returns {Uint8Array} Buffer
*/
/**
* A slicer as used by {@link util.pool}.
* @typedef PoolSlicer
* @type {function}
* @param {number} start Start offset
* @param {number} end End offset
* @returns {Uint8Array} Buffer slice
* @this {Uint8Array}
*/
/**
* A general purpose buffer pool.
* @memberof util
* @function
* @param {PoolAllocator} alloc Allocator
* @param {PoolSlicer} slice Slicer
* @param {number} [size=8192] Slab size
* @returns {PoolAllocator} Pooled allocator
*/
function pool(alloc, slice, size) {
var SIZE = size || 8192;
var MAX = SIZE >>> 1;
var slab = null;
var offset = SIZE;
return function pool_alloc(size) {
if (size > MAX)
return alloc(size);
if (offset + size > SIZE) {
slab = alloc(SIZE);
offset = 0;
}
var buf = slice.call(slab, offset, offset += size);
if (offset & 7) // align to 32 bit
offset = (offset | 7) + 1;
return buf;
};
}
|
Update git url and bump version to 0.1.1 | Package.describe({
name: 'hubaaa:easy-meteor-settings',
version: '0.1.1',
// Brief, one-line summary of the package.
summary: "Easily read deep values from Meteor.settings using 'a.b.c'",
// URL to the Git repository containing the source code for this package.
git: 'https://github.com/hubaaa/meteor-easy-meteor-settings',
// By default, Meteor will default to using README.md for documentation.
// To avoid submitting documentation, set this field to null.
documentation: 'README.md'
});
Package.onUse(function(api) {
api.versionsFrom('1.1.0.2');
api.use([
'meteor',
'underscore',
'coffeescript',
'practicalmeteor:loglevel@1.2.0_2',
'practicalmeteor:chai@2.1.0_1',
'practicalmeteor:underscore-deep@0.9.2'
]);
api.addFiles('namespace.coffee');
api.addFiles('EasyMeteorSettings.coffee');
});
Package.onTest(function(api) {
api.use([
'underscore',
'coffeescript',
'practicalmeteor:mocha@2.1.0_3'
]);
api.use('hubaaa:easy-meteor-settings@0.1.1');
api.addFiles('EasyMeteorSettingsTest.coffee');
});
| Package.describe({
name: 'hubaaa:easy-meteor-settings',
version: '0.1.0',
// Brief, one-line summary of the package.
summary: "Easily read deep values from Meteor.settings using 'a.b.c'",
// URL to the Git repository containing the source code for this package.
git: '',
// By default, Meteor will default to using README.md for documentation.
// To avoid submitting documentation, set this field to null.
documentation: 'README.md'
});
Package.onUse(function(api) {
api.versionsFrom('1.1.0.2');
api.use([
'meteor',
'underscore',
'coffeescript',
'practicalmeteor:loglevel@1.2.0_2',
'practicalmeteor:chai@2.1.0_1',
'practicalmeteor:underscore-deep@0.9.2'
]);
api.addFiles('namespace.coffee');
api.addFiles('EasyMeteorSettings.coffee');
});
Package.onTest(function(api) {
api.use([
'underscore',
'coffeescript',
'practicalmeteor:mocha@2.1.0_3'
]);
api.use('hubaaa:easy-meteor-settings@0.1.0');
api.addFiles('EasyMeteorSettingsTest.coffee');
});
|
Add a default option to predicate mapper | /*
* Copyright 2009-2014 Marcelo Guimarães
*
* 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 tools.devnull.trugger;
import java.util.function.Predicate;
/**
* Interface that maps something to a predicate inside a fluent interface.
*
* @since 5.0
*/
public interface PredicateMapper<T, R> {
/**
* Use the given condition to map the value.
*
* @param condition the condition to use
* @return a reference to the object for doing other mappings.
*/
R when(Predicate<T> condition);
/**
* Uses the mapped value as the default.
*
* @return a reference to the object for doing other mappings.
* @since 5.2
*/
R byDefault();
}
| /*
* Copyright 2009-2014 Marcelo Guimarães
*
* 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 tools.devnull.trugger;
import java.util.function.Predicate;
/**
* Interface that maps something to a predicate inside a fluent interface.
*
* @since 5.0
*/
public interface PredicateMapper<T, R> {
/**
* Use the given condition to map the value.
*
* @param condition the condition to use
* @return a reference to the object for doing other mappings.
*/
R when(Predicate<T> condition);
}
|
Create media file when it doesn't exist, use local copy when it does | package gitmediafilters
import (
".."
"../client"
"io"
"os"
)
func Smudge(writer io.Writer, sha string) error {
mediafile := gitmedia.LocalMediaPath(sha)
if stat, err := os.Stat(mediafile); err != nil || stat == nil {
reader, err := gitmediaclient.Get(mediafile)
if err != nil {
return &SmudgeError{sha, mediafile, err.Error()}
}
defer reader.Close()
mediaWriter, err := os.Create(mediafile)
if err != nil {
return &SmudgeError{sha, mediafile, err.Error()}
}
defer mediaWriter.Close()
if err := copyFile(reader, writer, mediaWriter); err != nil {
return &SmudgeError{sha, mediafile, err.Error()}
}
} else {
reader, err := os.Open(mediafile)
if err != nil {
return &SmudgeError{sha, mediafile, err.Error()}
}
defer reader.Close()
if err := copyFile(reader, writer); err != nil {
return &SmudgeError{sha, mediafile, err.Error()}
}
}
return nil
}
func copyFile(reader io.ReadCloser, writers ...io.Writer) error {
multiWriter := io.MultiWriter(writers...)
_, err := io.Copy(multiWriter, reader)
return err
}
type SmudgeError struct {
Sha string
Filename string
ErrorMessage string
}
func (e *SmudgeError) Error() string {
return e.ErrorMessage
}
| package gitmediafilters
import (
".."
"../client"
"io"
"os"
)
func Smudge(writer io.Writer, sha string) error { // stdout, sha
mediafile := gitmedia.LocalMediaPath(sha)
reader, err := gitmediaclient.Get(mediafile)
if err != nil {
return &SmudgeError{sha, mediafile, err.Error()}
}
defer reader.Close()
mediaWriter, err := os.Create(mediafile)
defer mediaWriter.Close()
if err != nil {
return &SmudgeError{sha, mediafile, err.Error()}
}
multiWriter := io.MultiWriter(writer, mediaWriter)
_, err = io.Copy(multiWriter, reader)
if err != nil {
return &SmudgeError{sha, mediafile, err.Error()}
}
return nil
}
type SmudgeError struct {
Sha string
Filename string
ErrorMessage string
}
func (e *SmudgeError) Error() string {
return e.ErrorMessage
}
|
Fix tiny typo in comment | <?php
namespace Nathiss\Bundle\QuoteGeneratorBundle\Repository;
/**
* QuoteRepository
*/
class QuoteRepository extends \Doctrine\ORM\EntityRepository
{
/**
* Selects Quote from DB randomly
*
* @return \Nathiss\Bundle\QuoteGenerateBundle\Entity\Quote
*/
public function findOneRandomly()
{
$count = $this->createQueryBuilder('q')
->select('COUNT(q)')
->getQuery()
->getSingleScalarResult();
return $this->createQueryBuilder('q')
->setFirstResult(rand(0, $count-1))
->setMaxResults(1)
->getQuery()
->getSingleResult();
}
}
| <?php
namespace Nathiss\Bundle\QuoteGeneratorBundle\Repository;
/**
* QuoteRepository
*/
class QuoteRepository extends \Doctrine\ORM\EntityRepository
{
/**
* Selects Query from DB randomly
*
* @return \Nathiss\Bundle\QuoteGenerateBundle\Entity\Quote
*/
public function findOneRandomly()
{
$count = $this->createQueryBuilder('q')
->select('COUNT(q)')
->getQuery()
->getSingleScalarResult();
return $this->createQueryBuilder('q')
->setFirstResult(rand(0, $count-1))
->setMaxResults(1)
->getQuery()
->getSingleResult();
}
}
|
Allow puphpet machine to see dev env | <?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;
// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);
// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
|| isset($_SERVER['HTTP_X_FORWARDED_FOR'])
|| !(in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', '10.0.2.2', '192.168.56.1', 'fe80::1', '::1')) || php_sapi_name() === 'cli-server')
) {
header('HTTP/1.0 403 Forbidden');
exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}
$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
Debug::enable();
require_once __DIR__.'/../app/AppKernel.php';
$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
| <?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;
// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);
// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
|| isset($_SERVER['HTTP_X_FORWARDED_FOR'])
|| !(in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', '10.0.2.2', 'fe80::1', '::1')) || php_sapi_name() === 'cli-server')
) {
header('HTTP/1.0 403 Forbidden');
exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}
$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
Debug::enable();
require_once __DIR__.'/../app/AppKernel.php';
$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
|
Fix checksum failure when reexecuting changesets with
dropNotNullConstraint
The checksum validation failed when a changeset containing a
<dropNotNullConstraint> change was processed for the second time.
The reason is that the statement generation (which only occurs when the
change
is really executed, i.e. the first time only) changes the value of the
schemaName field. The schemaName, however, is used for checksum
calculation. | package liquibase.change.ext;
import liquibase.change.ChangeMetaData;
import liquibase.change.DatabaseChange;
import liquibase.change.core.DropNotNullConstraintChange;
import liquibase.database.Database;
import liquibase.database.ext.HanaDBDatabase;
import liquibase.statement.SqlStatement;
import liquibase.statement.core.SetNullableStatement;
@DatabaseChange(name="dropNotNullConstraint", description = "Makes a column nullable", priority = ChangeMetaData.PRIORITY_DATABASE, appliesTo = "column", since = "3.0")
public class DropNotNullConstraintChangeHana extends
DropNotNullConstraintChange {
@Override
public boolean supports(Database database) {
return database instanceof HanaDBDatabase;
}
@Override
public SqlStatement[] generateStatements(Database database) {
// local variable introduced as superclass's schemaName is used for checksum calculation
// TODO: is this logic also needed for the inverse?
String schemaToUse = getSchemaName();
if (schemaToUse == null) {
schemaToUse = database.getDefaultSchemaName();
}
String columnDataTypeName = getColumnDataType();
if (columnDataTypeName == null && schemaToUse != null && database instanceof HanaDBDatabase) {
columnDataTypeName = ((HanaDBDatabase) database).getColumnDataTypeName(getCatalogName(), schemaToUse, getTableName(), getColumnName());
}
return new SqlStatement[] { new SetNullableStatement(
getCatalogName(),
schemaToUse,
getTableName(), getColumnName(), columnDataTypeName, true)
};
}
}
| package liquibase.change.ext;
import liquibase.change.ChangeMetaData;
import liquibase.change.DatabaseChange;
import liquibase.change.core.DropNotNullConstraintChange;
import liquibase.database.Database;
import liquibase.database.ext.HanaDBDatabase;
import liquibase.statement.SqlStatement;
import liquibase.statement.core.SetNullableStatement;
@DatabaseChange(name="dropNotNullConstraint", description = "Makes a column nullable", priority = ChangeMetaData.PRIORITY_DATABASE, appliesTo = "column", since = "3.0")
public class DropNotNullConstraintChangeHana extends
DropNotNullConstraintChange {
@Override
public boolean supports(Database database) {
return database instanceof HanaDBDatabase;
}
@Override
public SqlStatement[] generateStatements(Database database) {
if (getSchemaName() == null) {
setSchemaName(database.getDefaultSchemaName());
}
String columnDataTypeName = getColumnDataType();
if (columnDataTypeName == null && getSchemaName() != null && database instanceof HanaDBDatabase) {
columnDataTypeName = ((HanaDBDatabase) database).getColumnDataTypeName(getCatalogName(), getSchemaName(), getTableName(), getColumnName());
}
return new SqlStatement[] { new SetNullableStatement(
getCatalogName(),
getSchemaName(),
getTableName(), getColumnName(), columnDataTypeName, true)
};
}
}
|
Add default type to declarations | import {
CREATE_DECLARATION, REMOVE_DECLARATION, EDIT_DECLARATION
} from '../actions/declaration'
import {
LOAD_QUESTIONNAIRE_SUCCESS
} from '../actions/questionnaire'
import { DECLARATION_TYPE } from '../constants/pogues-constants'
const { INSTRUCTION } = DECLARATION_TYPE
const emptyDeclaration = {
type: INSTRUCTION,
disjoignable: true,
text: ''
}
export default function (state={}, action) {
const { type, payload } = action
switch (type) {
case CREATE_DECLARATION:
return {
...state,
[payload.id]: {
id: payload.id,
...emptyDeclaration,
}
}
case EDIT_DECLARATION:
return {
...state,
[payload.id]: {
...state[payload.id],
...payload.update
}
}
case REMOVE_DECLARATION:
const { [payload.id]: toRemove, ...toKeep } = state
return toKeep
case LOAD_QUESTIONNAIRE_SUCCESS:
return payload.update.declarationById
default:
return state
}
} | import {
CREATE_DECLARATION, REMOVE_DECLARATION, EDIT_DECLARATION
} from '../actions/declaration'
import {
LOAD_QUESTIONNAIRE_SUCCESS
} from '../actions/questionnaire'
const emptyDeclaration = {
type: '',
disjoignable: true,
text: ''
}
export default function (state={}, action) {
const { type, payload } = action
switch (type) {
case CREATE_DECLARATION:
return {
...state,
[payload.id]: {
id: payload.id,
...emptyDeclaration,
}
}
case EDIT_DECLARATION:
return {
...state,
[payload.id]: {
...state[payload.id],
...payload.update
}
}
case REMOVE_DECLARATION:
const { [payload.id]: toRemove, ...toKeep } = state
return toKeep
case LOAD_QUESTIONNAIRE_SUCCESS:
return payload.update.declarationById
default:
return state
}
} |
Make a copy of dicts before deleting things from them when printing. | import json
from base64 import b64encode
# http://stackoverflow.com/a/4256027/212555
def del_none(o):
"""
Delete keys with the value ``None`` in a dictionary, recursively.
This alters the input so you may wish to ``copy`` the dict first.
"""
if isinstance(o, dict):
d = o.copy()
else:
d = o.__dict__.copy()
for key, value in list(d.items()):
if value is None:
del d[key]
elif isinstance(value, dict):
del_none(value)
return d
def _to_json_dict(o):
if isinstance(o, bytes):
try:
return o.decode("ASCII")
except UnicodeError:
return b64encode(o)
if isinstance(o, set):
return list(o)
return o.__dict__
def to_json(o):
return json.dumps(del_none(o), default=_to_json_dict, indent=4)
| import json
from base64 import b64encode
# http://stackoverflow.com/a/4256027/212555
def del_none(o):
"""
Delete keys with the value ``None`` in a dictionary, recursively.
This alters the input so you may wish to ``copy`` the dict first.
"""
if isinstance(o, dict):
d = o
else:
d = o.__dict__
for key, value in list(d.items()):
if value is None:
del d[key]
elif isinstance(value, dict):
del_none(value)
return d
def _to_json_dict(o):
if isinstance(o, bytes):
try:
return o.decode("ASCII")
except UnicodeError:
return b64encode(o)
if isinstance(o, set):
return list(o)
return o.__dict__
def to_json(o):
return json.dumps(del_none(o), default=_to_json_dict, indent=4)
|
Add missing extension in import | import Map from '../../../src/ol/Map.js';
import View from '../../../src/ol/View.js';
import {Group as LayerGroup, Tile as TileLayer} from '../../../src/ol/layer.js';
import XYZ from '../../../src/ol/source/XYZ.js';
new Map({
target: 'map',
view: new View({
center: [0, 0],
zoom: 3
}),
layers: new LayerGroup({
opacity: 0.75,
layers: [
new TileLayer({
opacity: 0.25,
source: new XYZ({
url: '/data/tiles/satellite/{z}/{x}/{y}.jpg'
})
}),
new TileLayer({
source: new XYZ({
url: '/data/tiles/stamen-labels/{z}/{x}/{y}.png'
})
})
]
})
});
render();
| import Map from '../../../src/ol/Map.js';
import View from '../../../src/ol/View.js';
import {Group as LayerGroup, Tile as TileLayer} from '../../../src/ol/layer.js';
import XYZ from '../../../src/ol/source/XYZ';
new Map({
target: 'map',
view: new View({
center: [0, 0],
zoom: 3
}),
layers: new LayerGroup({
opacity: 0.75,
layers: [
new TileLayer({
opacity: 0.25,
source: new XYZ({
url: '/data/tiles/satellite/{z}/{x}/{y}.jpg'
})
}),
new TileLayer({
source: new XYZ({
url: '/data/tiles/stamen-labels/{z}/{x}/{y}.png'
})
})
]
})
});
render();
|
Add support for flash messages | <?php
namespace Framework;
class Controller {
private $app;
private $api;
function __construct($app){
$this->app = $app;
}
protected function setHeader($header, $value)
{
$this->app->response->headers->set($header, $value);
}
protected function setLayout($layout) {
$this->app->view->setLayout($layout);
}
protected function render($name, $data=array()) {
return $this->app->render($name, $data);
}
protected function flash($key, $value)
{
$this->app->flash($key, $value);
}
protected function redirect($url, $params=null) {
if ($params !== null) $url = $this->app->urlFor($url, $params);
return $this->app->redirect($url);
}
protected function params($name = null) {
return $this->app->request->params($name);
}
protected function urlFor($name, $params=array()) {
return $this->app->router->urlFor($name, $params);
}
protected function current_user() {
return $this->app->current_user;
}
protected function api() {
if (!isset($this->api)) {
$this->api = new \App\Lib\Api($_COOKIE['Token']);
}
return $this->api;
}
}
| <?php
namespace Framework;
class Controller {
private $app;
private $api;
function __construct($app){
$this->app = $app;
}
protected function setHeader($header, $value)
{
$this->app->response->headers->set($header, $value);
}
protected function setLayout($layout) {
$this->app->view->setLayout($layout);
}
protected function render($name, $data=array()) {
return $this->app->render($name, $data);
}
protected function redirect($url, $params=null) {
if ($params !== null) $url = $this->app->urlFor($url, $params);
return $this->app->redirect($url);
}
protected function params($name = null) {
return $this->app->request->params($name);
}
protected function urlFor($name, $params=array()) {
return $this->app->router->urlFor($name, $params);
}
protected function current_user() {
return $this->app->current_user;
}
protected function api() {
if (!isset($this->api)) {
$this->api = new \App\Lib\Api($_COOKIE['Token']);
}
return $this->api;
}
}
|
chore: Correct typo in pg_table_def create view query | package jp.ne.opt.redshiftfake.views;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Created by frankfarrell on 14/06/2018.
*
* Some system tables that exist in redshift do not necessarily exist in postgres
*
* This creates pg_tableef as a view on each connection if it does not exist
*/
public class SystemViews {
private static final String pgTableDefExistsQuery =
"SELECT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'pg_table_def')";
private static final String createPgTableDefView =
"CREATE VIEW pg_table_def (schemaname, tablename, \"column\", \"type\", \"encoding\", distkey, sortkey, \"notnull\") " +
"AS SELECT table_schema, table_name, column_name, data_type, 'none', false, 0, CASE is_nullable WHEN 'yes' THEN false ELSE true END " +
"FROM information_schema.columns;";
public static void create(final Connection connection) throws SQLException {
final ResultSet resultSet = connection.createStatement().executeQuery(pgTableDefExistsQuery);
if(resultSet.next() && !resultSet.getBoolean(1)){
connection.createStatement().execute(createPgTableDefView);
}
}
}
| package jp.ne.opt.redshiftfake.views;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Created by ffarrell on 14/06/2018.
*
* Some system tables that exist in redshift do not necessarily exist in postgres
*
* This creates pg_tableef as a view on each connection if it does not exist
*/
public class SystemViews {
private static final String createPgTableDefView =
"CREATE VIEW pg_table_def (schemaname, tablename, \"column\", \"type\", \"encoding\", distkey, sortkey, \"notnull\") " +
"AS SELECT table_schema, table_name, column_name, data_type, 'none', false, 0, CASE is_nullable WHEN 'yes' THEN false ELSE true END " +
"FROM information_schema.columns;";
public static void create(final Connection connection) throws SQLException {
final ResultSet resultSet = connection.createStatement().executeQuery("SELECT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'pg_tab_def')");
if(resultSet.next() && !resultSet.getBoolean(1)){
connection.createStatement().execute(createPgTableDefView);
}
}
}
|
Support user-defined convenience package names | package gogist
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
)
const t = `
<html>
<head>
<meta name="go-import" content="%s git https://gist.github.com/%s.git" />
<script>window.location='https://github.com/ImJasonH/go-gist/';</script>
</head>
</html>
`
func init() {
r := mux.NewRouter()
h := func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
w.Write([]byte(fmt.Sprintf(t, r.URL.Host+r.URL.Path, mux.Vars(r)["gistID"])))
}
r.HandleFunc("/{username}/{gistID:[0-9]+}", h).Methods("GET")
r.HandleFunc("/{username}/{gistID:[0-9]+}/{package:[a-zA-Z0-9]+}", h).Methods("GET")
r.HandleFunc("/{gistID:[0-9]+}", h).Methods("GET")
r.HandleFunc("/{gistID:[0-9]+}/{package:[a-zA-Z0-9]+}", h).Methods("GET")
r.Handle("/", http.RedirectHandler("https://github.com/ImJasonH/go-gist", http.StatusSeeOther))
http.Handle("/", r)
}
| package gogist
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
)
const t = `
<html>
<head>
<meta name="go-import" content="%s git https://gist.github.com/%s.git" />
<script>window.location='https://github.com/ImJasonH/go-gist/';</script>
</head>
</html>
`
func init() {
r := mux.NewRouter()
h := func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
w.Write([]byte(fmt.Sprintf(t, r.URL.Host+r.URL.Path, mux.Vars(r)["gistID"])))
}
r.HandleFunc("/{username}/{gistID:[0-9]+}", h).Methods("GET")
r.HandleFunc("/{gistID:[0-9]+}", h).Methods("GET")
r.Handle("/", http.RedirectHandler("https://github.com/ImJasonH/go-gist", http.StatusSeeOther))
http.Handle("/", r)
}
|
Use if-elif instead of multiple if statements to check types
Use if-elif instead of multiple if statements to check types when converting from MongoDB BaseDict and BaseList to python dict and list types. Once the value is converted, use another if-elif block to recursively evaluate and convert the values of dict and list. | # Copyright 2019 Extreme Networks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
import mongoengine
import six
def mongodb_to_python_types(value):
# Convert MongoDB BaseDict and BaseList types to python dict and list types.
if isinstance(value, mongoengine.base.datastructures.BaseDict):
value = dict(value)
elif isinstance(value, mongoengine.base.datastructures.BaseList):
value = list(value)
# Recursively traverse the dict and list to convert values.
if isinstance(value, dict):
value = {k: mongodb_to_python_types(v) for k, v in six.iteritems(value)}
elif isinstance(value, list):
value = [mongodb_to_python_types(v) for v in value]
return value
| # Copyright 2019 Extreme Networks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
import mongoengine
import six
def mongodb_to_python_types(value):
if isinstance(value, mongoengine.base.datastructures.BaseDict):
value = dict(value)
if isinstance(value, mongoengine.base.datastructures.BaseList):
value = list(value)
if isinstance(value, dict):
value = {k: mongodb_to_python_types(v) for k, v in six.iteritems(value)}
if isinstance(value, list):
value = [mongodb_to_python_types(v) for v in value]
return value
|
Use alt thumb for front page tysky block
if set | <?php
$meta = get_post_meta($post->ID);
?>
<a href="<?php the_permalink() ?>">
<article <?php post_class('margin-bottom-small'); ?> id="post-<?php the_ID(); ?>">
<?php
if (!empty($meta['_cmb_alt_thumb_id'])) {
echo wp_get_attachment_image($meta['_cmb_alt_thumb_id'][0], 'col6-16to9', false, array('class' => 'margin-bottom-micro only-desktop'));
echo wp_get_attachment_image($meta['_cmb_alt_thumb_id'][0], 'mobile-16to9', false, array('class' => 'only-mobile'));
} else {
the_post_thumbnail('col6-16to9', array('class' => 'margin-bottom-micro only-desktop'));
the_post_thumbnail('mobile-16to9', array('class' => 'only-mobile'));
}
?>
<?php
$sub_category = get_the_sub_category($post->ID);
if ($sub_category) {
?>
<h4 class="font-small-caps"><?php echo $sub_category; ?></h4>
<?php
}
?>
<h5 class="js-fix-widows"><?php the_title(); ?></h5>
</article>
</a> | <?php
$meta = get_post_meta($post->ID);
?>
<a href="<?php the_permalink() ?>">
<article <?php post_class('margin-bottom-small'); ?> id="post-<?php the_ID(); ?>">
<?php the_post_thumbnail('col6-16to9', array('class' => 'margin-bottom-micro only-desktop')); ?>
<?php the_post_thumbnail('mobile-16to9', array('class' => 'only-mobile')); ?>
<?php
$sub_category = get_the_sub_category($post->ID);
if ($sub_category) {
?>
<h4 class="font-small-caps"><?php echo $sub_category; ?></h4>
<?php
}
?>
<h5 class="js-fix-widows"><?php the_title(); ?></h5>
</article>
</a> |
Fix xml declaration not parsed | <?php
if(!function_exists('wp_bootstrap_the_content')) {
function wp_bootstrap_the_content($content) {
$html = new DOMDocument();
@$html->loadHTML('<?xml encoding="utf-8" ?>' . $content );
$image_nodes = $html->getElementsByTagName( 'img' );
foreach ($image_nodes as $image_node) {
$class = $image_node->getAttribute('class');
if (strpos($class, 'alignleft') !== false) {
$class.= " pull-left";
}
if (strpos($class, 'alignright') !== false) {
$class.= " pull-right";
}
if (strpos($class, 'aligncenter') !== false) {
$class.= " center-block";
}
$image_node->setAttribute('class', $class);
}
return preg_replace('~(?:<\?[^>]*>|<(?:!DOCTYPE|/?(?:html|head|body))[^>]*>)\s*~i', '', $html->saveHTML());
}
}
?> | <?php
if(!function_exists('wp_bootstrap_the_content')) {
function wp_bootstrap_the_content($content) {
$html = new DOMDocument();
@$html->loadHTML('<?xml encoding="utf-8" ?>' . $content );
$image_nodes = $html->getElementsByTagName( 'img' );
foreach ($image_nodes as $image_node) {
$class = $image_node->getAttribute('class');
if (strpos($class, 'alignleft') !== false) {
$class.= " pull-left";
}
if (strpos($class, 'alignright') !== false) {
$class.= " pull-right";
}
if (strpos($class, 'aligncenter') !== false) {
$class.= " center-block";
}
$image_node->setAttribute('class', $class);
}
return preg_replace('/^<!DOCTYPE.+?>/', '', str_replace( array('<html>', '</html>', '<body>', '</body>'), array('', '', '', ''), $html->saveHTML()));
}
}
?> |
Use table instead of separate lines | import string
import textwrap
from veryprettytable import VeryPrettyTable
from plugins import BasePlugin
__author__ = 'peter'
class BasicInfoPlugin(BasePlugin):
name = 'BasicInfoPlugin'
short_description = 'Basic info:'
default = True
description = textwrap.dedent('''
This plugin provides some basic info about the string such as:
- Length
- Presence of alpha/digits/raw bytes
''')
def handle(self):
result = ''
for s in self.args['STRING']:
if len(self.args['STRING']) > 1:
result += '{0}:\n'.format(s)
table = VeryPrettyTable()
table.field_names = ['Length', '# Digits', '# Alpha', '# unprintable']
table.add_row((len(s), sum(x.isdigit() for x in s), sum(x.isalpha() for x in s),
sum(x in string.printable for x in s)))
result += str(table) + '\n'
return result | import string
import textwrap
from plugins import BasePlugin
__author__ = 'peter'
class BasicInfoPlugin(BasePlugin):
name = 'BasicInfoPlugin'
short_description = 'Basic info:'
default = True
description = textwrap.dedent('''
This plugin provides some basic info about the string such as:
- Length
- Presence of alpha/digits/raw bytes
''')
def handle(self):
result = ''
for s in self.args['STRING']:
if len(self.args['STRING']) > 1:
result += '{0}:\n'.format(s)
result += 'len: {0}\n'.format(len(s))
result += 'number of digits: {0}\n'.format(sum(x.isdigit() for x in s))
result += 'number of alpha: {0}\n'.format(sum(x.isalpha() for x in s))
result += 'number of unprintable: {0}\n'.format(sum(x in string.printable for x in s))
return result |
Allow indexing blank country field | from haystack.indexes import SearchIndex, CharField, MultiValueField, BooleanField
from haystack import site
from .models import MuseumObject
class MuseumObjectIndex(SearchIndex):
text = CharField(document=True, use_template=True)
categories = MultiValueField(faceted=True)
item_name = CharField(model_attr='artefact_type', faceted=True)
global_region = CharField(model_attr='global_region', faceted=True)
country = CharField(model_attr='country', faceted=True, default='')
people = MultiValueField(faceted=True)
has_images = BooleanField(faceted=True)
def prepare_categories(self, object):
return [unicode(cat) for cat in object.category.all()]
def prepare_people(self, object):
people = set()
if object.maker:
people.add(unicode(object.maker))
people.add(unicode(object.donor))
people.add(unicode(object.collector))
return list(people)
def prepare_has_images(self, object):
return object.artefactrepresentation_set.exists()
def get_model(self):
return MuseumObject
def index_queryset(self):
"""
Used when the entire index for model is updated.
"""
### TODO ###
# Ignore private/reserved etc objects
return self.get_model().objects.all()
site.register(MuseumObject, MuseumObjectIndex)
| from haystack.indexes import SearchIndex, CharField, MultiValueField, BooleanField
from haystack import site
from .models import MuseumObject
class MuseumObjectIndex(SearchIndex):
text = CharField(document=True, use_template=True)
categories = MultiValueField(faceted=True)
item_name = CharField(model_attr='artefact_type', faceted=True)
global_region = CharField(model_attr='global_region', faceted=True)
country = CharField(model_attr='country', faceted=True)
people = MultiValueField(faceted=True)
has_images = BooleanField(faceted=True)
def prepare_categories(self, object):
return [unicode(cat) for cat in object.category.all()]
def prepare_people(self, object):
people = set()
if object.maker:
people.add(unicode(object.maker))
people.add(unicode(object.donor))
people.add(unicode(object.collector))
return list(people)
def prepare_has_images(self, object):
return object.artefactrepresentation_set.exists()
def get_model(self):
return MuseumObject
def index_queryset(self):
"""
Used when the entire index for model is updated.
"""
### TODO ###
# Ignore private/reserved etc objects
return self.get_model().objects.all()
site.register(MuseumObject, MuseumObjectIndex)
|
Disable icon temporarily and adjust the debug print statements | import gntp
import Growl
class GNTPRegister(gntp.GNTPRegister):
def send(self):
print 'Sending Local Registration'
growl = Growl.GrowlNotifier(
applicationName = self.headers['Application-Name'],
notifications = self.notifications,
defaultNotifications = self.defaultNotifications,
)
growl.register()
class GNTPNotice(gntp.GNTPNotice):
def send(self):
print 'Sending Local Notification'
growl = Growl.GrowlNotifier(
applicationName = self.headers['Application-Name'],
notifications = [self.headers['Notification-Name']]
)
noticeIcon = None
if self.headers.get('Notification-Icon',False):
resource = self.headers['Notification-Icon'].split('://')
#print resource
resource = self.resources.get(resource[1],False)
#print resource
if resource:
noticeIcon = resource['Data']
growl.notify(
noteType = self.headers['Notification-Name'],
title = self.headers['Notification-Title'],
description=self.headers['Notification-Text'],
) | import gntp
import Growl
class GNTPRegister(gntp.GNTPRegister):
def send(self):
print 'Sending Registration'
growl = Growl.GrowlNotifier(
applicationName = self.headers['Application-Name'],
notifications = self.notifications,
defaultNotifications = self.defaultNotifications,
)
growl.register()
class GNTPNotice(gntp.GNTPNotice):
def send(self):
print 'Sending Notification'
growl = Growl.GrowlNotifier(
applicationName = self.headers['Application-Name'],
notifications = [self.headers['Notification-Name']]
)
noticeIcon = None
if self.headers.get('Notification-Icon',False):
resource = self.headers['Notification-Icon'].split('://')
#print resource
resource = self.resources.get(resource[1],False)
#print resource
if resource:
noticeIcon = resource['Data']
growl.notify(
noteType = self.headers['Notification-Name'],
title = self.headers['Notification-Title'],
description=self.headers['Notification-Text'],
icon=noticeIcon
) |
Unify variable names in components(junit5-spring) | /*
* (C) Copyright 2017 Boni Garcia (http://bonigarcia.github.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.github.bonigarcia;
import org.springframework.stereotype.Component;
@Component
public class MessageComponent {
private MessageService messageService;
public MessageComponent(MessageService messageService) {
this.messageService = messageService;
}
public String getMessage() {
return messageService.getMessage();
}
} | /*
* (C) Copyright 2017 Boni Garcia (http://bonigarcia.github.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.github.bonigarcia;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class MessageComponent {
@Autowired
private MessageService service;
public String getMessage() {
return service.getMessage();
}
} |
Disable all timing output in production for now | // These are the primary log levels.
// Your logger object has a method for each of these.
var LOG_LEVELS = {
emergency : 7,
alert : 6,
critical : 5,
error : 4,
warning : 3,
notice : 2,
info : 1,
debug : 0,
}
// Need these to be shared across triton and corvair (can actually be modified
// by the logging modules).
var config = (global._TRITON_CONFIG || (global._TRITON_CONFIG = {
main: {
baseLevel: 'error',
levels: LOG_LEVELS,
colors: {
emergency : 'red',
alert : 'red',
critical : 'red',
error : 'red',
warning : 'yellow',
notice : 'yellow',
info : 'green',
debug : 'blue',
},
},
// This config is for an internal logger used by the `time` method.
stats: {
// TODO: Some day, when slow times are rare, we should set
// this to 'slow' in production to surface performance issues.
baseLevel: 'none',
levels: {
none: 3, // Not used. Disables in production.
slow: 2,
fine: 1,
fast: 0,
},
colors: {
slow: 'red',
fine: 'yellow',
fast: 'green',
},
},
}));
module.exports = { config };
| // These are the primary log levels.
// Your logger object has a method for each of these.
var LOG_LEVELS = {
emergency : 7,
alert : 6,
critical : 5,
error : 4,
warning : 3,
notice : 2,
info : 1,
debug : 0,
}
// Need these to be shared across triton and corvair (can actually be modified
// by the logging modules).
var config = (global._TRITON_CONFIG || (global._TRITON_CONFIG = {
main: {
baseLevel: 'error',
levels: LOG_LEVELS,
colors: {
emergency : 'red',
alert : 'red',
critical : 'red',
error : 'red',
warning : 'yellow',
notice : 'yellow',
info : 'green',
debug : 'blue',
},
},
// This config is for an internal logger used by the `time` method.
stats: {
baseLevel: 'slow',
levels: {
slow: 2,
fine: 1,
fast: 0,
},
colors: {
slow: 'red',
fine: 'yellow',
fast: 'green',
},
},
}));
module.exports = { config };
|
Fix ajax request in Stimulus maps controller | import {Controller} from "stimulus"
export default class extends Controller {
static targets = ["mapInfo"]
connect() {
const courseId = this.mapInfoTarget.dataset.courseId;
const splitId = this.mapInfoTarget.dataset.splitId;
Rails.ajax({
url: "/api/v1/courses/" + courseId,
type: "GET",
success: function (data) {
const attributes = data.data.attributes;
var locations = null;
if(splitId === undefined) {
locations = attributes.locations;
} else {
locations = attributes.locations.filter(function(e) {
return e.id === parseInt(splitId)
})
}
const trackPoints = attributes.trackPoints;
gmap_show(locations, trackPoints);
}
})
}
}
| import {Controller} from "stimulus"
export default class extends Controller {
static targets = ["mapInfo"]
connect() {
const courseId = this.mapInfoTarget.dataset.courseId;
const splitId = this.mapInfoTarget.dataset.splitId;
Rails.ajax({
url: "/courses/" + courseId + '.json',
type: "GET",
success: function (data) {
const attributes = data.data.attributes;
var locations = null;
if(splitId === undefined) {
locations = attributes.locations;
} else {
locations = attributes.locations.filter(function(e) {
return e.id === parseInt(splitId)
})
}
const trackPoints = attributes.trackPoints;
gmap_show(locations, trackPoints);
}
})
}
}
|
Allow config access to app object | #! /usr/bin/env python3
from functools import partial
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
app = Flask("odie", template_folder='admin/templates', static_folder='admin/static')
import config # pylint: disable=unused-import
app.config.from_object('config.FlaskConfig')
if app.config['DEBUG']:
# allow requests from default broccoli server port
from flask.ext.cors import CORS
CORS(app, origins=['http://localhost:4200'], supports_credentials=True)
sqla = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.setup_app(app)
def __unauthorized():
raise ClientError("unauthorized", status=401)
login_manager.unauthorized_handler(__unauthorized)
# sqlalchemy treats columns as nullable by default, which we don't want.
Column = partial(sqla.Column, nullable=False)
# errors that will be reported to the client
class ClientError(Exception):
def __init__(self, *errors, status=400):
super().__init__()
self.errors = errors
self.status = status
| #! /usr/bin/env python3
import config # pylint: disable=unused-import
from functools import partial
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
app = Flask("odie", template_folder='admin/templates', static_folder='admin/static')
app.config.from_object('config.FlaskConfig')
if app.config['DEBUG']:
# allow requests from default broccoli server port
from flask.ext.cors import CORS
CORS(app, origins=['http://localhost:4200'], supports_credentials=True)
sqla = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.setup_app(app)
def __unauthorized():
raise ClientError("unauthorized", status=401)
login_manager.unauthorized_handler(__unauthorized)
# sqlalchemy treats columns as nullable by default, which we don't want.
Column = partial(sqla.Column, nullable=False)
# errors that will be reported to the client
class ClientError(Exception):
def __init__(self, *errors, status=400):
super().__init__()
self.errors = errors
self.status = status
|
Change MIME-type for JSON-LD graph query responses
- Addresses EBISPOT/lodestar#25 upstream and HHS/meshrdf#91 downstream | package uk.ac.ebi.fgpt.lode.utils;
/**
* @author Simon Jupp
* @date 21/02/2013
* Functional Genomics Group EMBL-EBI
*/
public enum GraphQueryFormats {
RDFXML ("RDF/XML", "application/rdf+xml"),
N3 ("N3", "application/rdf+n3"),
JSON ("JSON-LD", "application/ld+json"),
TURTLE ("TURTLE", "text/turtle");
private final String format;
private final String mimetype;
private GraphQueryFormats(final String format, final String mimetype) {
this.format = format;
this.mimetype = mimetype;
}
@Override
public String toString() {
return format;
}
public String toMimeType() {
return mimetype;
}
}
| package uk.ac.ebi.fgpt.lode.utils;
/**
* @author Simon Jupp
* @date 21/02/2013
* Functional Genomics Group EMBL-EBI
*/
public enum GraphQueryFormats {
RDFXML ("RDF/XML", "application/rdf+xml"),
N3 ("N3", "application/rdf+n3"),
JSON ("JSON-LD", "application/rdf+json"),
TURTLE ("TURTLE", "text/turtle");
private final String format;
private final String mimetype;
private GraphQueryFormats(final String format, final String mimetype) {
this.format = format;
this.mimetype = mimetype;
}
@Override
public String toString() {
return format;
}
public String toMimeType() {
return mimetype;
}
}
|
Make JS observation on 'change notice period' form live.
Now our JavaScript can still catch events even when the form
elements are added to the DOM after page load. | // Place all the behaviors and hooks related to the matching controller here.
// All this logic will automatically be available in application.js.
$(document).ready(function () {
$(document).on('change', '#change_meeting_notice_period_resolution_meeting_notice_period', function() {
var currentMeetingNoticePeriod = parseInt($('span.meeting_notice_period').first().text(), 10);
var newMeetingNoticePeriod = parseInt(this.value, 10);
if (newMeetingNoticePeriod >= currentMeetingNoticePeriod) {
$('.increase_meeting_notice_period').slideDown();
$('.decrease_meeting_notice_period').slideUp();
} else {
$('.increase_meeting_notice_period').slideUp();
$('.decrease_meeting_notice_period').slideDown();
}
});
$('#change_meeting_notice_period_resolution_pass_immediately').change(function () {
if ($('#change_meeting_notice_period_resolution_pass_immediately:checked').val() == '1') {
$('.pass_immediately_true').show();
$('.pass_immediately_false').hide();
} else {
$('.pass_immediately_true').hide();
$('.pass_immediately_false').show();
}
});
});
| // Place all the behaviors and hooks related to the matching controller here.
// All this logic will automatically be available in application.js.
$(document).ready(function () {
var currentMeetingNoticePeriod = parseInt($('span.meeting_notice_period').first().text());
$('#change_meeting_notice_period_resolution_meeting_notice_period').observe_field(1, function () {
var newMeetingNoticePeriod = parseInt(this.value);
if (newMeetingNoticePeriod >= currentMeetingNoticePeriod) {
$('.increase_meeting_notice_period').slideDown();
$('.decrease_meeting_notice_period').slideUp();
} else {
$('.increase_meeting_notice_period').slideUp();
$('.decrease_meeting_notice_period').slideDown();
}
});
$('#change_meeting_notice_period_resolution_pass_immediately').change(function () {
if ($('#change_meeting_notice_period_resolution_pass_immediately:checked').val() == '1') {
$('.pass_immediately_true').show();
$('.pass_immediately_false').hide();
} else {
$('.pass_immediately_true').hide();
$('.pass_immediately_false').show();
}
});
});
|
cmd/table: Change interface to search nodes by role. | // Chef client command-line tool.
package main
import (
"flag"
"fmt"
"os"
"github.com/marpaia/chef-golang"
"github.com/shurcooL/go-goon"
)
var _ = goon.Dump
func chefConnect() *chef.Chef {
c, err := chef.Connect()
if err != nil {
panic(err)
}
c.SSLNoVerify = true
return c
}
func main() {
flag.Parse()
args := flag.Args()
switch {
case len(args) == 1:
c := chefConnect()
results, err := c.Search("node", "role:"+args[0])
if err != nil {
panic(err)
}
//fmt.Println(results.Total)
for _, row := range results.Rows {
row := row.(map[string]interface{})
fmt.Println(row["name"])
}
/*case false:
c := chefConnect()
nodes, err := c.GetNodes()
if err != nil {
panic(err)
}
goon.DumpExpr(nodes)*/
default:
flag.PrintDefaults()
os.Exit(2)
}
}
| // Chef client command-line tool.
package main
import (
"flag"
"fmt"
"os"
"github.com/marpaia/chef-golang"
"github.com/shurcooL/go-goon"
)
var _ = goon.Dump
func chefConnect() *chef.Chef {
c, err := chef.Connect()
if err != nil {
panic(err)
}
c.SSLNoVerify = true
return c
}
func main() {
flag.Parse()
args := flag.Args()
switch {
case len(args) == 3 && args[0] == "search":
c := chefConnect()
results, err := c.Search(args[1], args[2])
if err != nil {
panic(err)
}
//fmt.Println(results.Total)
for _, row := range results.Rows {
row := row.(map[string]interface{})
fmt.Println(row["name"])
}
/*case false:
c := chefConnect()
nodes, err := c.GetNodes()
if err != nil {
panic(err)
}
goon.DumpExpr(nodes)*/
default:
flag.PrintDefaults()
os.Exit(2)
}
}
|
Change to promise for Wit runactions | 'use strict';
const config = require('../../config');
const Facebook = require('../../app/services/facebook');
const sessions = require('../../app/services/sessions');
module.exports = {
get: (req, reply) => {
if (req.query['hub.verify_token'] === config.Facebook.verifyToken) {
return reply(req.query['hub.challenge']);
}
return reply('Error, wrong validation token');
},
post: (req, reply) => {
const witClient = req.server.plugins['keepr-bot'].witClient;
const messaging = Facebook.getFirstMessagingEntry(req.payload);
console.log(messaging);
if (messaging && messaging.message) {
const msg = messaging.message.text;
console.log('Message: ' + msg);
const sender = messaging.sender.id;
const sessionId = sessions.findOrCreateSession(sender);
const session = sessions.getSessions()[sessionId];
witClient.runActions(sessionId, msg, session.context).then((context) => {
console.log(context);
session.context = context;
}).catch((err) => {
console.log(err);
});
}
reply('Accepted').code(200)
}
};
| 'use strict';
const config = require('../../config');
const Facebook = require('../../app/services/facebook');
const sessions = require('../../app/services/sessions');
module.exports = {
get: (req, reply) => {
if (req.query['hub.verify_token'] === config.Facebook.verifyToken) {
return reply(req.query['hub.challenge']);
}
return reply('Error, wrong validation token');
},
post: (req, reply) => {
const witClient = req.server.plugins['keepr-bot'].witClient;
const messaging = Facebook.getFirstMessagingEntry(req.payload);
console.log(messaging);
if (messaging && messaging.message) {
const msg = messaging.message.text;
console.log('Message: ' + msg);
const sender = messaging.sender.id;
const sessionId = sessions.findOrCreateSession(sender);
witClient.runActions(sessionId, msg, sessions.getSessions()[sessionId].context,
(error, context) => {
if (error) {
console.log(error);
}
console.log(context);
sessions.getSessions()[sessionId].context = context;
});
}
reply('Accepted').code(200)
}
};
|
Increase version 3.1.6 -> 3.1.7 | #!/usr/bin/env python
from setuptools import setup, find_packages # This setup relies on setuptools since distutils is insufficient and badly hacked code
version = '3.1.7'
author = 'Yannick Dieter, David-Leon Pohl, Jens Janssen'
author_email = 'dieter@physik.uni-bonn.de, pohl@physik.uni-bonn.de, janssen@physik.uni-bonn.de'
# requirements for core functionality from requirements.txt
with open('requirements.txt') as f:
install_requires = f.read().splitlines()
setup(
name='pixel_clusterizer',
version=version,
description='A fast, generic, and easy to use clusterizer to cluster hits of a pixel matrix in Python.',
url='https://github.com/SiLab-Bonn/pixel_clusterizer',
license='GNU LESSER GENERAL PUBLIC LICENSE Version 2.1',
long_description='',
author=author,
maintainer=author,
author_email=author_email,
maintainer_email=author_email,
install_requires=install_requires,
packages=find_packages(),
include_package_data=True, # accept all data files and directories matched by MANIFEST.in or found in source control
package_data={'': ['README.*', 'VERSION'], 'docs': ['*'], 'examples': ['*']},
keywords=['cluster', 'clusterizer', 'pixel'],
python_requires='>=2.7',
platforms='any'
)
| #!/usr/bin/env python
from setuptools import setup, find_packages # This setup relies on setuptools since distutils is insufficient and badly hacked code
version = '3.1.6.dev0'
author = 'David-Leon Pohl, Jens Janssen'
author_email = 'pohl@physik.uni-bonn.de, janssen@physik.uni-bonn.de'
# requirements for core functionality from requirements.txt
with open('requirements.txt') as f:
install_requires = f.read().splitlines()
setup(
name='pixel_clusterizer',
version=version,
description='A fast, generic, and easy to use clusterizer to cluster hits of a pixel matrix in Python.',
url='https://github.com/SiLab-Bonn/pixel_clusterizer',
license='GNU LESSER GENERAL PUBLIC LICENSE Version 2.1',
long_description='',
author=author,
maintainer=author,
author_email=author_email,
maintainer_email=author_email,
install_requires=install_requires,
packages=find_packages(),
include_package_data=True, # accept all data files and directories matched by MANIFEST.in or found in source control
package_data={'': ['README.*', 'VERSION'], 'docs': ['*'], 'examples': ['*']},
keywords=['cluster', 'clusterizer', 'pixel'],
python_requires='>=2.7',
platforms='any'
)
|
Add comments to HTTPError interface
This can be very confusing potentially | package errors
import "fmt"
type HttpError interface {
error
StatusCode() int // actual HTTP status code
ErrorCode() string // error code returned in response body from CC or UAA
Headers() string // see: known_error_codes.go
Body() string
}
type httpError struct {
statusCode int
headers string
body string
code string
description string
}
type HttpNotFoundError struct {
*httpError
}
func NewHttpError(statusCode int, header string, body string, code string, description string) HttpError {
err := httpError{
statusCode: statusCode,
headers: header,
body: body,
code: code,
description: description,
}
switch statusCode {
case 404:
return HttpNotFoundError{&err}
default:
return &err
}
}
func (err *httpError) StatusCode() int {
return err.statusCode
}
func (err *httpError) Headers() string {
return err.headers
}
func (err *httpError) Body() string {
return err.body
}
func (err *httpError) Error() string {
return fmt.Sprintf(
"Server error, status code: %d, error code: %s, message: %s",
err.statusCode,
err.code,
err.description,
)
}
func (err *httpError) ErrorCode() string {
return err.code
}
| package errors
import "fmt"
type HttpError interface {
Error
StatusCode() int
Headers() string
Body() string
}
type httpError struct {
statusCode int
headers string
body string
code string
description string
}
type HttpNotFoundError struct {
*httpError
}
func NewHttpError(statusCode int, header string, body string, code string, description string) HttpError {
err := httpError{
statusCode: statusCode,
headers: header,
body: body,
code: code,
description: description,
}
switch statusCode {
case 404:
return HttpNotFoundError{&err}
default:
return &err
}
}
func (err *httpError) StatusCode() int {
return err.statusCode
}
func (err *httpError) Headers() string {
return err.headers
}
func (err *httpError) Body() string {
return err.body
}
func (err *httpError) Error() string {
return fmt.Sprintf(
"Server error, status code: %d, error code: %s, message: %s",
err.statusCode,
err.code,
err.description,
)
}
func (err *httpError) ErrorCode() string {
return err.code
}
|
Fix bug when saving users in mailing list | <?php
// fetch email addresses and remove duplicates
$emails = Lista::remove_duplicates_from($_POST['email_addresses']);
/* Saves users in the list.
* @param $list_id the ID of the mailing list you want to save the users to.
* @param $emails an array of unique emails.
*/
foreach ($emails as $email) {
$_user_is_empty = empty($email);
$_user_already_exists = User::findByEmail($email);
if ($_user_is_empty) {
echo "<p>$email cannot be added because it's empty.</p>";
}
else if ($_user_already_exists) {
// then don't insert it.
echo "<p>$email cannot be added to the list because it already exists in another list.</p>";
} else {
// let's create the user.
if (User::create($email, '', $list_id)) {
echo "<p><b>$email</b> successfully added to the list.";
} else {
echo "<p><b>$email</b> hasn't been created because of an unknown error. Sorry.</p>";
}
}
}
| <?php
// fetch email addresses and remove duplicates
$emails = Lista::remove_duplicates_from($_POST['email_addresses']);
/* Saves users in the list.
* @param $list_id the ID of the mailing list you want to save the users to.
* @param $emails an array of unique emails.
*
*/
foreach ($emails as $email) {
if ( !empty($email) && User::findByEmail($email) == false ) { // user doesn't exist yet
if ( User::create($email) ) {
echo "<p><b>$email</b> aggiunto con successo alla lista <b>{$_POST['name']}</b>.";
}
else {
// Probabilmente fallisce perche` e` gia` nel db.
echo "<p>ERRORE durante l'inserimento di <b>$email</b>.";
}
}
}
// Setto la list_id all'id della lista corrente, cosi' l'aggiunta e' completa
$update_list_id = $db->prepare("UPDATE users SET list_id = $list_id WHERE list_id <= 0");
$update_list_id->execute();
|
Add date in log format | """Provide all package executables
"""
import logging
from docopt import docopt
from hpcbench import __version__
from hpcbench.toolbox.loader import load_components
LOGGING_FORMAT = "%(asctime)-15s:%(levelname)s:%(name)s:%(message)s"
def setup_logger(verbose):
"""Prepare root logger
:param verbose: integer greater than 0 to indicate verbosity level
"""
level = logging.WARNING
if verbose == 1:
level = logging.INFO
elif verbose > 1:
level = logging.DEBUG
logging.basicConfig(level=level, format=LOGGING_FORMAT)
def cli_common(doc, **kwargs):
"""Program initialization for all provided executables
"""
arguments = docopt(doc, version='hpcbench ' + __version__, **kwargs)
setup_logger(arguments['-v'])
load_components()
try:
import matplotlib
except ImportError:
pass
else:
matplotlib.use('PS')
return arguments
| """Provide all package executables
"""
import logging
from docopt import docopt
from hpcbench import __version__
from hpcbench.toolbox.loader import load_components
def setup_logger(verbose):
"""Prepare root logger
:param verbose: integer greater than 0 to indicate verbosity level
"""
level = logging.WARNING
if verbose == 1:
level = logging.INFO
elif verbose > 1:
level = logging.DEBUG
logging.basicConfig(level=level)
def cli_common(doc, **kwargs):
"""Program initialization for all provided executables
"""
arguments = docopt(doc, version='hpcbench ' + __version__, **kwargs)
setup_logger(arguments['-v'])
load_components()
try:
import matplotlib
except ImportError:
pass
else:
matplotlib.use('PS')
return arguments
|
Use DIRECTORY_SEPARATOR instead of hard-coded '/'
We never know where this thing is going to be run on. | <?php
namespace UView;
class View {
protected $storage = [];
protected $path;
public function __construct( $path ) {
$this->path = $path;
}
public function set( $var, $value ) {
$this->storage[ $var ] = $value;
}
public function __toString() {
ob_start();
// "Trigger" a "-" error, so that we can check if the include
// issued any error. Unfortunately error_clear_last() requires
// PHP >= 7.
@trigger_error('-');
extract($this->storage);
@include $this->path;
$err = error_get_last();
$output = ob_get_clean();
if ($err['message'] != '-') {
// Call error_log() as a last resort.
error_log($err['message']);
}
return $output;
}
}
class Registry {
protected $path;
public function __construct( $path ) {
$this->path = $path;
}
public function get( $name ) {
$path = $this->path . DIRECTORY_SEPARATOR . "$name.php";
if ( ! file_exists($path) ) {
throw new \RuntimeException("No such view '$name' found in '$this->path'");
}
return new View($path);
}
}
| <?php
namespace UView;
class View {
protected $storage = [];
protected $path;
public function __construct( $path ) {
$this->path = $path;
}
public function set( $var, $value ) {
$this->storage[ $var ] = $value;
}
public function __toString() {
ob_start();
// "Trigger" a "-" error, so that we can check if the include
// issued any error. Unfortunately error_clear_last() requires
// PHP >= 7.
@trigger_error('-');
extract($this->storage);
@include $this->path;
$err = error_get_last();
$output = ob_get_clean();
if ($err['message'] != '-') {
// Call error_log() as a last resort.
error_log($err['message']);
}
return $output;
}
}
class Registry {
protected $path;
public function __construct( $path ) {
$this->path = $path;
}
public function get( $name ) {
$path = $this->path . "/$name.php";
if ( ! file_exists($path) ) {
throw new \RuntimeException("No such view '$name' found in '$this->path'");
}
return new View($path);
}
}
|
Remove print-link JS. There aren't any print links in the template | $(document).ready(function() {
// fix for printing bug in Windows Safari
var windowsSafari = (window.navigator.userAgent.match(/(\(Windows[\s\w\.]+\))[\/\(\s\w\.\,\)]+(Version\/[\d\.]+)\s(Safari\/[\d\.]+)/) !== null),
style;
if (windowsSafari) {
// set the New Transport font to Arial for printing
style = document.createElement('style');
style.setAttribute('type', 'text/css');
style.setAttribute('media', 'print');
style.innerHTML = '@font-face { font-family: nta !important; src: local("Arial") !important; }';
document.getElementsByTagName('head')[0].appendChild(style);
}
if (window.GOVUK && GOVUK.addCookieMessage) {
GOVUK.addCookieMessage();
}
});
| $(document).ready(function() {
$('.print-link a').attr('target', '_blank');
// fix for printing bug in Windows Safari
var windowsSafari = (window.navigator.userAgent.match(/(\(Windows[\s\w\.]+\))[\/\(\s\w\.\,\)]+(Version\/[\d\.]+)\s(Safari\/[\d\.]+)/) !== null),
style;
if (windowsSafari) {
// set the New Transport font to Arial for printing
style = document.createElement('style');
style.setAttribute('type', 'text/css');
style.setAttribute('media', 'print');
style.innerHTML = '@font-face { font-family: nta !important; src: local("Arial") !important; }';
document.getElementsByTagName('head')[0].appendChild(style);
}
if (window.GOVUK && GOVUK.addCookieMessage) {
GOVUK.addCookieMessage();
}
});
|
[SMALLFIX] Replace lambda with method reference
replace lambda with method reference in
/alluxio/core/server/master/src/main/java/alluxio/master/file/BlockDeletionContext.java#registerBlocksForDeletion
Change
blockIds.forEach(id -> registerBlockForDeletion(id));
to
blockIds.forEach(this::registerBlockForDeletion);
pr-link: Alluxio/alluxio#8883
change-id: cid-c34d06a869cf99cff05f90546b2b7f04bbe12250 | /*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.master.file;
import java.io.Closeable;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
/**
* Interface for a class which gathers block deletion requests, then handles them during close.
*/
public interface BlockDeletionContext extends Closeable {
/**
* @param blockIds the blocks to be deleted when the context closes
*/
default void registerBlocksForDeletion(Collection<Long> blockIds) {
blockIds.forEach(this::registerBlockForDeletion);
}
/**
* @param blockId the block to be deleted when the context closes
*/
void registerBlockForDeletion(long blockId);
/**
* Interface for block deletion listeners.
*/
@FunctionalInterface
interface BlockDeletionListener {
/**
* Processes block deletion.
*
* @param blocks the deleted blocks
*/
void process(List<Long> blocks) throws IOException;
}
}
| /*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.master.file;
import java.io.Closeable;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
/**
* Interface for a class which gathers block deletion requests, then handles them during close.
*/
public interface BlockDeletionContext extends Closeable {
/**
* @param blockIds the blocks to be deleted when the context closes
*/
default void registerBlocksForDeletion(Collection<Long> blockIds) {
blockIds.forEach(id -> registerBlockForDeletion(id));
}
/**
* @param blockId the block to be deleted when the context closes
*/
void registerBlockForDeletion(long blockId);
/**
* Interface for block deletion listeners.
*/
@FunctionalInterface
interface BlockDeletionListener {
/**
* Processes block deletion.
*
* @param blocks the deleted blocks
*/
void process(List<Long> blocks) throws IOException;
}
}
|
Fix typo at calendar transaction
Summary:
* Fixed conveted => converted
Ref T11576
Test Plan: * Looked at a page, where somebody converted an AllDay Event to a normal one
Reviewers: #blessed_reviewers, epriestley
Reviewed By: #blessed_reviewers, epriestley
Subscribers: epriestley
Tags: #calendar
Maniphest Tasks: T11576
Differential Revision: https://secure.phabricator.com/D16488 | <?php
final class PhabricatorCalendarEventAllDayTransaction
extends PhabricatorCalendarEventTransactionType {
const TRANSACTIONTYPE = 'calendar.allday';
public function generateOldValue($object) {
return (int)$object->getIsAllDay();
}
public function generateNewValue($object, $value) {
return (int)$value;
}
public function applyInternalEffects($object, $value) {
$object->setIsAllDay($value);
}
public function getTitle() {
if ($this->getNewValue()) {
return pht(
'%s changed this as an all day event.',
$this->renderAuthor());
} else {
return pht(
'%s converted this from an all day event.',
$this->renderAuthor());
}
}
public function getTitleForFeed() {
if ($this->getNewValue()) {
return pht(
'%s changed %s to an all day event.',
$this->renderAuthor(),
$this->renderObject());
} else {
return pht(
'%s converted %s from an all day event.',
$this->renderAuthor(),
$this->renderObject());
}
}
}
| <?php
final class PhabricatorCalendarEventAllDayTransaction
extends PhabricatorCalendarEventTransactionType {
const TRANSACTIONTYPE = 'calendar.allday';
public function generateOldValue($object) {
return (int)$object->getIsAllDay();
}
public function generateNewValue($object, $value) {
return (int)$value;
}
public function applyInternalEffects($object, $value) {
$object->setIsAllDay($value);
}
public function getTitle() {
if ($this->getNewValue()) {
return pht(
'%s changed this as an all day event.',
$this->renderAuthor());
} else {
return pht(
'%s conveted this from an all day event.',
$this->renderAuthor());
}
}
public function getTitleForFeed() {
if ($this->getNewValue()) {
return pht(
'%s changed %s to an all day event.',
$this->renderAuthor(),
$this->renderObject());
} else {
return pht(
'%s converted %s from an all day event.',
$this->renderAuthor(),
$this->renderObject());
}
}
}
|
Fix for requiring autoloader in bin script. | #!/usr/bin/env php
<?php
/*
* This file is part of StaticReview
*
* Copyright (c) 2014 Samuel Parkinson <@samparkinson_>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @see http://github.com/sjparkinson/static-review/blob/master/LICENSE.md
*/
// Composer autoloader
require_once file_exists(__DIR__ . '/../vendor/autoload.php')
? __DIR__ . '/../vendor/autoload.php'
: __DIR__ . '/../../../autoload.php';
use StaticReview\Command\HookListCommand;
use StaticReview\Command\HookLinkCommand;
use StaticReview\Command\HookRunCommand;
use Symfony\Component\Console\Application;
$console = new Application();
$console->addCommands([
new HookListCommand,
new HookLinkCommand,
new HookRunCommand
]);
$console->run();
| #!/usr/bin/env php
<?php
/*
* This file is part of StaticReview
*
* Copyright (c) 2014 Samuel Parkinson <@samparkinson_>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @see http://github.com/sjparkinson/static-review/blob/master/LICENSE.md
*/
// Composer autoloader
require_once file_exists(__DIR__ . '/../autoload.php')
? __DIR__ . '/../autoload.php'
: __DIR__ . '/../vendor/autoload.php';
use StaticReview\Command\HookListCommand;
use StaticReview\Command\HookLinkCommand;
use StaticReview\Command\HookRunCommand;
use Symfony\Component\Console\Application;
$console = new Application();
$console->addCommands([
new HookListCommand,
new HookLinkCommand,
new HookRunCommand
]);
$console->run();
|
Add comment about allowed accesses. | class ArrayAccessExpressionTest {
public static void main(String[] args) {
int i;
int[] ia;
long l;
long[] la;
boolean b;
A cA;
B cB;
//i = ia[i];// OK!
i = ia[ia]; // INVALID_INDEX_TYPE
i = ia[l]; // INVALID_INDEX_TYPE
i = ia[la]; // INVALID_INDEX_TYPE
i = ia[b]; // INVALID_INDEX_TYPE
i = ia[cA]; // INVALID_INDEX_TYPE
//l = la[i]; // OK!
l = la[ia]; // INVALID_INDEX_TYPE
l = la[l]; // INVALID_INDEX_TYPE
l = la[la]; // INVALID_INDEX_TYPE
l = la[b]; // INVALID_INDEX_TYPE
l = la[cA]; // INVALID_INDEX_TYPE
i = i[i]; // NOT_ARRAY_TYPE
i = l[i]; // NOT_ARRAY_TYPE
i = b[i]; // NOT_ARRAY_TYPE
i = cA[i]; // NOT_ARRAY_TYPE
}
}
class A {}
class B {}
| class ArrayAccessExpressionTest {
public static void main(String[] args) {
int i;
int[] ia;
long l;
long[] la;
boolean b;
A cA;
B cB;
i = ia[ia]; // INVALID_INDEX_TYPE
i = ia[l]; // INVALID_INDEX_TYPE
i = ia[la]; // INVALID_INDEX_TYPE
i = ia[b]; // INVALID_INDEX_TYPE
i = ia[cA]; // INVALID_INDEX_TYPE
l = la[ia]; // INVALID_INDEX_TYPE
l = la[l]; // INVALID_INDEX_TYPE
l = la[la]; // INVALID_INDEX_TYPE
l = la[b]; // INVALID_INDEX_TYPE
l = la[cA]; // INVALID_INDEX_TYPE
i = i[i]; // NOT_ARRAY_TYPE
i = l[i]; // NOT_ARRAY_TYPE
i = b[i]; // NOT_ARRAY_TYPE
i = cA[i]; // NOT_ARRAY_TYPE
}
}
class A {}
class B {}
|
Use async await on test | import createCredentialsAuthenticator from '../../src/authenticators/credentials'
beforeEach(() => {
fetch.resetMocks()
})
it('fetches from given endpoint using default config', () => {
fetch.mockResponse(JSON.stringify({ ok: true }))
const credentials = createCredentialsAuthenticator({
endpoint: '/authenticate'
})
const creds = { email: 'text@example.com', password: 'password' }
credentials.authenticate(creds)
expect(fetch).toHaveBeenCalledWith('/authenticate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(creds)
})
})
it('resolves with returned data by default', async () => {
fetch.mockResponse(JSON.stringify({ token: '12345' }))
const credentials = createCredentialsAuthenticator({
endpoint: '/authenticate'
})
const creds = { email: 'text@example.com', password: 'password' }
const promise = credentials.authenticate(creds)
await expect(promise).resolves.toEqual({ token: '12345' })
})
| import createCredentialsAuthenticator from '../../src/authenticators/credentials'
beforeEach(() => {
fetch.resetMocks()
})
it('fetches from given endpoint using default config', () => {
fetch.mockResponse(JSON.stringify({ ok: true }))
const credentials = createCredentialsAuthenticator({
endpoint: '/authenticate'
})
const creds = { email: 'text@example.com', password: 'password' }
credentials.authenticate(creds)
expect(fetch).toHaveBeenCalledWith('/authenticate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(creds)
})
})
it('resolves with returned data by default', () => {
fetch.mockResponse(JSON.stringify({ token: '12345' }))
const credentials = createCredentialsAuthenticator({
endpoint: '/authenticate'
})
const creds = { email: 'text@example.com', password: 'password' }
const promise = credentials.authenticate(creds)
expect(promise).resolves.toEqual({ token: '12345' })
})
|
Add better python path description | var path = require('path');
var fs = require('fs');
module.exports = function() {
verifyNode();
verifyPython27();
};
function verifyNode() {
var nodeVersion = process.versions.node.split('.');
var nodeMajorVersion = +nodeVersion[0];
var nodeMinorVersion = +nodeVersion[1];
if (nodeMajorVersion === 0 && nodeMinorVersion < 10) {
console.warn("node v0.10 is required to build Atom.");
process.exit(1);
}
}
function verifyPython27() {
if (process.platform == 'win32') {
var pythonPath = process.env.PYTHON;
if (!pythonPath) {
var systemDrive = process.env.SystemDrive || 'C:\\';
pythonPath = path.join(systemDrive, 'Python27');
}
if (!fs.existsSync(pythonPath)) {
console.warn("Python 2.7 is required to build Atom. Python 2.7 must be installed at '" + pythonPath + "' or the PYTHON env var must be set to '/path/to/Python27/python.exe'");
process.exit(1);
}
}
}
| var path = require('path');
var fs = require('fs');
module.exports = function() {
verifyNode();
verifyPython27();
};
function verifyNode() {
var nodeVersion = process.versions.node.split('.');
var nodeMajorVersion = +nodeVersion[0];
var nodeMinorVersion = +nodeVersion[1];
if (nodeMajorVersion === 0 && nodeMinorVersion < 10) {
console.warn("node v0.10 is required to build Atom.");
process.exit(1);
}
}
function verifyPython27() {
if (process.platform == 'win32') {
var pythonPath = process.env.PYTHON;
if (!pythonPath) {
var systemDrive = process.env.SystemDrive || 'C:\\';
pythonPath = path.join(systemDrive, 'Python27');
}
if (!fs.existsSync(pythonPath)) {
console.warn("Python 2.7 is required to build Atom. Python 2.7 must be installed at '" + pythonPath + "' or the PYTHON env var must be set to '/path/to/executable/python2.7'");
process.exit(1);
}
}
}
|
Fix double quotes to single quotes | from pydantic import BaseModel
class Person(BaseModel):
name: str
age: int
class Config:
schema_extra = {
'examples': [
{
'name': 'John Doe',
'age': 25,
}
]
}
print(Person.schema())
# {'title': 'Person',
# 'type': 'object',
# 'properties': {'name': {'title': 'Name', 'type': 'string'},
# 'age': {'title': 'Age', 'type': 'integer'}},
# 'required': ['name', 'age'],
# 'examples': [{'name': 'John Doe', 'age': 25}]}
print(Person.schema_json(indent=2))
| from pydantic import BaseModel
class Person(BaseModel):
name: str
age: int
class Config:
schema_extra = {
"examples": [
{
"name": "John Doe",
"age": 25,
}
]
}
print(Person.schema())
# {'title': 'Person',
# 'type': 'object',
# 'properties': {'name': {'title': 'Name', 'type': 'string'},
# 'age': {'title': 'Age', 'type': 'integer'}},
# 'required': ['name', 'age'],
# 'examples': [{'name': 'John Doe', 'age': 25}]}
print(Person.schema_json(indent=2))
|
Test that there are errors instead of exact number | import React from 'react';
import { mount, shallow } from 'enzyme';
import App from './App';
import TimeTable from 'timetablescreen';
describe('App', () => {
beforeEach( () => {
Object.defineProperty(window.location, 'href', {
writable: true,
value: 'localhost:3000/kara'
});
});
it('renders without crashing', () => {
shallow(<App />);
});
it('shows error when state is updated to error', () => {
const component = mount(<App />);
component.setState({data: {
error: 'error'
}});
expect(component.find('.cs-error')).toBeTruthy(); // TODO: Add error prefix and use toHaveLenght
});
it('shows timetable when state is updated to valid state', () => {
const component = shallow(<App />);
component.setState({data: {lat: 0, lon:0}});
component.update();
expect(component.find(TimeTable)).toHaveLength(1);
});
});
| import React from 'react';
import { mount, shallow } from 'enzyme';
import App from './App';
import TimeTable from 'timetablescreen';
describe('App', () => {
beforeEach( () => {
Object.defineProperty(window.location, 'href', {
writable: true,
value: 'localhost:3000/kara'
});
});
it('renders without crashing', () => {
shallow(<App />);
});
it('shows error when state is updated to error', () => {
const component = mount(<App />);
component.setState({data: {
error: 'error'
}});
expect(component.find('.cs-error')).toHaveLength(1);
});
it('shows timetable when state is updated to valid state', () => {
const component = shallow(<App />);
component.setState({data: {lat: 0, lon:0}});
component.update();
expect(component.find(TimeTable)).toHaveLength(1);
});
});
|
Apply ember codemods on tests | import { module, test, todo } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
module('Integration | Component | bs datetimepicker', function(hooks) {
setupRenderingTest(hooks);
todo('it renders iconClasses and iconText', async function(assert) {
assert.expect(2);
await render(hbs`{{bs-datetimepicker date='2016-01-01' iconClasses='material-icons' iconText='date-range'}}`);
assert.dom('.input-group-addon i').hasAttribute('class', 'material-icons');
assert.dom('.input-group-addon i').hasText('date-range');
});
test('it renders with default icon classes', async function(assert) {
assert.expect(1);
await render(hbs`{{bs-datetimepicker date='2016-01-01'}}`);
assert.dom('.input-group-addon i').hasAttribute('class', 'glyphicon glyphicon-calendar');
});
});
| import { moduleForComponent, test, todo } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
moduleForComponent('bs-datetimepicker', 'Integration | Component | bs datetimepicker', {
integration: true
});
todo('it renders iconClasses and iconText', function(assert) {
assert.expect(2);
this.render(
hbs`{{bs-datetimepicker date='2016-01-01' iconClasses='material-icons' iconText='date-range'}}`
);
assert.equal(this.$('.input-group-addon i').attr('class'), 'material-icons');
assert.equal(
this.$('.input-group-addon i')
.text()
.trim(),
'date-range'
);
});
test('it renders with default icon classes', function(assert) {
assert.expect(1);
this.render(hbs`{{bs-datetimepicker date='2016-01-01'}}`);
assert.equal(this.$('.input-group-addon i').attr('class'), 'glyphicon glyphicon-calendar');
});
|
Drop meteor-base version to 1.5 for tests to pass | Package.describe({
name: 'meteor-base',
version: '1.5.0-beta230.2',
// Brief, one-line summary of the package.
summary: 'Packages that every Meteor app needs',
// By default, Meteor will default to using README.md for documentation.
// To avoid submitting documentation, set this field to null.
documentation: 'README.md'
});
Package.onUse(function(api) {
api.imply([
// Super basic stuff about where your code is running and async utilities
'meteor',
// This package enables making client-server connections; currently Meteor
// only supports building client/server web applications so this is not
// removable
'webapp',
// The protocol and client/server libraries that Meteor uses to send data
'ddp',
// This package uses the user agent of each incoming HTTP request to
// decide whether to inject <script> tags into the <head> of the
// response document to polyfill ECMAScript 5 support.
'es5-shim',
// Push code changes to the client and automatically reload the page
'hot-code-push'
]);
});
| Package.describe({
name: 'meteor-base',
version: '2.0.0-beta230.2',
// Brief, one-line summary of the package.
summary: 'Packages that every Meteor app needs',
// By default, Meteor will default to using README.md for documentation.
// To avoid submitting documentation, set this field to null.
documentation: 'README.md'
});
Package.onUse(function(api) {
api.imply([
// Super basic stuff about where your code is running and async utilities
'meteor',
// This package enables making client-server connections; currently Meteor
// only supports building client/server web applications so this is not
// removable
'webapp',
// The protocol and client/server libraries that Meteor uses to send data
'ddp',
// This package uses the user agent of each incoming HTTP request to
// decide whether to inject <script> tags into the <head> of the
// response document to polyfill ECMAScript 5 support.
'es5-shim',
// Push code changes to the client and automatically reload the page
'hot-code-push'
]);
});
|
Use requests 0.14.1 from now on. | #!/usr/bin/env python
# coding: utf-8
from setuptools import setup
from setuptools import find_packages
classifiers = [
"Intended Audience :: Developers",
"Programming Language :: Python",
"Operating System :: OS Independent",
"Topic :: Software Development :: Libraries",
"Environment :: Web Environment",
"License :: OSI Approved :: BSD License",
"Development Status :: 5 - Production/Stable",
]
requires = ["requests==0.14.1", ]
# This might not be the best idea.
try:
import json
except ImportError:
requires.append('simplejson>=2.0')
setup(name='pyspotlight',
version='0.5.3',
license='BSD',
url='https://github.com/newsgrape/pyspotlight',
packages=find_packages(),
description='Python interface to the DBPedia Spotlight REST API',
long_description=open('README.rst').read(),
keywords="dbpedia spotlight semantic",
classifiers=classifiers,
install_requires=requires,
)
| #!/usr/bin/env python
# coding: utf-8
from setuptools import setup
from setuptools import find_packages
classifiers = [
"Intended Audience :: Developers",
"Programming Language :: Python",
"Operating System :: OS Independent",
"Topic :: Software Development :: Libraries",
"Environment :: Web Environment",
"License :: OSI Approved :: BSD License",
"Development Status :: 5 - Production/Stable",
]
requires = ["requests>=0.11.1", ]
# This might not be the best idea.
try:
import json
except ImportError:
requires.append('simplejson>=2.0')
setup(name='pyspotlight',
version='0.5.3',
license='BSD',
url='https://github.com/newsgrape/pyspotlight',
packages=find_packages(),
description='Python interface to the DBPedia Spotlight REST API',
long_description=open('README.rst').read(),
keywords="dbpedia spotlight semantic",
classifiers=classifiers,
install_requires=requires,
)
|
Use sphinx-apidoc to generate API docs from docstrings. | from invoke import task, run
@task
def clean_docs():
run("rm -rf docs/_build")
run("rm -rf docs/binaryornot.rst")
run("rm -rf docs/modules.rst")
@task('clean_docs')
def docs():
run("sphinx-apidoc -o docs/ binaryornot/")
run("sphinx-build docs docs/_build")
run("open docs/_build/index.html")
@task
def flake8():
run("flake8 binaryornot tests")
@task
def autopep8():
run("autopep8 --in-place --aggressive -r binaryornot")
run("autopep8 --in-place --aggressive -r tests")
@task
def test():
run("python setup.py test")
@task
def coverage():
run("coverage run --source binaryornot setup.py test")
run("coverage report -m")
run("coverage html")
run("open htmlcov/index.html")
@task
def clean_build():
run("rm -fr build/")
run("rm -fr dist/")
run("rm -fr *.egg-info")
@task
def clean_pyc():
run("find . -name '*.pyc' -exec rm -f {} +")
run("find . -name '*.pyo' -exec rm -f {} +")
run("find . -name '*~' -exec rm -f {} +")
@task('clean_build', 'clean_pyc')
def sdist():
run("python setup.py sdist")
run("ls -l dist")
@task('sdist')
def release():
run("python setup.py upload")
| from invoke import task, run
@task
def clean_docs():
run("rm -rf docs/_build")
@task('clean_docs')
def docs():
run("sphinx-build docs docs/_build")
run("open docs/_build/index.html")
@task
def flake8():
run("flake8 binaryornot tests")
@task
def autopep8():
run("autopep8 --in-place --aggressive -r binaryornot")
run("autopep8 --in-place --aggressive -r tests")
@task
def test():
run("python setup.py test")
@task
def coverage():
run("coverage run --source binaryornot setup.py test")
run("coverage report -m")
run("coverage html")
run("open htmlcov/index.html")
@task
def clean_build():
run("rm -fr build/")
run("rm -fr dist/")
run("rm -fr *.egg-info")
@task
def clean_pyc():
run("find . -name '*.pyc' -exec rm -f {} +")
run("find . -name '*.pyo' -exec rm -f {} +")
run("find . -name '*~' -exec rm -f {} +")
@task('clean_build', 'clean_pyc')
def sdist():
run("python setup.py sdist")
run("ls -l dist")
@task('sdist')
def release():
run("python setup.py upload")
|
Add Adress to lat, lng converter | define(["backbone", "underscore", "jquery"], function(Backbone, _, $) {
var UserProfile = Backbone.Model.extend({
//data attributes
defaults: {
age: null,
gender: null,
address: null,
pricePerSMeter: null,
color: null,
extras: null,
},
convertAddress: function(){
var self = this;
var url = "http://maps.googleapis.com/maps/api/geocode/json?address=" + this.address + "&sensor=false";
var json = $.getJSON(url, function(json) { return json });
return json.done(function(response) {
var location = response.results[0].geometry.location;
self.point = location.lat + ", " + location.lng;
});
},
//converters
getMinMaxPrice: function(){
//setPricePerSMeter();
min = pricePerSMeter* 1000 * 0.7;
max = pricePerSMeter* 1000 * 1.3;
return {min: min, max: max};
},
setPricePerSMeter: function(){
//TODO get from location
}
});
return UserProfile;
});
| define(["backbone", "underscore" ], function(Backbone, _) {
var UserProfile = Backbone.Model.extend({
//data attributes
defaults: {
age: null,
gender: null,
address: null,
pricePerSMeter: null,
color: null,
extras: null,
},
//converters
getMinMaxPrice: function(){
//setPricePerSMeter();
min = pricePerSMeter* 1000 * 0.7;
max = pricePerSMeter* 1000 * 1.3;
return {min: min, max: max};
},
setPricePerSMeter: function(){
//TODO get from location
}
});
return UserProfile;
});
|
Add correct props to mapStateToProps | import { connect } from 'react-redux';
import {
fetchNavigation,
setNavigationVisibility,
fetchTOS,
setPhaseVisibility,
setPhasesVisibility,
setDocumentState,
fetchRecordTypes,
fetchAttributeTypes,
addAction,
addRecord,
addPhase,
changeOrder,
importItems,
closeMessage
} from '../modules/home';
import HomeView from '../components/HomeView';
const mapDispatchToProps = {
fetchNavigation,
setNavigationVisibility,
fetchTOS,
setPhaseVisibility,
setPhasesVisibility,
setDocumentState,
fetchRecordTypes,
fetchAttributeTypes,
addAction,
addRecord,
addPhase,
changeOrder,
importItems,
closeMessage
};
const mapStateToProps = (state) => {
return {
navigation: state.navigation,
recordTypes: state.home.recordTypes,
selectedTOS: state.tos,
phases: state.tos.phases,
actions: state.tos.actions,
records: state.tos.records,
selectedTOSPath: state.tos.path,
isFetching: state.home.isFetching,
documentState: state.tos.documentState,
attributeTypes: state.home.attributeTypes,
message: state.home.message
};
};
export default connect(mapStateToProps, mapDispatchToProps)(HomeView);
| import { connect } from 'react-redux';
import {
fetchNavigation,
setNavigationVisibility,
fetchTOS,
setPhaseVisibility,
setPhasesVisibility,
setDocumentState,
fetchRecordTypes,
fetchAttributeTypes,
addAction,
addRecord,
addPhase,
changeOrder,
importItems,
closeMessage
} from '../modules/home';
import HomeView from '../components/HomeView';
const mapDispatchToProps = {
fetchNavigation,
setNavigationVisibility,
fetchTOS,
setPhaseVisibility,
setPhasesVisibility,
setDocumentState,
fetchRecordTypes,
fetchAttributeTypes,
addAction,
addRecord,
addPhase,
changeOrder,
importItems,
closeMessage
};
const mapStateToProps = (state) => {
return {
navigation: state.home.navigation,
recordTypes: state.home.recordTypes,
selectedTOS: state.home.selectedTOS.tos,
phases: state.home.selectedTOS.phases,
actions: state.home.selectedTOS.actions,
records: state.home.selectedTOS.records,
selectedTOSPath: state.home.selectedTOS.path,
isFetching: state.home.isFetching,
documentState: state.home.selectedTOS.documentState,
attributeTypes: state.home.attributeTypes,
message: state.home.message
};
};
export default connect(mapStateToProps, mapDispatchToProps)(HomeView);
|
Make sure to always restore "debug" state in page-example test | <?php
class CM_Page_ExampleTest extends CMTest_TestCase {
/** @var bool */
private $_debugBackup;
protected function setUp() {
$this->_debugBackup = CM_Bootloader::getInstance()->isDebug();
}
protected function tearDown() {
CM_Bootloader::getInstance()->setDebug($this->_debugBackup);
}
public function testAccessible() {
$page = new CM_Page_Example();
CM_Bootloader::getInstance()->setDebug(true);
$this->_renderPage($page);
CM_Bootloader::getInstance()->setDebug(false);
$this->assertPageNotRenderable($page);
}
public function testTidy() {
CM_Bootloader::getInstance()->setDebug(true);
$page = $this->_createPage('CM_Page_Example');
$html = $this->_renderPage($page);
$this->assertTidy($html, false);
}
}
| <?php
class CM_Page_ExampleTest extends CMTest_TestCase {
public function testAccessible() {
$debugBackup = CM_Bootloader::getInstance()->isDebug();
$page = new CM_Page_Example();
CM_Bootloader::getInstance()->setDebug(true);
$this->_renderPage($page);
CM_Bootloader::getInstance()->setDebug(false);
$this->assertPageNotRenderable($page);
CM_Bootloader::getInstance()->setDebug($debugBackup);
}
public function testTidy() {
$debugBackup = CM_Bootloader::getInstance()->isDebug();
CM_Bootloader::getInstance()->setDebug(true);
$page = $this->_createPage('CM_Page_Example');
$html = $this->_renderPage($page);
$this->assertTidy($html, false);
CM_Bootloader::getInstance()->setDebug($debugBackup);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.