text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Fix user seeder (giving DateTime when setter expects string) | <?php
class UsersTableSeeder extends Seeder {
public function run()
{
$faker = Faker\Factory::create();
User::truncate();
User::create([
'first_name' => 'Dave',
'email' => '[email protected]',
'password' => 'tops3cret',
])->assignRole(1);
User::create([
'first_name' => 'Andrea',
'email' => '[email protected]',
'password' => 'tops3cret',
])->assignRole(1);
User::create([
'first_name' => 'Calvin',
'email' => '[email protected]',
'password' => 'tops3cret',
])->assignRole(1);
User::create([
'first_name' => 'Naomi',
'email' => '[email protected]',
'password' => 'tops3cret',
])->assignRole(1);
if (App::environment('local')) {
foreach(range(1,25) as $index) {
User::create([
'first_name' => $faker->firstName,
'email' => $faker->unique()->safeEmail,
'birthdate' => $faker->date($format = 'm/d/Y', $max = 'now'),
]);
}
foreach(range(1,25) as $index) {
User::create([
'first_name' => $faker->firstName,
'phone' => $faker->unique()->phoneNumber,
'birthdate' => $faker->date($format = 'm/d/Y', $max = 'now'),
]);
}
}
}
}
| <?php
class UsersTableSeeder extends Seeder {
public function run()
{
$faker = Faker\Factory::create();
User::truncate();
User::create([
'first_name' => 'Dave',
'email' => '[email protected]',
'password' => 'tops3cret',
])->assignRole(1);
User::create([
'first_name' => 'Andrea',
'email' => '[email protected]',
'password' => 'tops3cret',
])->assignRole(1);
User::create([
'first_name' => 'Calvin',
'email' => '[email protected]',
'password' => 'tops3cret',
])->assignRole(1);
User::create([
'first_name' => 'Naomi',
'email' => '[email protected]',
'password' => 'tops3cret',
])->assignRole(1);
if (App::environment('local')) {
foreach(range(1,25) as $index) {
User::create([
'first_name' => $faker->firstName,
'email' => $faker->unique()->safeEmail,
'birthdate' => $faker->dateTime('now'),
]);
}
foreach(range(1,25) as $index) {
User::create([
'first_name' => $faker->firstName,
'phone' => $faker->unique()->phoneNumber,
'birthdate' => $faker->dateTime('now'),
]);
}
}
}
}
|
Raise DependencyError when series plugin is missing | from __future__ import unicode_literals, division, absolute_import
import logging
from sqlalchemy import desc, func
from flexget.manager import Session
from flexget.plugin import register_plugin, priority, DependencyError
from flexget.utils.tools import multiply_timedelta
try:
from flexget.plugins.filter.series import Series, Episode
except ImportError:
raise DependencyError(issued_by='est_released_series', missing='series plugin', silent=True)
log = logging.getLogger('est_series')
class EstimatesReleasedSeries(object):
@priority(0) # Run only if better online lookups fail
def estimate(self, entry):
if all(field in entry for field in ['series_name', 'series_season', 'series_episode']):
session = Session()
series = session.query(Series).filter(Series.name == entry['series_name']).first()
if not series:
return
episodes = (session.query(Episode).join(Series).
filter(Episode.season != None).
filter(Series.id == series.id).
filter(Episode.season == func.max(Episode.season).select()).
order_by(desc(Episode.number)).limit(2).all())
if len(episodes) < 2:
return
last_diff = episodes[0].first_seen - episodes[1].first_seen
return episodes[0].first_seen + multiply_timedelta(last_diff, 0.9)
# TODO: Some fancier logic? Season break estimates?
register_plugin(EstimatesReleasedSeries, 'est_released_series', groups=['estimate_release'])
| from __future__ import unicode_literals, division, absolute_import
import logging
from sqlalchemy import desc, func
from flexget.manager import Session
from flexget.plugin import register_plugin, priority
from flexget.plugins.filter.series import SeriesDatabase, Series, Episode
from flexget.utils.tools import multiply_timedelta
log = logging.getLogger('est_series')
class EstimatesReleasedSeries(SeriesDatabase):
@priority(0) # Run only if better online lookups fail
def estimate(self, entry):
if all(field in entry for field in ['series_name', 'series_season', 'series_episode']):
session = Session()
series = session.query(Series).filter(Series.name == entry['series_name']).first()
if not series:
return
episodes = (session.query(Episode).join(Series).
filter(Episode.season != None).
filter(Series.id == series.id).
filter(Episode.season == func.max(Episode.season).select()).
order_by(desc(Episode.number)).limit(2).all())
if len(episodes) < 2:
return
last_diff = episodes[0].first_seen - episodes[1].first_seen
return episodes[0].first_seen + multiply_timedelta(last_diff, 0.9)
# TODO: Some fancier logic? Season break estimates?
register_plugin(EstimatesReleasedSeries, 'est_released_series', groups=['estimate_release'])
|
Remove alerts when clicking link or button |
(function(){
var app = angular.module('runnersNotes',[]);
app.controller('NoteController',['$http',function($http){
var rn = this;
rn.success = false;
rn.errors = [];
rn.notes = [];
rn.note = {};
$http.get('http://localhost:8080/notes').success(function(data){
rn.notes = data.items;
});
this.clearAlerts = function() {
rn.errors = [];
rn.success = false;
};
this.addNote = function() {
rn.note.created = new Date(rn.note.date).getTime();
$http.post('http://localhost:8080/notes',rn.note).
then(function(response){
rn.notes.push(rn.note);
rn.note = {};
rn.success = true;
rn.errors = [];
$("#addForm").collapse('hide');
}, function(response) {
rn.success = false;
for (var i=0; i < response.data.length; i++) {
rn.errors.push(response.data[i]);
}
});
};
}]);
})(); |
(function(){
var app = angular.module('runnersNotes',[]);
app.controller('NoteController',['$http',function($http){
var rn = this;
rn.success = false;
rn.errors = [];
rn.notes = [];
rn.note = {};
$http.get('http://localhost:8080/notes').success(function(data){
rn.notes = data.items;
});
this.addNote = function() {
rn.note.created = new Date(rn.note.date).getTime();
$http.post('http://localhost:8080/notes',rn.note).
then(function(response){
//if (response.status === 201) {
rn.notes.push(rn.note);
rn.note = {};
rn.success = true;
rn.errors = [];
$("#addForm").collapse('hide');
//}
}, function(response) {
rn.success = false;
for (var i=0; i < response.data.length; i++) {
rn.errors.push(response.data[i]);
}
console.log(response);
});
};
}]);
})(); |
Rename default -> vespa and add clarifying comment. | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.admin.monitoring;
import ai.vespa.metricsproxy.core.VespaMetrics;
import com.google.common.collect.ImmutableList;
import static com.yahoo.vespa.model.admin.monitoring.NetworkMetrics.networkMetricSet;
import static com.yahoo.vespa.model.admin.monitoring.SystemMetrics.systemMetricSet;
import static com.yahoo.vespa.model.admin.monitoring.VespaMetricSet.vespaMetricSet;
import static java.util.Collections.emptyList;
/**
* This class sets up the 'Vespa' metrics consumer, which is mainly used for Yamas in hosted Vespa.
*
* @author trygve
* @author gjoranv
*/
public class VespaMetricsConsumer {
public static final String VESPA_CONSUMER_ID = VespaMetrics.VESPA_CONSUMER_ID.id;
private static final MetricSet vespaConsumerMetrics = new MetricSet("vespa-consumer-metrics",
emptyList(),
ImmutableList.of(vespaMetricSet,
systemMetricSet,
networkMetricSet));
public static MetricsConsumer getVespaMetricsConsumer() {
return new MetricsConsumer(VESPA_CONSUMER_ID, vespaConsumerMetrics);
}
}
| // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.admin.monitoring;
import ai.vespa.metricsproxy.core.VespaMetrics;
import com.google.common.collect.ImmutableList;
import static com.yahoo.vespa.model.admin.monitoring.NetworkMetrics.networkMetricSet;
import static com.yahoo.vespa.model.admin.monitoring.SystemMetrics.systemMetricSet;
import static com.yahoo.vespa.model.admin.monitoring.VespaMetricSet.vespaMetricSet;
import static java.util.Collections.emptyList;
/**
* This class sets up the 'Vespa' metrics consumer.
*
* @author trygve
* @author gjoranv
*/
public class VespaMetricsConsumer {
public static final String VESPA_CONSUMER_ID = VespaMetrics.VESPA_CONSUMER_ID.id;
private static final MetricSet defaultConsumerMetrics = new MetricSet("vespa-consumer-metrics",
emptyList(),
ImmutableList.of(vespaMetricSet,
systemMetricSet,
networkMetricSet));
public static MetricsConsumer getVespaMetricsConsumer() {
return new MetricsConsumer(VESPA_CONSUMER_ID, defaultConsumerMetrics);
}
}
|
Make OptionList return gracefully when iterating over falsy values | import PropTypes from "prop-types";
import React, { Component } from "react";
import {
StyleSheet,
ScrollView,
View,
TouchableWithoutFeedback,
ViewPropTypes
} from "react-native";
export default class OptionList extends Component {
static defaultProps = {
onSelect: () => {}
};
static propTypes = {
style: ViewPropTypes.style,
onSelect: PropTypes.func
};
render() {
const { style, children, onSelect, selectedStyle, selected } = this.props;
const renderedItems = React.Children.map(children, (item, key) => (
if (!item) return null
<TouchableWithoutFeedback
key={key}
style={{ borderWidth: 0 }}
onPress={() => onSelect(item.props.children, item.props.value)}
>
<View
style={[
{ borderWidth: 0 },
item.props.value === selected ? selectedStyle : null
]}
>
{item}
</View>
</TouchableWithoutFeedback>
));
return (
<View style={[styles.scrollView, style]}>
<ScrollView automaticallyAdjustContentInsets={false} bounces={false}>
{renderedItems}
</ScrollView>
</View>
);
}
}
var styles = StyleSheet.create({
scrollView: {
height: 120,
width: 300,
borderWidth: 1
}
});
| import PropTypes from "prop-types";
import React, { Component } from "react";
import {
StyleSheet,
ScrollView,
View,
TouchableWithoutFeedback,
ViewPropTypes
} from "react-native";
export default class OptionList extends Component {
static defaultProps = {
onSelect: () => {}
};
static propTypes = {
style: ViewPropTypes.style,
onSelect: PropTypes.func
};
render() {
const { style, children, onSelect, selectedStyle, selected } = this.props;
const renderedItems = React.Children.map(children, (item, key) => (
<TouchableWithoutFeedback
key={key}
style={{ borderWidth: 0 }}
onPress={() => onSelect(item.props.children, item.props.value)}
>
<View
style={[
{ borderWidth: 0 },
item.props.value === selected ? selectedStyle : null
]}
>
{item}
</View>
</TouchableWithoutFeedback>
));
return (
<View style={[styles.scrollView, style]}>
<ScrollView automaticallyAdjustContentInsets={false} bounces={false}>
{renderedItems}
</ScrollView>
</View>
);
}
}
var styles = StyleSheet.create({
scrollView: {
height: 120,
width: 300,
borderWidth: 1
}
});
|
[Backend] Include exception cause's stacktrace in JSON in case of error. | package org.talend.dataprep.exception;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
class TDPException extends RuntimeException {
private static final Logger LOGGER = LoggerFactory.getLogger(TDPException.class);
private final Messages code;
private final String message;
private Throwable cause;
public TDPException(Messages code, String message, Throwable cause) {
super(message, cause);
this.code = code;
this.message = message;
this.cause = cause;
}
public void writeTo(Writer writer) {
try {
JsonGenerator generator = (new JsonFactory()).createGenerator(writer);
generator.writeStartObject();
{
generator.writeStringField("code", code.getProduct() + '_' + code.getGroup() + '_' + code.getCode()); //$NON-NLS-1$
generator.writeStringField("message", message); //$NON-NLS-1$
if (cause != null) {
generator.writeStringField("cause", cause.getMessage()); //$NON-NLS-1$
final StringWriter details = new StringWriter();
cause.printStackTrace(new PrintWriter(details));
generator.writeStringField("details", details.toString()); //$NON-NLS-1$
}
}
generator.writeEndObject();
generator.flush();
} catch (IOException e) {
LOGGER.error("Unable to write exception to " + writer + ".", e);
}
}
}
| package org.talend.dataprep.exception;
import java.io.IOException;
import java.io.Writer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
class TDPException extends RuntimeException {
private static final Logger LOGGER = LoggerFactory.getLogger(TDPException.class);
private final Messages code;
private final String message;
private Throwable cause;
public TDPException(Messages code, String message, Throwable cause) {
super(message, cause);
this.code = code;
this.message = message;
this.cause = cause;
}
public void writeTo(Writer writer) {
try {
JsonGenerator generator = (new JsonFactory()).createGenerator(writer);
generator.writeStartObject();
{
generator.writeStringField("code", code.getProduct() + '_' + code.getGroup() + '_' + code.getCode()); //$NON-NLS-1$
generator.writeStringField("message", message); //$NON-NLS-1$
if (cause != null) {
generator.writeStringField("cause", cause.getMessage()); //$NON-NLS-1$
}
}
generator.writeEndObject();
generator.flush();
} catch (IOException e) {
LOGGER.error("Unable to write exception to " + writer + ".", e);
}
}
}
|
Change id query parameter to route parameter | 'use strict'
module.exports = (function(){
/**
* Import modules
*/
const footballDb = require('./../db/footballDb')
/**
* football module API
*/
return {
'leagues': leagues,
'leagueTable_id': leagueTable_id
}
/**
* football module API -- leagueTable
*/
function leagueTable_id(id) { // Auto parses id from query-string
return footballDb
.leagueTable(id)
.then(league => {
league.title = 'League Table'
return league
})
}
/**
* football module API -- leagues
*/
function leagues() {
return footballDb
.leagues()
.then(leagues => {
leagues = leaguesWithLinks(leagues)
return {
'title':'Leagues',
'leagues': leagues
}
})
}
/**
* Utility auxiliary function
*/
function leaguesWithLinks(leagues) {
return leagues.map(item => {
item.leagueHref = "/football/leagueTable/" + item.id
return item
})
}
})() | 'use strict'
module.exports = (function(){
/**
* Import modules
*/
const footballDb = require('./../db/footballDb')
/**
* football module API
*/
return {
'leagues': leagues,
'leagueTable': leagueTable
}
/**
* football module API -- leagueTable
*/
function leagueTable(id) { // Auto parses id from query-string
return footballDb
.leagueTable(id)
.then(league => {
league.title = 'League Table'
return league
})
}
/**
* football module API -- leagues
*/
function leagues() {
return footballDb
.leagues()
.then(leagues => {
leagues = leaguesWithLinks(leagues)
return {
'title':'Leagues',
'leagues': leagues
}
})
}
/**
* Utility auxiliary function
*/
function leaguesWithLinks(leagues) {
return leagues.map(item => {
item.leagueHref = "/football/leagueTable?id=" + item.id
return item
})
}
})() |
Build production without any devtool (no source-map) | /**
* webpack configuration for react-to-mdl
*/
const webpack = require('webpack');
const path = require('path');
const libraryName = 'react-to-mdl';
// export config
module.exports = {
// devtool: 'cheap-module-eval-source-map',
devtool: process.env.NODE_ENV == 'production' ? false : 'eval',
entry: {
button: './src/button',
card: './src/card',
dataTable: './src/dataTable',
grid: './src/grid',
layout: './src/layout',
menu: './src/menu',
spinner: './src/spinner',
tabs: './src/tabs',
textfield: './src/textfield',
index: './src/index'
},
externals: [
'classnames',
'material-design-lite',
'react',
'react-dom',
'react-router'
],
output: {
path: path.join(__dirname, 'lib'),
filename: '[name].js',
library: libraryName,
libraryTarget: 'umd',
umdNamedDefine: true
},
module: {
rules: [{
test: /\.jsx?$/,
loader: 'babel-loader',
include: path.join(__dirname, 'src'),
options: {
presets: [
["es2015", {"modules": false}],
"stage-0",
"react"
]
}
}]
}
};
| /**
* webpack configuration for react-to-mdl
*/
const webpack = require('webpack');
const path = require('path');
const libraryName = 'react-to-mdl';
// export config
module.exports = {
// devtool: 'cheap-module-eval-source-map',
devtool: process.env.NODE_ENV == 'production' ? 'source-map' : 'eval',
entry: {
button: './src/button',
card: './src/card',
dataTable: './src/dataTable',
grid: './src/grid',
layout: './src/layout',
menu: './src/menu',
spinner: './src/spinner',
tabs: './src/tabs',
textfield: './src/textfield',
index: './src/index'
},
externals: [
'classnames',
'material-design-lite',
'react',
'react-dom',
'react-router'
],
output: {
path: path.join(__dirname, 'lib'),
filename: '[name].js',
library: libraryName,
libraryTarget: 'umd',
umdNamedDefine: true
},
module: {
rules: [{
test: /\.jsx?$/,
loader: 'babel-loader',
include: path.join(__dirname, 'src'),
options: {
presets: [
["es2015", {"modules": false}],
"stage-0",
"react"
]
}
}]
}
};
|
Tweak CesiumViewer build to avoid some warnings. | var profile = {
basePath : '../..',
baseUrl : '.',
releaseDir : './Build/Apps/CesiumViewer',
action : 'release',
cssOptimize : 'comments',
mini : true,
optimize : 'closure',
layerOptimize : 'closure',
stripConsole : 'all',
selectorEngine : 'acme',
layers : {
'dojo/dojo' : {
include : ['dojo/dojo', 'CesiumViewer/CesiumViewer', 'CesiumViewer/boot'],
boot : true,
customBase : true
}
},
packages : [{
name : 'CesiumViewer',
destLocation : '.'
}],
staticHasFeatures : {
'dojo-trace-api' : 0,
'dojo-log-api' : 0,
'dojo-publish-privates' : 0,
'dojo-sync-loader' : 0,
'dojo-xhr-factory' : 0,
'dojo-test-sniff' : 0,
'dom-addeventlistener' : 1,
'dojo-firebug' : 0
},
resourceTags : {
miniExclude : function(filename, mid) {
"use strict";
return mid in {
'CesiumViewer/CesiumViewer.profile' : 1
};
},
amd : function(filename, mid) {
"use strict";
return (/\.js$/).test(filename);
}
}
}; | var profile = {
basePath : '../..',
baseUrl : '.',
releaseDir : './Build/Apps/CesiumViewer',
action : 'release',
cssOptimize : 'comments',
mini : true,
optimize : 'closure',
layerOptimize : 'closure',
stripConsole : 'all',
selectorEngine : 'acme',
layers : {
'dojo/dojo' : {
include : ['dojo/dojo', 'CesiumViewer/CesiumViewer', 'CesiumViewer/boot'],
boot : true,
customBase : true
}
},
packages : [{
name : 'CesiumViewer',
destLocation : '.'
}],
staticHasFeatures : {
'dojo-trace-api' : 0,
'dojo-log-api' : 0,
'dojo-publish-privates' : 0,
'dojo-sync-loader' : 0,
'dojo-xhr-factory' : 0,
'dojo-test-sniff' : 0
},
resourceTags : {
miniExclude : function(filename, mid) {
"use strict";
return mid in {
'CesiumViewer/CesiumViewer.profile' : 1
};
},
amd : function(filename, mid) {
"use strict";
return (/\.js$/).test(filename);
}
}
}; |
Write ajax post request for pin form submit | $(document).ready(function() {
$("#map-placeholder").on("click", "#new-gem-button", function(event){
event.preventDefault();
var url = $(event.target).attr('href');
$.ajax({
url: url,
type: 'get'
}).done(function(data){
var $popupForm = $(data).children('section');
$('body').append($popupForm);
// Global Variable from _map.html
if(addGemPopup){
addGemPopup.remove();
addGemPopup = null;
}
});
});
$('body').on('click', '#new_pin_cancel', function(event) {
event.preventDefault();
var $form = $(this).closest('section.popup-new-pin-form');
$($form).remove();
});
$('body').on("submit", "#new_pin", function(event) {
event.preventDefault();
var $form = $(this);
var data = $form.serialize();
$.ajax({
type: 'post',
url: '/pins',
data: data,
dataType: 'html',
success: function(response) {
console.log("RESPONSE", response)
var $pintagForm = $(response);
$('#new_pin').append($pintagForm);
},
fail: function(response) {
console.log("fail", response);
},
error: function(response, jqXHR) {
console.log("ERROR", response);
console.log("xhr", jqXHR);
}
});
});
});
| $(document).ready(function() {
$("#map-placeholder").on("click", "#new-gem-button", function(event){
event.preventDefault();
var url = $(event.target).attr('href');
$.ajax({
url: url,
type: 'get'
}).done(function(data){
var $popupForm = $(data).children('section');
$('body').append($popupForm);
// Global Variable from _map.html
if(addGemPopup){
addGemPopup.remove();
addGemPopup = null;
}
});
});
$('body').on('click', '#new_pin_cancel', function(event) {
event.preventDefault();
var $form = $(this).closest('section.popup-new-pin-form');
$($form).remove();
});
$('body').on("submit", "#new_pin", function(event) {
event.preventDefault();
var $form = $(this);
var data = $form.serialize();
console.log(data)
$.ajax({
type: 'post',
url: '/pins',
data: data
}).done(function(response) {
console.log("RESPONSE", response)
// var $pintagForm = $(response).children('.pintag-form-container');
// debugger;
// var $section = $form.closest('section.popup-new-pin-form');
// $('.new-pin').append($pintagForm);
}).error(function(response) {
console.log("ERROR", response);
})
});
});
//
// $section.remove();
|
Fix UMD build for webpack 2
Closes #4 | import path from 'path';
const projectRoot = path.join(__dirname, '..');
export default {
cache: true,
entry: [
path.join(projectRoot, 'src', 'hibp.js'),
],
output: {
library: 'hibp',
libraryTarget: 'umd',
path: path.join(projectRoot, 'dist'),
},
module: {
rules: [
{
test: /\.js$/,
include: [
path.join(projectRoot, 'src'),
],
use: [
{
loader: 'babel-loader',
options: {
babelrc: false,
cacheDirectory: true,
plugins: [
'add-module-exports',
],
presets: [
[
'env',
{
targets: {
browsers: [
'> 1%',
'last 2 versions',
],
},
},
],
],
},
},
],
},
],
},
node: {
fs: 'empty',
module: 'empty',
Buffer: false, // axios 0.16.1
},
};
| import path from 'path';
const projectRoot = path.join(__dirname, '..');
export default {
cache: true,
entry: [
path.join(projectRoot, 'src', 'hibp.js'),
],
output: {
library: 'hibp',
libraryTarget: 'umd',
path: path.join(projectRoot, 'dist'),
},
module: {
rules: [
{
test: /\.js$/,
include: [
path.join(projectRoot, 'src'),
],
use: [
{
loader: 'babel-loader',
options: {
babelrc: false,
cacheDirectory: true,
plugins: [
'add-module-exports',
],
presets: [
[
'env',
{
modules: false,
targets: {
browsers: [
'> 1%',
'last 2 versions',
],
},
},
],
],
},
},
],
},
],
},
node: {
fs: 'empty',
module: 'empty',
Buffer: false, // axios 0.16.1
},
};
|
Convert model not found exceptions to 404 not found exceptions. | <?php
namespace App\Exceptions;
use Exception;
use Illuminate\Http\Response;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Laravel\Lumen\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
AuthorizationException::class,
HttpException::class,
ModelNotFoundException::class,
ValidationException::class,
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $e
* @return void
*/
public function report(Exception $e)
{
parent::report($e);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
// Convert model not found exceptions to 404 not found exceptions.
if ($e instanceof ModelNotFoundException) {
$e = new NotFoundHttpException($e->getMessage(), $e);
}
if ($e instanceof NotFoundHttpException) {
// 404 error.
$resp = new Response();
$resp->setStatusCode(404);
$resp->setContent('');
return $resp;
}
return parent::render($request, $e);
}
}
| <?php
namespace App\Exceptions;
use Exception;
use Illuminate\Http\Response;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Laravel\Lumen\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
AuthorizationException::class,
HttpException::class,
ModelNotFoundException::class,
ValidationException::class,
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $e
* @return void
*/
public function report(Exception $e)
{
parent::report($e);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
if ($e instanceof NotFoundHttpException) {
// 404 error.
$resp = new Response();
$resp->setStatusCode(404);
$resp->setContent('');
return $resp;
}
return parent::render($request, $e);
}
}
|
Fix units on wallet info screen | 'use strict';
angular.module('copayApp.controllers').controller('walletInfoController',
function ($scope, $rootScope, $timeout, profileService, configService, lodash, coloredCoins, walletService) {
function initAssets(assets) {
if (!assets) {
this.assets = [];
return;
}
this.assets = lodash.values(assets)
.map(function(asset) {
return {
assetName: asset.metadata.assetName,
assetId: asset.assetId,
balanceStr: coloredCoins.formatAssetAmount(asset.amount, asset)
};
})
.concat([{
assetName: 'Bitcoin',
assetId: 'bitcoin',
balanceStr: walletService.btcBalance
}])
.sort(function(a1, a2) {
return a1.assetName > a2.assetName;
});
}
var setAssets = initAssets.bind(this);
if (!coloredCoins.onGoingProcess) {
setAssets(coloredCoins.assets);
} else {
this.assets = null;
}
var disableAssetListener = $rootScope.$on('ColoredCoins/AssetsUpdated', function (event, assets) {
setAssets(assets);
$timeout(function() {
$rootScope.$digest();
});
});
$scope.$on('$destroy', function () {
disableAssetListener();
});
this.walletAsset = walletService.updateWalletAsset();
this.setWalletAsset = function(asset) {
walletService.setWalletAsset(asset);
};
});
| 'use strict';
angular.module('copayApp.controllers').controller('walletInfoController',
function ($scope, $rootScope, $timeout, profileService, configService, lodash, coloredCoins, walletService) {
function initAssets(assets) {
if (!assets) {
this.assets = [];
return;
}
this.assets = lodash.values(assets)
.map(function(asset) {
return {
assetName: asset.metadata.assetName,
assetId: asset.assetId,
balanceStr: coloredCoins.formatAssetAmount(asset.amount, asset.asset, walletService.walletUnit)
};
})
.concat([{
assetName: 'Bitcoin',
assetId: 'bitcoin',
balanceStr: walletService.btcBalance
}])
.sort(function(a1, a2) {
return a1.assetName > a2.assetName;
});
}
var setAssets = initAssets.bind(this);
if (!coloredCoins.onGoingProcess) {
setAssets(coloredCoins.assets);
} else {
this.assets = null;
}
var disableAssetListener = $rootScope.$on('ColoredCoins/AssetsUpdated', function (event, assets) {
setAssets(assets);
$timeout(function() {
$rootScope.$digest();
});
});
$scope.$on('$destroy', function () {
disableAssetListener();
});
this.walletAsset = walletService.updateWalletAsset();
this.setWalletAsset = function(asset) {
walletService.setWalletAsset(asset);
};
});
|
Change bs4 html parser to html.parser
This is to fix wrapping with <html> tags. | import re
from bs4 import BeautifulSoup
from django import template
register = template.Library()
@register.filter(is_safe=True)
def baseurl(html, base):
if not base.endswith('/'):
base += '/'
absurl = re.compile(r'\s*[a-zA-Z][a-zA-Z0-9\+\.\-]*:') # Starts with scheme:.
def isabs(url):
return url.startswith('/') or absurl.match(url)
soup = BeautifulSoup(html, 'html.parser')
for link in soup.findAll('a', href=True):
if not isabs(link['href']):
link['href'] = base + link['href']
for img in soup.findAll('img', src=True):
if not isabs(img['src']):
img['src'] = base + img['src']
elements = soup.findAll(style=True) # All styled elements.
for e in elements:
def func(m):
url = m.group(2)
if not isabs(url):
url = base + url
return m.group(1) + url + m.group(3)
e['style'] = re.sub(r'''(url\(\s*)([^\s\)\"\']*)(\s*\))''', func, e['style'])
e['style'] = re.sub(r'''(url\(\s*")([^\s\"]*)("\s*\))''', func, e['style'])
e['style'] = re.sub(r'''(url\(\s*')([^\s\']*)('\s*\))''', func, e['style'])
return str(soup)
| import re
from bs4 import BeautifulSoup
from django import template
register = template.Library()
@register.filter(is_safe=True)
def baseurl(html, base):
if not base.endswith('/'):
base += '/'
absurl = re.compile(r'\s*[a-zA-Z][a-zA-Z0-9\+\.\-]*:') # Starts with scheme:.
def isabs(url):
return url.startswith('/') or absurl.match(url)
soup = BeautifulSoup(html)
for link in soup.findAll('a', href=True):
if not isabs(link['href']):
link['href'] = base + link['href']
for img in soup.findAll('img', src=True):
if not isabs(img['src']):
img['src'] = base + img['src']
elements = soup.findAll(style=True) # All styled elements.
for e in elements:
def func(m):
url = m.group(2)
if not isabs(url):
url = base + url
return m.group(1) + url + m.group(3)
e['style'] = re.sub(r'''(url\(\s*)([^\s\)\"\']*)(\s*\))''', func, e['style'])
e['style'] = re.sub(r'''(url\(\s*")([^\s\"]*)("\s*\))''', func, e['style'])
e['style'] = re.sub(r'''(url\(\s*')([^\s\']*)('\s*\))''', func, e['style'])
return str(soup)
|
Fix empty pixel set list message | from django.core.urlresolvers import reverse
from apps.core.factories import PIXELER_PASSWORD, PixelerFactory
from apps.core.tests import CoreFixturesTestCase
from apps.core.management.commands.make_development_fixtures import (
make_development_fixtures
)
class PixelSetListViewTestCase(CoreFixturesTestCase):
def setUp(self):
self.user = PixelerFactory(
is_active=True,
is_staff=True,
is_superuser=True,
)
self.client.login(
username=self.user.username,
password=PIXELER_PASSWORD,
)
self.url = reverse('explorer:pixelset_list')
def test_renders_pixelset_list_template(self):
response = self.client.get(self.url)
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'explorer/pixelset_list.html')
def test_renders_empty_message(self):
response = self.client.get(self.url)
expected = (
'<td colspan="8" class="empty">'
'No pixel set matches your query'
'</td>'
)
self.assertContains(response, expected, html=True)
def test_renders_pixelset_list(self):
make_development_fixtures(n_pixel_sets=12)
response = self.client.get(self.url)
self.assertContains(
response,
'<tr class="pixelset">',
count=10
)
| from django.core.urlresolvers import reverse
from apps.core.factories import PIXELER_PASSWORD, PixelerFactory
from apps.core.tests import CoreFixturesTestCase
from apps.core.management.commands.make_development_fixtures import (
make_development_fixtures
)
class PixelSetListViewTestCase(CoreFixturesTestCase):
def setUp(self):
self.user = PixelerFactory(
is_active=True,
is_staff=True,
is_superuser=True,
)
self.client.login(
username=self.user.username,
password=PIXELER_PASSWORD,
)
self.url = reverse('explorer:pixelset_list')
def test_renders_pixelset_list_template(self):
response = self.client.get(self.url)
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'explorer/pixelset_list.html')
def test_renders_empty_message(self):
response = self.client.get(self.url)
expected = (
'<td colspan="8" class="empty">'
'No pixel set has been submitted yet'
'</td>'
)
self.assertContains(response, expected, html=True)
def test_renders_pixelset_list(self):
make_development_fixtures(n_pixel_sets=12)
response = self.client.get(self.url)
self.assertContains(
response,
'<tr class="pixelset">',
count=10
)
|
Use kwargs when calling User.__init__ | from faker import Faker
import click
from app.database import db
from app.user.models import User
@click.option('--num_users', default=5, help='Number of users.')
def populate_db(num_users):
"""Populates the database with seed data."""
fake = Faker()
users = []
for _ in range(num_users):
users.append(
User(
username=fake.user_name(),
email=fake.email(),
password=fake.word() + fake.word(),
remote_addr=fake.ipv4()
)
)
users.append(
User(
username='cburmeister',
email='[email protected]',
password='test123',
remote_addr=fake.ipv4(),
active=True,
is_admin=True
)
)
for user in users:
db.session.add(user)
db.session.commit()
def create_db():
"""Creates the database."""
db.create_all()
def drop_db():
"""Drops the database."""
if click.confirm('Are you sure?', abort=True):
db.drop_all()
def recreate_db():
"""Same as running drop_db() and create_db()."""
drop_db()
create_db()
| from faker import Faker
import click
from app.database import db
from app.user.models import User
@click.option('--num_users', default=5, help='Number of users.')
def populate_db(num_users):
"""Populates the database with seed data."""
fake = Faker()
users = []
for _ in range(num_users):
users.append(
User(
fake.user_name(),
fake.email(),
fake.word() + fake.word(),
fake.ipv4()
)
)
users.append(
User(
'cburmeister',
'[email protected]',
'test123',
fake.ipv4(),
active=True,
is_admin=True
)
)
for user in users:
db.session.add(user)
db.session.commit()
def create_db():
"""Creates the database."""
db.create_all()
def drop_db():
"""Drops the database."""
if click.confirm('Are you sure?', abort=True):
db.drop_all()
def recreate_db():
"""Same as running drop_db() and create_db()."""
drop_db()
create_db()
|
Resolve style errors on data block | var Data = require('../../lib/data');
module.exports = {
className: 'data',
template: require('./index.html'),
data: {
name: 'Data',
icon: '/images/blocks_text.png',
attributes: {
label: {
label: 'Header Text',
type: 'string',
value: '',
placeholder: 'Responses',
skipAutoRender: true
},
color: {
label: 'Header and Title Text Color',
type: 'color',
value: '#36494A',
skipAutoRender: true
}
},
currentDataSets: [],
initialDataLoaded: false,
isInteractive: false,
sortOldest: false
},
ready: function () {
var self = this;
if (
!self.$data ||
!self.$data.currentDataSets ||
self.$data.currentDataSets.length === 0
) {
self.$data.initialDataLoaded = false;
}
// Fetch collected Data
self.currentDataSets = [];
if (!self.isEditing) {
var data = new Data(self.$parent.$parent.$data.app.id);
data.getAllDataSets(function (currentDataSets) {
self.$data.initialDataLoaded = true;
self.currentDataSets = currentDataSets;
});
} else {
self.$data.initialDataLoaded = true;
}
}
};
| var Data = require('../../lib/data');
module.exports = {
className: 'data',
template: require('./index.html'),
data: {
name: 'Data',
icon: '/images/blocks_text.png',
attributes: {
label: {
label: 'Header Text',
type: 'string',
value: '',
placeholder: 'Responses',
skipAutoRender: true
},
color: {
label: 'Header and Title Text Color',
type: 'color',
value: '#36494A',
skipAutoRender: true
}
},
currentDataSets: [],
initialDataLoaded: false,
isInteractive: false,
sortOldest: false
},
ready: function (){
var self = this;
if (!self.$data || !self.$data.currentDataSets || self.$data.currentDataSets.length === 0) self.$data.initialDataLoaded = false;
// Fetch collected Data
self.currentDataSets = [];
if(!self.isEditing) {
var data = new Data(self.$parent.$parent.$data.app.id);
data.getAllDataSets(function(currentDataSets) {
self.$data.initialDataLoaded = true;
self.currentDataSets = currentDataSets;
});
}
else {
self.$data.initialDataLoaded = true;
}
}
};
|
Adjust the ds deployment example to use the directly-usable
DatasourceArchive. | package org.wildfly.swarm.examples.ds.deployment;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.wildfly.swarm.Swarm;
import org.wildfly.swarm.container.Container;
import org.wildfly.swarm.datasources.DatasourceArchive;
import org.wildfly.swarm.jaxrs.JAXRSArchive;
import org.wildfly.swarm.spi.api.JARArchive;
/**
* @author Bob McWhirter
*/
public class Main {
public static void main(String[] args) throws Exception {
Container container = new Container();
container.start();
// Create a JDBC driver deployment using maven groupId:artifactId
// The version is resolved from your pom.xml's <dependency>
container.deploy(Swarm.artifact("com.h2database:h2", "h2"));
// Create a DS deployment
DatasourceArchive dsArchive = ShrinkWrap.create(DatasourceArchive.class);
dsArchive.dataSource("ExampleDS", (ds) -> {
ds.connectionUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE");
ds.driverName("h2");
ds.userName("sa");
ds.password("sa");
});
// Deploy the datasource
container.deploy(dsArchive);
JAXRSArchive appDeployment = ShrinkWrap.create(JAXRSArchive.class);
appDeployment.addResource(MyResource.class);
// Deploy your app
container.deploy(appDeployment);
}
}
| package org.wildfly.swarm.examples.ds.deployment;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.wildfly.swarm.Swarm;
import org.wildfly.swarm.container.Container;
import org.wildfly.swarm.datasources.DatasourceArchive;
import org.wildfly.swarm.jaxrs.JAXRSArchive;
import org.wildfly.swarm.spi.api.JARArchive;
/**
* @author Bob McWhirter
*/
public class Main {
public static void main(String[] args) throws Exception {
Container container = new Container();
container.start();
// Create a JDBC driver deployment using maven groupId:artifactId
// The version is resolved from your pom.xml's <dependency>
container.deploy(Swarm.artifact("com.h2database:h2", "h2"));
// Create a DS deployment
JARArchive dsArchive = ShrinkWrap.create(JARArchive.class);
dsArchive.as(DatasourceArchive.class).dataSource("ExampleDS", (ds) -> {
ds.connectionUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE");
ds.driverName("h2");
ds.userName("sa");
ds.password("sa");
});
// Deploy the datasource
container.deploy(dsArchive);
JAXRSArchive appDeployment = ShrinkWrap.create(JAXRSArchive.class);
appDeployment.addResource(MyResource.class);
// Deploy your app
container.deploy(appDeployment);
}
}
|
Allow quit on first page without reset prompt | define(["dist/local_object"], function(LocalObject){
function Pipeline(id, finalNode, resetPage, overwrite){
this.id = id;
this.finalNode = finalNode;
this.resetPage = resetPage;
this.indexObj = new LocalObject(this.id, overwrite);
}
Pipeline.prototype.nodes = [];
Pipeline.prototype.add = function(runFn){
var that = this;
this.nodes.push(function(){
runFn(function(){that.runNext()});
});
};
Pipeline.prototype.start = function(){
var that = this;
if(this.indexObj.get("index") === undefined){
this.run(0);
} else {
var index = that.indexObj.get("index");
if(index === 0){
this.run(0);
} else {
this.resetPage(function(reset){
if(reset){
that.run(0);
} else {
that.run(index);
}
});
}
}
};
Pipeline.prototype.runNext = function(){
var index = this.indexObj.get("index") + 1;
this.run(index);
};
Pipeline.prototype.run = function(index){
this.indexObj.set("index", index);
var node = this.nodes[index];
if(node){
node();
} else {
this.finalNode();
this.indexObj = new LocalObject(this.id, true);
}
}
console.log("pipeline", Pipeline);
return Pipeline;
});
| define(["dist/local_object"], function(LocalObject){
function Pipeline(id, finalNode, resetPage, overwrite){
this.id = id;
this.finalNode = finalNode;
this.resetPage = resetPage;
this.indexObj = new LocalObject(this.id, overwrite);
}
Pipeline.prototype.nodes = [];
Pipeline.prototype.add = function(runFn){
var that = this;
this.nodes.push(function(){
runFn(function(){that.runNext()});
});
};
Pipeline.prototype.start = function(){
var that = this;
if(this.indexObj.get("index") === undefined){
this.run(0);
} else {
this.resetPage(function(reset){
if(reset){
that.run(0);
} else {
that.run(that.indexObj.get("index"));
}
});
}
};
Pipeline.prototype.runNext = function(){
var index = this.indexObj.get("index") + 1;
this.run(index);
};
Pipeline.prototype.run = function(index){
this.indexObj.set("index", index);
var node = this.nodes[index];
if(node){
node();
} else {
this.finalNode();
this.indexObj = new LocalObject(this.id, true);
}
}
console.log("pipeline", Pipeline);
return Pipeline;
});
|
Update select to remove warnning messages, use MenuItem instead | /**
* Created by steve on 15/09/15.
*/
import React from 'react';
import ValidationMixin from './ValidationMixin';
import MenuItem from 'material-ui/lib/menus/menu-item';
const SelectField = require('material-ui/lib/select-field');
class Select extends React.Component {
constructor(props) {
super(props);
this.onSelected = this.onSelected.bind(this);
this.state = {
currentValue: this.props.form.titleMap != null ? this.props.form.titleMap[0].value : ""
};
}
onSelected(event, selectedIndex, menuItem) {
this.setState({
currentValue: menuItem
});
event.target.value = event.target.textContent;
this.props.onChangeValidate(event);
}
render() {
const menuItems = this.props.form.titleMap.map((item, idx) => (
<MenuItem key={idx}
primaryText={item.name}
value={item.value} />
));
return (
<SelectField
value={this.state.currentValue}
floatingLabelText={this.props.form.title}
onChange={this.onSelected}
fullWidth={true} >
{menuItems}
</SelectField>
);
}
}
export default ValidationMixin(Select);
| /**
* Created by steve on 15/09/15.
*/
import React from 'react';
import ValidationMixin from './ValidationMixin';
const SelectField = require('material-ui/lib/select-field');
class Select extends React.Component {
constructor(props) {
super(props);
this.onSelected = this.onSelected.bind(this);
this.state = {
currentValue: this.props.form.titleMap != null ? this.props.form.titleMap[0].value : ""
};
}
onSelected(event, selectedIndex, menuItem) {
this.setState({
currentValue: menuItem.value
});
event.target.value = event.target.textContent;
this.props.onChangeValidate(event);
}
render() {
return (
<SelectField
menuItems={this.props.form.titleMap}
value={this.state.currentValue}
displayMember="name"
valueMember="value"
floatingLabelText={this.props.form.title}
onChange={this.onSelected}
fullWidth={true} />
);
}
}
export default ValidationMixin(Select);
|
Return a Link for collection fields | <?php
namespace SoliantConsulting\Apigility\Server\Hydrator\Strategy;
use Zend\Stdlib\Hydrator\Strategy\StrategyInterface;
use DoctrineModule\Persistence\ObjectManagerAwareInterface;
use DoctrineModule\Persistence\ProvidesObjectManager;
use DoctrineModule\Stdlib\Hydrator\Strategy\AbstractCollectionStrategy;
use ZF\Hal\Collection as HalCollection;
use ZF\Hal\Link\Link;
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceManagerAwareInterface;
class Collection extends AbstractCollectionStrategy
implements StrategyInterface, ServiceManagerAwareInterface //, ObjectManagerAwareInterface
{
use ProvidesObjectManager;
protected $serviceManager;
public function setServiceManager(ServiceManager $serviceManager)
{
$this->serviceManager = $serviceManager;
return $this;
}
public function getServiceManager()
{
return $this->serviceManager;
}
public function extract($value)
{
$config = $this->getServiceManager()->get('Config');
$config = $config['zf-hal']['metadata_map'][$value->getTypeClass()->name];
$link = new Link($this->getCollectionName());
$link->setRoute($config['route_name']);
$link->setRouteParams(array('id' => null));
$mapping = $value->getMapping();
$link->setRouteOptions(array(
'query' => array(
'query' => array(
array('field' =>$mapping['mappedBy'], 'type'=>'eq', 'value' => $value->getOwner()->getId()),
),
),
));
return $link;
}
public function hydrate($value)
{
// hydrate
die('hydrate apigility collection');
}
} | <?php
namespace SoliantConsulting\Apigility\Server\Hydrator\Strategy;
use Zend\Stdlib\Hydrator\Strategy\StrategyInterface;
use DoctrineModule\Persistence\ObjectManagerAwareInterface;
use DoctrineModule\Persistence\ProvidesObjectManager;
use DoctrineModule\Stdlib\Hydrator\Strategy\AbstractCollectionStrategy;
use ZF\Hal\Collection as HalCollection;
use ZF\Hal\Link\Link;
class Collection extends AbstractCollectionStrategy
implements StrategyInterface, ObjectManagerAwareInterface
{
use ProvidesObjectManager;
public function extract($value)
{
$link = new Link($this->getCollectionName());
return $link;
# $self->setRoute($route);
# $self->setRouteParams($routeParams);
# $resource->getLinks()->add($self, true);
# print_r(get_class_methods($value));
# print_r(($value->count() . ' count'));
#die();
die($this->getCollectionName());
return new HalCollection($this->getObject());
return array(
'_links' => array(
'asdf' => 'fdas',
'asdfasdf' => 'fdasfdas',
),
);
// extract
print_r(get_class($value));
die('extract apigility collection');
}
public function hydrate($value)
{
// hydrate
die('hydrate apigility collection');
}
} |
Fix write path for generate command secret. | <?php
namespace Tymon\JWTAuth\Commands;
use Illuminate\Support\Str;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
class JWTGenerateCommand extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'jwt:generate';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Set the JWTAuth secret key used to sign the tokens';
/**
* Execute the console command.
*
* @return void
*/
public function fire()
{
$key = $this->getRandomKey();
if ($this->option('show')) {
return $this->line('<comment>'.$key.'</comment>');
}
$path = config_path('jwt.php');
if (file_exists($path)) {
file_put_contents($path, str_replace(
$this->laravel['config']['jwt.secret'], $key, file_get_contents($path)
));
}
$this->laravel['config']['jwt.secret'] = $key;
$this->info("jwt-auth secret [$key] set successfully.");
}
/**
* Generate a random key for the JWT Auth secret.
*
* @return string
*/
protected function getRandomKey()
{
return Str::random(32);
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return [
['show', null, InputOption::VALUE_NONE, 'Simply display the key instead of modifying files.'],
];
}
}
| <?php
namespace Tymon\JWTAuth\Commands;
use Illuminate\Support\Str;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
class JWTGenerateCommand extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'jwt:generate';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Set the JWTAuth secret key used to sign the tokens';
/**
* Execute the console command.
*
* @return void
*/
public function fire()
{
$key = $this->getRandomKey();
if ($this->option('show')) {
return $this->line('<comment>'.$key.'</comment>');
}
$path = base_path('.env');
if (file_exists($path)) {
file_put_contents($path, str_replace(
$this->laravel['config']['jwt.secret'], $key, file_get_contents($path)
));
}
$this->laravel['config']['jwt.secret'] = $key;
$this->info("jwt-auth secret [$key] set successfully.");
}
/**
* Generate a random key for the JWT Auth secret.
*
* @return string
*/
protected function getRandomKey()
{
return Str::random(32);
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return [
['show', null, InputOption::VALUE_NONE, 'Simply display the key instead of modifying files.'],
];
}
}
|
Revert the removal of an unused import (in [14175]) that was referenced in documentation. Thanks for noticing, clong.
git-svn-id: 554f83ef17aa7291f84efa897c1acfc5d0035373@14359 bcc190cf-cafb-0310-a4f2-bffc1f526a37 | # ACTION_CHECKBOX_NAME is unused, but should stay since its import from here
# has been referenced in documentation.
from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME
from django.contrib.admin.options import ModelAdmin, HORIZONTAL, VERTICAL
from django.contrib.admin.options import StackedInline, TabularInline
from django.contrib.admin.sites import AdminSite, site
def autodiscover():
"""
Auto-discover INSTALLED_APPS admin.py modules and fail silently when
not present. This forces an import on them to register any admin bits they
may want.
"""
import copy
from django.conf import settings
from django.utils.importlib import import_module
from django.utils.module_loading import module_has_submodule
for app in settings.INSTALLED_APPS:
mod = import_module(app)
# Attempt to import the app's admin module.
try:
before_import_registry = copy.copy(site._registry)
import_module('%s.admin' % app)
except:
# Reset the model registry to the state before the last import as
# this import will have to reoccur on the next request and this
# could raise NotRegistered and AlreadyRegistered exceptions
# (see #8245).
site._registry = before_import_registry
# Decide whether to bubble up this error. If the app just
# doesn't have an admin module, we can ignore the error
# attempting to import it, otherwise we want it to bubble up.
if module_has_submodule(mod, 'admin'):
raise
| from django.contrib.admin.options import ModelAdmin, HORIZONTAL, VERTICAL
from django.contrib.admin.options import StackedInline, TabularInline
from django.contrib.admin.sites import AdminSite, site
def autodiscover():
"""
Auto-discover INSTALLED_APPS admin.py modules and fail silently when
not present. This forces an import on them to register any admin bits they
may want.
"""
import copy
from django.conf import settings
from django.utils.importlib import import_module
from django.utils.module_loading import module_has_submodule
for app in settings.INSTALLED_APPS:
mod = import_module(app)
# Attempt to import the app's admin module.
try:
before_import_registry = copy.copy(site._registry)
import_module('%s.admin' % app)
except:
# Reset the model registry to the state before the last import as
# this import will have to reoccur on the next request and this
# could raise NotRegistered and AlreadyRegistered exceptions
# (see #8245).
site._registry = before_import_registry
# Decide whether to bubble up this error. If the app just
# doesn't have an admin module, we can ignore the error
# attempting to import it, otherwise we want it to bubble up.
if module_has_submodule(mod, 'admin'):
raise
|
Create array in old manner (PHP 5.3) | <?php
namespace Ratchet\Session\Serialize;
class PhpHandler implements HandlerInterface {
/**
* Simply reverse behaviour of unserialize method.
* {@inheritdoc}
*/
function serialize(array $data) {
$preSerialized = array();
$serialized = '';
if (count($data)) {
foreach ($data as $bucket => $bucketData) {
$preSerialized[] = $bucket . '|' . serialize($bucketData);
}
$serialized = implode('',$preSerialized);
}
return $serialized;
}
/**
* {@inheritdoc}
* @link http://ca2.php.net/manual/en/function.session-decode.php#108037 Code from this comment on php.net
* @throws \UnexpectedValueException If there is a problem parsing the data
*/
public function unserialize($raw) {
$returnData = array();
$offset = 0;
while ($offset < strlen($raw)) {
if (!strstr(substr($raw, $offset), "|")) {
throw new \UnexpectedValueException("invalid data, remaining: " . substr($raw, $offset));
}
$pos = strpos($raw, "|", $offset);
$num = $pos - $offset;
$varname = substr($raw, $offset, $num);
$offset += $num + 1;
$data = unserialize(substr($raw, $offset));
$returnData[$varname] = $data;
$offset += strlen(serialize($data));
}
return $returnData;
}
}
| <?php
namespace Ratchet\Session\Serialize;
class PhpHandler implements HandlerInterface {
/**
* Simply reverse behaviour of unserialize method.
* {@inheritdoc}
*/
function serialize(array $data) {
$preSerialized = [];
$serialized = '';
if (count($data)) {
foreach ($data as $bucket => $bucketData) {
$preSerialized[] = $bucket . '|' . serialize($bucketData);
}
$serialized = implode('',$preSerialized);
}
return $serialized;
}
/**
* {@inheritdoc}
* @link http://ca2.php.net/manual/en/function.session-decode.php#108037 Code from this comment on php.net
* @throws \UnexpectedValueException If there is a problem parsing the data
*/
public function unserialize($raw) {
$returnData = array();
$offset = 0;
while ($offset < strlen($raw)) {
if (!strstr(substr($raw, $offset), "|")) {
throw new \UnexpectedValueException("invalid data, remaining: " . substr($raw, $offset));
}
$pos = strpos($raw, "|", $offset);
$num = $pos - $offset;
$varname = substr($raw, $offset, $num);
$offset += $num + 1;
$data = unserialize(substr($raw, $offset));
$returnData[$varname] = $data;
$offset += strlen(serialize($data));
}
return $returnData;
}
}
|
Add method to generate config and load config on vendor class | <?php
namespace Core;
/**
* Manage vendor and can automatically detect vendor.
*
* @package Core
*/
class Vendor
{
/**
* Cache vendor list
*
* @var array
*/
private $vendors = array();
public function __construct()
{
if (ENVIRONMENT == 'development')
{
$this->generateConfig();
}
else
{
$this->loadConfig();
}
}
/**
* Generate Config that contain vendor list
*/
private function generateConfig()
{
$dirs = scandir(BASE_PATH);
$length = count($dirs);
$arr = array();
for ($i = 0 ; $i < count($dirs) ; $i++)
{
if ($dirs[$i] != '.' && $dirs[$i] != '..' && $dirs[$i] != '.git' &&
is_dir($dirs[$i]))
{
$arr[] = $dirs[$i];
}
}
$config =& loadClass('Config', 'Core');
$config->save('Vendor', $arr);
$this->vendors = $arr;
}
/**
* Load vendor list from config
*/
private function loadConfig()
{
$config =& loadClass('Config', 'Core');
$arr = $config->load('Vendor');
if ($arr !== false)
{
$this->vendors = $arr;
}
}
/**
* Get vendor list
*
* @return array Vendor list as an array
*/
public function lists()
{
return $this->vendors;
}
}
?>
| <?php
namespace Core;
/**
* Manage vendor and can automatically detect vendor.
*
* @package Core
*/
class Vendor
{
/**
* Cache vendor list
*
* @var array
*/
private $vendors = array();
public function __construct()
{
if (ENVIRONMENT == 'development')
{
$dirs = scandir(BASE_PATH);
$length = count($dirs);
$arr = array();
for ($i = 0 ; $i < count($dirs) ; $i++)
{
if ($dirs[$i] != '.' && $dirs[$i] != '..' && $dirs[$i] != '.git' &&
is_dir($dirs[$i]))
{
$arr[] = $dirs[$i];
}
}
$config =& loadClass('Config', 'Core');
$config->save('Vendor', $arr);
$this->vendors = $arr;
}
else
{
$config =& loadClass('Config', 'Core');
$arr = $config->load('Vendor');
if ($arr !== false)
{
$this->vendors = $arr;
}
}
}
/**
* Get vendor list
*
* @return array Vendor list as an array
*/
public function lists()
{
return $this->vendors;
}
}
?>
|
Test ´ifShortPart´: fix code style | import chai from 'chai'
import ifShortPart from '@/wordbreaker-russian/rules/if-short-part'
describe(
'ifShortPart',
() => {
it(
'Это функция',
() => chai.assert.isFunction(ifShortPart)
)
describe(
'Правильно работает',
() => {
const testCaseArr = [
{
inputWord: 'секуляризм',
expectedOutput: [
true, // с
false, // е
false, // к
false, // у
false, // л
false, // я
false, // р
false, // и
true, // з
true, // м
],
},
{
inputWord: 'акация',
expectedOutput: [
true, // а
false, // к
false, // а
false, // ц
true, // и
true, // я
],
},
]
testCaseArr.forEach(
({inputWord, expectedOutput}) => {
it(
inputWord,
() => {
expectedOutput.forEach(
(result, i) => {
chai.assert.equal(
ifShortPart(
i,
inputWord
),
result
)
}
)
}
)
}
)
}
)
}
)
| import chai from 'chai'
import ifShortPart from '@/wordbreaker-russian/rules/if-short-part'
describe(
'ifShortPart', () => {
it(
'Это функция', () => {
chai.assert.isFunction(ifShortPart)
}
)
it(
'Правильно работает', () => {
const inputs = [
{
position: 0,
word: 'акация',
result: true,
},
{
position: 1,
word: 'акация',
result: false,
},
{
position: 2,
word: 'акация',
result: false,
},
{
position: 3,
word: 'акация',
result: false,
},
{
position: 4,
word: 'акация',
result: true,
},
]
inputs.forEach(
input => {
chai.assert.equal(
ifShortPart(
input.position,
input.word.split('')
),
input.result
)
}
)
}
)
}
)
|
Return true if there are no filters to validate. | var _ = require('lodash');
var RunValidations = require('../utils/RunValidations').run;
var FilterValidations = require('../validations/FilterValidations');
var TimeframeUtils = require('../utils/TimeframeUtils');
var FilterUtils = require('../utils/FilterUtils');
module.exports = {
event_collection: {
msg: 'Choose an Event Collection.',
validate: function(value) {
return value ? true : false;
}
},
filters: {
msg: 'One of your filters is invalid.',
validate: function(filters) {
if (!filters || (_.isArray(filters) && !filters.length)) return true;
for (var i=0; i<filters.length; i++) {
var complete = FilterUtils.isComplete(filters[i]);
var valid = RunValidations(FilterValidations, filters[i]).length === 0;
if (complete && !valid) return false;
}
return true;
}
},
time: {
validate: function(time) {
var time = time || {};
if (TimeframeUtils.timeframeType(time) === 'relative') {
if (time.relativity && time.amount && time.sub_timeframe) {
return true;
} else {
return "You must choose all 3 options for relative timeframes.";
}
} else if (TimeframeUtils.timeframeType(time) === 'absolute') {
if (time.start && time.end) {
return true;
} else {
return "You must provide a start and end time for absolute timeframes.";
}
} else {
return "You must provide a timeframe.";
}
return true;
}
}
}; | var RunValidations = require('../utils/RunValidations').run;
var FilterValidations = require('../validations/FilterValidations');
var TimeframeUtils = require('../utils/TimeframeUtils');
var FilterUtils = require('../utils/FilterUtils');
module.exports = {
event_collection: {
msg: 'Choose an Event Collection.',
validate: function(value) {
return value ? true : false;
}
},
filters: {
msg: 'One of your filters is invalid.',
validate: function(filters) {
for (var i=0; i<filters.length; i++) {
var complete = FilterUtils.isComplete(filters[i]);
var valid = RunValidations(FilterValidations, filters[i]).length === 0;
if (complete && !valid) return false;
}
return true;
}
},
time: {
validate: function(time) {
var time = time || {};
if (TimeframeUtils.timeframeType(time) === 'relative') {
if (time.relativity && time.amount && time.sub_timeframe) {
return true;
} else {
return "You must choose all 3 options for relative timeframes.";
}
} else if (TimeframeUtils.timeframeType(time) === 'absolute') {
if (time.start && time.end) {
return true;
} else {
return "You must provide a start and end time for absolute timeframes.";
}
} else {
return "You must provide a timeframe.";
}
return true;
}
}
}; |
Add sleep on start database | # -*- coding: utf-8 -*-
import logging
from util import full_stack
from workflow.steps.util.base import BaseStep
from workflow.exceptions.error_codes import DBAAS_0022
from workflow.steps.util.restore_snapshot import use_database_initialization_script
from time import sleep
LOG = logging.getLogger(__name__)
class StartDatabase(BaseStep):
def __unicode__(self):
return "Starting database..."
def do(self, workflow_dict):
try:
databaseinfra = workflow_dict['databaseinfra']
instance = workflow_dict['instance']
if databaseinfra.plan.is_ha:
sleep(60)
driver = databaseinfra.get_driver()
driver.start_slave(instance=instance)
return True
except Exception:
traceback = full_stack()
workflow_dict['exceptions']['error_codes'].append(DBAAS_0022)
workflow_dict['exceptions']['traceback'].append(traceback)
return False
def undo(self, workflow_dict):
LOG.info("Running undo...")
try:
databaseinfra = workflow_dict['databaseinfra']
host = workflow_dict['host']
return_code, output = use_database_initialization_script(databaseinfra=databaseinfra,
host=host,
option='stop')
if return_code != 0:
raise Exception(str(output))
return True
except Exception:
traceback = full_stack()
workflow_dict['exceptions']['error_codes'].append(DBAAS_0022)
workflow_dict['exceptions']['traceback'].append(traceback)
return False
| # -*- coding: utf-8 -*-
import logging
from util import full_stack
from workflow.steps.util.base import BaseStep
from workflow.exceptions.error_codes import DBAAS_0022
from workflow.steps.util.restore_snapshot import use_database_initialization_script
LOG = logging.getLogger(__name__)
class StartDatabase(BaseStep):
def __unicode__(self):
return "Starting database..."
def do(self, workflow_dict):
try:
databaseinfra = workflow_dict['databaseinfra']
instance = workflow_dict['instance']
if databaseinfra.plan.is_ha:
driver = databaseinfra.get_driver()
driver.start_slave(instance=instance)
return True
except Exception:
traceback = full_stack()
workflow_dict['exceptions']['error_codes'].append(DBAAS_0022)
workflow_dict['exceptions']['traceback'].append(traceback)
return False
def undo(self, workflow_dict):
LOG.info("Running undo...")
try:
databaseinfra = workflow_dict['databaseinfra']
host = workflow_dict['host']
return_code, output = use_database_initialization_script(databaseinfra=databaseinfra,
host=host,
option='stop')
if return_code != 0:
raise Exception(str(output))
return True
except Exception:
traceback = full_stack()
workflow_dict['exceptions']['error_codes'].append(DBAAS_0022)
workflow_dict['exceptions']['traceback'].append(traceback)
return False
|
Fix total number of values printed | // ****************************************************************
// PowersOf2.java
//
// Print out as many powers of 2 as the user requests
//
// ****************************************************************
import java.util.Scanner;
public class PowersOf2 {
public static void main(String[] args) {
int numPowersOf2; //How many powers of 2 to compute
int nextPowerOf2 = 1; //Current power of 2
int exponent; //Exponent for current power of 2 -- this
//also serves as a counter for the loop
Scanner scan = new Scanner(System.in);
System.out.println("How many powers of 2 would you like printed?");
numPowersOf2 = scan.nextInt();
// add code below each comment to carry out the action
// listed in the comment; more than one statement may be needed
// in some cases
// print a message saying how many powers of 2 will be printed
System.out.println((numPowersOf2 + 1) + " powers of 2 will be printed!");
// initialize exponent -- the first thing printed is 2 to the what?
exponent = 0;
while (exponent <= numPowersOf2) {
//print out current power of 2
System.out.println("2^" + exponent + " = "+ nextPowerOf2);
//find next power of 2 -- how do you get this from the last one?
nextPowerOf2 = nextPowerOf2 * 2;
//increment exponent
exponent++;
}
}
} | // ****************************************************************
// PowersOf2.java
//
// Print out as many powers of 2 as the user requests
//
// ****************************************************************
import java.util.Scanner;
public class PowersOf2 {
public static void main(String[] args) {
int numPowersOf2; //How many powers of 2 to compute
int nextPowerOf2 = 1; //Current power of 2
int exponent; //Exponent for current power of 2 -- this
//also serves as a counter for the loop
Scanner scan = new Scanner(System.in);
System.out.println("How many powers of 2 would you like printed?");
numPowersOf2 = scan.nextInt();
// add code below each comment to carry out the action
// listed in the comment; more than one statement may be needed
// in some cases
// print a message saying how many powers of 2 will be printed
System.out.println(numPowersOf2 + " powers of 2 will be printed!");
// initialize exponent -- the first thing printed is 2 to the what?
exponent = 0;
while (exponent <= numPowersOf2) {
//print out current power of 2
System.out.println("2^" + exponent + " = "+ nextPowerOf2);
//find next power of 2 -- how do you get this from the last one?
nextPowerOf2 = nextPowerOf2 * 2;
//increment exponent
exponent++;
}
}
} |
Fix failing command on Linux. | # :coding: utf-8
# :copyright: Copyright (c) 2013 Martin Pengelly-Phillips
# :license: See LICENSE.txt.
import subprocess
import pickle
import base64
try:
from shlex import quote
except ImportError:
from pipes import quote
from .base import Processor
from .. import pickle_support
class BackgroundProcessor(Processor):
'''Local background processor.'''
def process(self, command, args=None, kw=None):
'''Process *command* with *args* and *kw*.'''
if args is None:
args = ()
if kw is None:
kw = {}
serialised = base64.b64encode(
pickle.dumps(
{'command': command, 'args': args, 'kw': kw},
pickle.HIGHEST_PROTOCOL
)
)
python_statement = (
'import pickle;'
'import base64;'
'data = base64.b64decode(\'{0}\');'
'data = pickle.loads(data);'
'data[\'command\'](*data[\'args\'], **data[\'kw\'])'
).format(serialised.replace("'", r"\'"))
command = ['python', '-c', python_statement]
process = subprocess.Popen(command)
return 'Background process started: {0}'.format(process.pid)
| # :coding: utf-8
# :copyright: Copyright (c) 2013 Martin Pengelly-Phillips
# :license: See LICENSE.txt.
import subprocess
import pickle
import base64
try:
from shlex import quote
except ImportError:
from pipes import quote
from .base import Processor
from .. import pickle_support
class BackgroundProcessor(Processor):
'''Local background processor.'''
def process(self, command, args=None, kw=None):
'''Process *command* with *args* and *kw*.'''
if args is None:
args = ()
if kw is None:
kw = {}
serialised = base64.b64encode(
pickle.dumps(
{'command': command, 'args': args, 'kw': kw},
pickle.HIGHEST_PROTOCOL
)
)
python_statement = (
'import pickle;'
'import base64;'
'data = base64.b64decode(\'{0}\');'
'data = pickle.loads(data);'
'data[\'command\'](*data[\'args\'], **data[\'kw\'])'
).format(serialised.replace("'", r"\'"))
command = ' '.join(['python', '-c', '"{0}"'.format(python_statement)])
process = subprocess.Popen(command)
return 'Background process started: {0}'.format(process.pid)
|
Fix typo in matplotlib setup. | import tables
import tables as tb
try:
import fipy
import fipy as fp
except:
pass
import numpy
import numpy as np
import scipy
import scipy as spy
import matplotlib.pyplot as plt
def gitCommand(cmd, verbose=False):
from subprocess import Popen, PIPE
p = Popen(['git'] + cmd, shell=False, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
p.wait()
out = p.stdout.read()
if verbose:
print out
print p.stderr.read()
return out
def gitCurrentCommit():
return gitCommand(['log', '--oneline', '-1', '--abbrev=12', '--format="%h"']).strip().strip('"')
class _Prompt(object):
def __str__(self):
import datetime
sha = gitCommand(['log', '--oneline', '-1', '--abbrev=12', '--format="%h"']).strip().strip('"')
if len(sha) > 0:
sha = ' ' + sha
return '[' + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + sha + ']'
class _PromptIn(_Prompt):
def __str__(self):
return super(_PromptIn, self).__str__() + ' >>> '
class _PromptOut(_Prompt):
def __str__(self):
return super(_PromptOut, self).__str__() + ' <<< '
_promptIn = _PromptIn()
_promptOut = _PromptOut()
| import tables
import tables as tb
try:
import fipy
import fipy as fp
except:
pass
import numpy
import numpy as np
import scipy
import scipy as spy
import matplotlib.pylot as plt
def gitCommand(cmd, verbose=False):
from subprocess import Popen, PIPE
p = Popen(['git'] + cmd, shell=False, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
p.wait()
out = p.stdout.read()
if verbose:
print out
print p.stderr.read()
return out
def gitCurrentCommit():
return gitCommand(['log', '--oneline', '-1', '--abbrev=12', '--format="%h"']).strip().strip('"')
class _Prompt(object):
def __str__(self):
import datetime
sha = gitCommand(['log', '--oneline', '-1', '--abbrev=12', '--format="%h"']).strip().strip('"')
if len(sha) > 0:
sha = ' ' + sha
return '[' + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + sha + ']'
class _PromptIn(_Prompt):
def __str__(self):
return super(_PromptIn, self).__str__() + ' >>> '
class _PromptOut(_Prompt):
def __str__(self):
return super(_PromptOut, self).__str__() + ' <<< '
_promptIn = _PromptIn()
_promptOut = _PromptOut()
|
Fix NameError: global name 'messsage' is not defined | import json
class Database(dict):
"""Holds a dict that contains all the information about the users in a channel"""
def __init__(self, irc):
super(Database, self).__init__(json.load(open("userdb.json")))
self.irc = irc
def remove_entry(self, event, nick):
try:
del self[event.target][nick]
except KeyError:
for i in self[event.target].values():
if i['host'] == event.source.host:
del self[event.target][i['hostmask'].split("!")[0]]
break
def add_entry(self, channel, nick, hostmask, account):
temp = {
'hostmask': hostmask,
'host': hostmask.split("@")[1],
'account': account,
'seen': [{"time":__import__("time").time(), "messsage":""}]
}
if nick in self[channel]:
del temp['seen']
self[channel][nick].update(temp)
else:
self[channel][nick] = temp
def get_user_host(self, channel, nick):
try:
host = "*!*@" + self[channel][nick]['host']
except KeyError:
self.irc.send("WHO {0} nuhs%nhuac".format(channel))
host = "*!*@" + self[channel][nick]['host']
return host
def flush(self):
with open('userdb.json', 'w') as f:
json.dump(self, f, indent=2, separators=(',', ': '))
f.write("\n")
| import json
class Database(dict):
"""Holds a dict that contains all the information about the users in a channel"""
def __init__(self, irc):
super(Database, self).__init__(json.load(open("userdb.json")))
self.irc = irc
def remove_entry(self, event, nick):
try:
del self[event.target][nick]
except KeyError:
for i in self[event.target].values():
if i['host'] == event.source.host:
del self[event.target][i['hostmask'].split("!")[0]]
break
def add_entry(self, channel, nick, hostmask, account):
temp = {
'hostmask': hostmask,
'host': hostmask.split("@")[1],
'account': account,
'seen': [{"time":__import__("time").time(), messsage:""}]
}
if nick in self[channel]:
del temp['seen']
self[channel][nick].update(temp)
else:
self[channel][nick] = temp
def get_user_host(self, channel, nick):
try:
host = "*!*@" + self[channel][nick]['host']
except KeyError:
self.irc.send("WHO {0} nuhs%nhuac".format(channel))
host = "*!*@" + self[channel][nick]['host']
return host
def flush(self):
with open('userdb.json', 'w') as f:
json.dump(self, f, indent=2, separators=(',', ': '))
f.write("\n")
|
Fix url to 404 template | (function() {
'use strict';
moment.locale('nb');
var module = angular.module('billett', [
'ngRoute',
'billett.auth',
// common
'billett.common.directives',
'billett.common.filters',
'billett.common.CsrfInceptorService',
'billett.common.HeaderController',
'billett.common.PageController',
'billett.common.PageService',
'billett.common.ResponseDataService',
// admin
'billett.admin.event',
'billett.admin.eventgroup',
'billett.admin.index',
'billett.admin.order',
'billett.admin.paymentgroup',
'billett.admin.ticketgroup',
// guest
'billett.event',
'billett.eventgroup',
'billett.index',
'billett.infopages.HjelpController',
'billett.infopages.SalgsBetController',
'billett.order'
]);
module.config(function ($locationProvider, $routeProvider) {
$routeProvider.otherwise({templateUrl: 'assets/views/guest/infopages/404.html'});
// use HTML5 history API for nice urls
$locationProvider.html5Mode(true);
});
})();
| (function() {
'use strict';
moment.locale('nb');
var module = angular.module('billett', [
'ngRoute',
'billett.auth',
// common
'billett.common.directives',
'billett.common.filters',
'billett.common.CsrfInceptorService',
'billett.common.HeaderController',
'billett.common.PageController',
'billett.common.PageService',
'billett.common.ResponseDataService',
// admin
'billett.admin.event',
'billett.admin.eventgroup',
'billett.admin.index',
'billett.admin.order',
'billett.admin.paymentgroup',
'billett.admin.ticketgroup',
// guest
'billett.event',
'billett.eventgroup',
'billett.index',
'billett.infopages.HjelpController',
'billett.infopages.SalgsBetController',
'billett.order'
]);
module.config(function ($locationProvider, $routeProvider) {
$routeProvider.otherwise({templateUrl: 'infopages/404.html'});
// use HTML5 history API for nice urls
$locationProvider.html5Mode(true);
});
})();
|
Fix incorrect member visibility on event | <?php namespace Flarum\Events;
use Flarum\Api\Actions\SerializeAction;
class BuildApiAction
{
public $action;
/**
* @param SerializeAction $action
*/
public function __construct($action)
{
$this->action = $action;
}
public function serializer($serializer)
{
$this->action->serializer = $serializer;
}
public function addInclude($relation, $default = true)
{
$this->action->include[$relation] = $default;
}
public function removeInclude($relation)
{
unset($this->action->include[$relation]);
}
public function addLink($relation)
{
$this->action->link[] = $relation;
}
public function removeLink($relation)
{
if (($k = array_search($relation, $this->action->link)) !== false) {
unset($this->action->link[$k]);
}
}
public function limitMax($limitMax)
{
$this->action->limitMax = $limitMax;
}
public function limit($limit)
{
$this->action->limit = $limit;
}
public function addSortField($field)
{
$this->action->sortFields[] = $field;
}
public function removeSortField($field)
{
if (($k = array_search($field, $this->action->sortFields)) !== false) {
unset($this->action->sortFields[$k]);
}
}
public function sort($sort)
{
$this->action->sort = $sort;
}
}
| <?php namespace Flarum\Events;
use Flarum\Api\Actions\SerializeAction;
class BuildApiAction
{
protected $action;
/**
* @param SerializeAction $action
*/
public function __construct($action)
{
$this->action = $action;
}
public function serializer($serializer)
{
$this->action->serializer = $serializer;
}
public function addInclude($relation, $default = true)
{
$this->action->include[$relation] = $default;
}
public function removeInclude($relation)
{
unset($this->action->include[$relation]);
}
public function addLink($relation)
{
$this->action->link[] = $relation;
}
public function removeLink($relation)
{
if (($k = array_search($relation, $this->action->link)) !== false) {
unset($this->action->link[$k]);
}
}
public function limitMax($limitMax)
{
$this->action->limitMax = $limitMax;
}
public function limit($limit)
{
$this->action->limit = $limit;
}
public function addSortField($field)
{
$this->action->sortFields[] = $field;
}
public function removeSortField($field)
{
if (($k = array_search($field, $this->action->sortFields)) !== false) {
unset($this->action->sortFields[$k]);
}
}
public function sort($sort)
{
$this->action->sort = $sort;
}
}
|
BAP-738: Rename buttons "Add new" to "Add {entity_name}" | <?php
namespace Acme\Bundle\DemoFlexibleEntityBundle\Tests\Functional\Controller;
/**
* Test related class
*
* @author Romain Monceau <[email protected]>
* @copyright 2012 Akeneo SAS (http://www.akeneo.com)
* @license http://opensource.org/licenses/MIT MIT
*
*/
class FlexibleControllerTest extends KernelAwareControllerTest
{
/**
* Define flexible controller name for url generation
* @staticvar string
*/
protected static $controller = 'flexible';
/**
* Test related method
*/
public function testIndexAction()
{
foreach (self::$locales as $locale) {
$this->client->request(
'GET',
self::prepareUrl($locale, 'index')
);
$this->assertEquals(200, $this->client->getResponse()->getStatusCode());
}
}
/**
* Test related method
*/
// public function testEntityConfigAction()
// {
// foreach (self::$locales as $locale) {
// $this->client->request(
// 'GET',
// self::prepareUrl($locale, 'config')
// );
// $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
// }
// }
}
| <?php
namespace Acme\Bundle\DemoFlexibleEntityBundle\Tests\Functional\Controller;
/**
* Test related class
*
* @author Romain Monceau <[email protected]>
* @copyright 2012 Akeneo SAS (http://www.akeneo.com)
* @license http://opensource.org/licenses/MIT MIT
*
*/
class FlexibleControllerTest extends KernelAwareControllerTest
{
/**
* Define flexible controller name for url generation
* @staticvar string
*/
protected static $controller = 'flexible';
/**
* Test related method
*/
public function testIndexAction()
{
foreach (self::$locales as $locale) {
$this->client->request(
'GET',
self::prepareUrl($locale, 'index')
);
$this->assertEquals(200, $this->client->getResponse()->getStatusCode());
}
}
/**
* Test related method
*/
public function testEntityConfigAction()
{
foreach (self::$locales as $locale) {
$this->client->request(
'GET',
self::prepareUrl($locale, 'config')
);
$this->assertEquals(200, $this->client->getResponse()->getStatusCode());
}
}
}
|
Revert getLocked (Lombokified name was isLocked) | package net.glowstone.scoreboard;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import net.glowstone.net.message.play.scoreboard.ScoreboardScoreMessage;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.scoreboard.Objective;
import org.bukkit.scoreboard.Score;
import org.bukkit.scoreboard.Scoreboard;
/**
* Implementation/data holder for Scores.
*/
@RequiredArgsConstructor
public final class GlowScore implements Score {
@Getter
private final GlowObjective objective;
@Getter
private final String entry;
private int score;
@Setter
private boolean locked;
@Override
public Scoreboard getScoreboard() {
return objective.getScoreboard();
}
@Override
@Deprecated
public OfflinePlayer getPlayer() {
return Bukkit.getOfflinePlayer(entry);
}
@Override
public int getScore() throws IllegalStateException {
objective.checkValid();
return score;
}
/**
* Sets this score's value.
* @param score the new value
* @throws IllegalStateException if the objective is not registered on a scoreboard
*/
@Override
public void setScore(int score) throws IllegalStateException {
objective.checkValid();
this.score = score;
objective.getScoreboard()
.broadcast(new ScoreboardScoreMessage(entry, objective.getName(), score));
}
@Override
public boolean isScoreSet() throws IllegalStateException {
objective.checkValid();
return objective.getScoreboard().getScores(entry).contains(this);
}
public boolean getLocked() {
return locked;
}
}
| package net.glowstone.scoreboard;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import net.glowstone.net.message.play.scoreboard.ScoreboardScoreMessage;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.scoreboard.Objective;
import org.bukkit.scoreboard.Score;
import org.bukkit.scoreboard.Scoreboard;
/**
* Implementation/data holder for Scores.
*/
@RequiredArgsConstructor
public final class GlowScore implements Score {
@Getter
private final GlowObjective objective;
@Getter
private final String entry;
private int score;
@Getter
@Setter
private boolean locked;
@Override
public Scoreboard getScoreboard() {
return objective.getScoreboard();
}
@Override
@Deprecated
public OfflinePlayer getPlayer() {
return Bukkit.getOfflinePlayer(entry);
}
@Override
public int getScore() throws IllegalStateException {
objective.checkValid();
return score;
}
/**
* Sets this score's value.
* @param score the new value
* @throws IllegalStateException if the objective is not registered on a scoreboard
*/
@Override
public void setScore(int score) throws IllegalStateException {
objective.checkValid();
this.score = score;
objective.getScoreboard()
.broadcast(new ScoreboardScoreMessage(entry, objective.getName(), score));
}
@Override
public boolean isScoreSet() throws IllegalStateException {
objective.checkValid();
return objective.getScoreboard().getScores(entry).contains(this);
}
}
|
Remove Debugger Statement From Route
Remove a debugger statement in the application route. | import config from '../config/environment';
import {
inject as service
} from '@ember/service';
import AuthenticateRoute from 'wholetale/routes/authenticate';
export default AuthenticateRoute.extend({
internalState: service(),
model: function (params) {
// console.log("Called Authenticate, proceeding in Application");
let router = this;
return router._super(...arguments)
.then(_ => {
let user = router.get('userAuth').getCurrentUser();
return user;
});
},
setupController: function (controller, model) {
this._super(controller, model);
if (model) {
controller.set('loggedIn', true);
controller.set('user', model);
controller.set('gravatarUrl', config.apiUrl + "/user/" + model.get('_id') + "/gravatar?size=64");
this.store.findAll('job', {
reload: true,
adapterOptions: {
queryParams: {
limit: "0"
}
}
}).then(jobs => {
controller.set('jobs', jobs);
controller.set('isLoadingJobs', false);
});
}
},
actions: {
toRoute() {
this.transitionTo.call(this, ...arguments);
return true;
},
showModal(modalDialogName, modalContext) {
const applicationController = this.controller;
Ember.setProperties(applicationController, {
modalDialogName,
modalContext,
isModalVisible: true
});
},
closeModal() {
const applicationController = this.controller;
Ember.set(applicationController, 'isModalVisible', false);
}
}
});
| import config from '../config/environment';
import {
inject as service
} from '@ember/service';
import AuthenticateRoute from 'wholetale/routes/authenticate';
export default AuthenticateRoute.extend({
internalState: service(),
model: function (params) {
// console.log("Called Authenticate, proceeding in Application");
let router = this;
return router._super(...arguments)
.then(_ => {
let user = router.get('userAuth').getCurrentUser();
return user;
});
},
setupController: function (controller, model) {
this._super(controller, model);
if (model) {
controller.set('loggedIn', true);
controller.set('user', model);
controller.set('gravatarUrl', config.apiUrl + "/user/" + model.get('_id') + "/gravatar?size=64");
this.store.findAll('job', {
reload: true,
adapterOptions: {
queryParams: {
limit: "0"
}
}
}).then(jobs => {
controller.set('jobs', jobs);
controller.set('isLoadingJobs', false);
});
}
},
actions: {
toRoute() {
this.transitionTo.call(this, ...arguments);
return true;
},
showModal(modalDialogName, modalContext) {
const applicationController = this.controller;
Ember.setProperties(applicationController, {
modalDialogName,
modalContext,
isModalVisible: true
});
},
closeModal() {
debugger;
const applicationController = this.controller;
Ember.set(applicationController, 'isModalVisible', false);
}
}
});
|
Fix incorrect docstring for NFA class | #!/usr/bin/env python3
import automata.automaton as automaton
class NFA(automaton.Automaton):
"""a nondeterministic finite automaton"""
def validate_automaton(self):
"""returns True if this NFA is internally consistent;
raises the appropriate exception if this NFA is invalid"""
for state in self.states:
if state not in self.transitions:
raise automaton.MissingStateError(
'state {} is missing from transition function'.format(
state))
for start_state, paths in self.transitions.items():
invalid_states = set().union(*paths.values()).difference(
self.states)
if invalid_states:
raise automaton.InvalidStateError(
'states are not valid ({})'.format(
', '.join(invalid_states)))
if self.initial_state not in self.states:
raise automaton.InvalidStateError(
'{} is not a valid state'.format(self.initial_state))
for state in self.final_states:
if state not in self.states:
raise automaton.InvalidStateError(
'{} is not a valid state'.format(state))
return True
# TODO
def validate_input(self, input_str):
"""returns True if the given string is accepted by this NFA;
raises the appropriate exception if the string is not accepted"""
return True
| #!/usr/bin/env python3
import automata.automaton as automaton
class NFA(automaton.Automaton):
"""a deterministic finite automaton"""
def validate_automaton(self):
"""returns True if this NFA is internally consistent;
raises the appropriate exception if this NFA is invalid"""
for state in self.states:
if state not in self.transitions:
raise automaton.MissingStateError(
'state {} is missing from transition function'.format(
state))
for start_state, paths in self.transitions.items():
invalid_states = set().union(*paths.values()).difference(
self.states)
if invalid_states:
raise automaton.InvalidStateError(
'states are not valid ({})'.format(
', '.join(invalid_states)))
if self.initial_state not in self.states:
raise automaton.InvalidStateError(
'{} is not a valid state'.format(self.initial_state))
for state in self.final_states:
if state not in self.states:
raise automaton.InvalidStateError(
'{} is not a valid state'.format(state))
return True
# TODO
def validate_input(self, input_str):
"""returns True if the given string is accepted by this NFA;
raises the appropriate exception if the string is not accepted"""
return True
|
Copy CSS from source to dist using Webpack | const webpack = require("webpack");
const path = require("path");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
entry: "./src/com/mendix/widget/StarRating/StarRating.ts",
output: {
path: path.resolve(__dirname, "dist/tmp"),
filename: "src/com/mendix/widget/StarRating/StarRating.js",
libraryTarget: "umd",
umdNamedDefine: true,
library: "com.mendix.widget.StarRating.StarRating"
},
resolve: {
extensions: [ "", ".ts", ".js", ".json" ],
alias: {
"tests": path.resolve(__dirname, "./tests")
}
},
errorDetails: true,
module: {
loaders: [
{ test: /\.ts$/, loader: "ts-loader" },
{ test: /\.json$/, loader: "json" },
{ test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader") }
]
},
devtool: "source-map",
externals: [ "mxui/widget/_WidgetBase", "dojo/_base/declare" ],
plugins: [
new CopyWebpackPlugin([
{ from: "src/**/*.js" },
{ from: "src/**/*.xml" },
{ from: "src/**/*.css" }
], {
copyUnmodified: true
}),
new ExtractTextPlugin("./src/com/mendix/widget/StarRating/ui/StarRating.css")
],
watch: true
};
| const webpack = require("webpack");
const path = require("path");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
entry: "./src/com/mendix/widget/StarRating/StarRating.ts",
output: {
path: path.resolve(__dirname, "dist/tmp"),
filename: "src/com/mendix/widget/StarRating/StarRating.js",
libraryTarget: "umd",
umdNamedDefine: true,
library: "com.mendix.widget.StarRating.StarRating"
},
resolve: {
extensions: [ "", ".ts", ".js", ".json" ],
alias: {
"tests": path.resolve(__dirname, "./tests")
}
},
errorDetails: true,
module: {
loaders: [
{ test: /\.ts$/, loader: "ts-loader" },
{ test: /\.json$/, loader: "json" },
{ test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader") }
]
},
devtool: "source-map",
externals: [ "mxui/widget/_WidgetBase", "dojo/_base/declare" ],
plugins: [
new CopyWebpackPlugin([
{ from: "src/**/*.js" },
{ from: "src/**/*.xml" }
], {
copyUnmodified: true
}),
new ExtractTextPlugin("./src/com/mendix/widget/StarRating/ui/StarRating.css")
],
watch: true
};
|
Remove the now-defunct middleware from the test settings | # Settings to be used when running unit tests
# python manage.py test --settings=lazysignup.test_settings lazysignup
DATABASE_ENGINE = 'sqlite3' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = '' # Or path to database file if using sqlite3.
DATABASE_USER = '' # Not used with sqlite3.
DATABASE_PASSWORD = '' # Not used with sqlite3.
DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.
INSTALLED_APPS = (
# Put any other apps that your app depends on here
'django.contrib.auth',
'django.contrib.sessions',
'django.contrib.contenttypes',
'lazysignup',
)
SITE_ID = 1
AUTHENTICATION_BACKENDS = (
"django.contrib.auth.backends.ModelBackend",
"lazysignup.backends.LazySignupBackend",
)
MIDDLEWARE_CLASSES = [
"django.middleware.common.CommonMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
]
LAZYSIGNUP_USER_AGENT_BLACKLIST = [
"^search",
]
# This merely needs to be present - as long as your test case specifies a
# urls attribute, it does not need to be populated.
ROOT_URLCONF = ''
| # Settings to be used when running unit tests
# python manage.py test --settings=lazysignup.test_settings lazysignup
DATABASE_ENGINE = 'sqlite3' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = '' # Or path to database file if using sqlite3.
DATABASE_USER = '' # Not used with sqlite3.
DATABASE_PASSWORD = '' # Not used with sqlite3.
DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.
INSTALLED_APPS = (
# Put any other apps that your app depends on here
'django.contrib.auth',
'django.contrib.sessions',
'django.contrib.contenttypes',
'lazysignup',
)
SITE_ID = 1
AUTHENTICATION_BACKENDS = (
"django.contrib.auth.backends.ModelBackend",
"lazysignup.backends.LazySignupBackend",
)
MIDDLEWARE_CLASSES = [
"django.middleware.common.CommonMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"lazysignup.middleware.LazySignupMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
]
LAZYSIGNUP_USER_AGENT_BLACKLIST = [
"^search",
]
# This merely needs to be present - as long as your test case specifies a
# urls attribute, it does not need to be populated.
ROOT_URLCONF = '' |
Add pretty url pagination support | <?php
namespace Zelenin\yii\modules\I18n;
use yii\base\BootstrapInterface;
use Yii;
use yii\data\Pagination;
use Zelenin\yii\modules\I18n\console\controllers\I18nController;
class Bootstrap implements BootstrapInterface
{
/**
* @inheritdoc
*/
public function bootstrap($app)
{
if ($app instanceof \yii\web\Application && $i18nModule = Yii::$app->getModule('i18n')) {
$moduleId = $i18nModule->id;
$app->getUrlManager()->addRules([
'translations/<id:\d+>' => $moduleId . '/default/update',
'translations/page/<page:\d+>' => $moduleId . '/default/index',
'translations' => $moduleId . '/default/index',
], false);
Yii::$container->set(Pagination::className(), [
'pageSizeLimit' => [1, 100],
'defaultPageSize' => $i18nModule->pageSize
]);
}
if ($app instanceof \yii\console\Application) {
if (!isset($app->controllerMap['i18n'])) {
$app->controllerMap['i18n'] = I18nController::className();
}
}
}
}
| <?php
namespace Zelenin\yii\modules\I18n;
use yii\base\BootstrapInterface;
use Yii;
use yii\data\Pagination;
use Zelenin\yii\modules\I18n\console\controllers\I18nController;
class Bootstrap implements BootstrapInterface
{
/**
* @inheritdoc
*/
public function bootstrap($app)
{
if ($app instanceof \yii\web\Application && $i18nModule = Yii::$app->getModule('i18n')) {
$moduleId = $i18nModule->id;
$app->getUrlManager()->addRules([
'translations/<id:\d+>' => $moduleId . '/default/update',
'translations' => $moduleId . '/default/index',
], false);
Yii::$container->set(Pagination::className(), [
'pageSizeLimit' => [1, 100],
'defaultPageSize' => $i18nModule->pageSize
]);
}
if ($app instanceof \yii\console\Application) {
if (!isset($app->controllerMap['i18n'])) {
$app->controllerMap['i18n'] = I18nController::className();
}
}
}
}
|
Fix loader on empty config | var loaderUtils = require('loader-utils');
var postcss = require('postcss');
module.exports = function (source, map) {
if ( this.cacheable ) this.cacheable();
var file = loaderUtils.getRemainingRequest(this);
var params = loaderUtils.parseQuery(this.query);
var opts = {
from: file, to: file,
map: {
inline: false,
annotation: false
}
};
if ( map && map.mappings ) opts.map.prev = map;
if ( params.safe ) opts.safe = true;
var plugins = this.options.postcss;
if ( typeof plugins === 'undefined' ) {
plugins = [];
} else if ( params.pack ) {
plugins = plugins[params.pack];
} else if ( !Array.isArray(plugins) ) {
plugins = plugins.defaults;
}
var loader = this;
var callback = this.async();
postcss(plugins)
.process(source, opts).then(function (result) {
result.warnings().forEach(function (msg) {
loader.emitWarning(msg.toString());
});
callback(null, result.css, result.map);
})
.catch(function (error) {
if ( error.name === 'CssSyntaxError' ) {
loader.emitError(error.message + error.showSourceCode());
callback();
} else {
callback(error);
}
});
};
| var loaderUtils = require('loader-utils');
var postcss = require('postcss');
module.exports = function (source, map) {
if ( this.cacheable ) this.cacheable();
var file = loaderUtils.getRemainingRequest(this);
var params = loaderUtils.parseQuery(this.query);
var opts = {
from: file, to: file,
map: {
inline: false,
annotation: false
}
};
if ( map && map.mappings ) opts.map.prev = map;
if ( params.safe ) opts.safe = true;
var plugins = this.options.postcss;
if ( params.pack ) {
plugins = plugins[params.pack];
} else if ( !Array.isArray(plugins) ) {
plugins = plugins.defaults;
}
var loader = this;
var callback = this.async();
postcss(plugins)
.process(source, opts).then(function (result) {
result.warnings().forEach(function (msg) {
loader.emitWarning(msg.toString());
});
callback(null, result.css, result.map);
})
.catch(function (error) {
if ( error.name === 'CssSyntaxError' ) {
loader.emitError(error.message + error.showSourceCode());
callback();
} else {
callback(error);
}
});
};
|
Add Chardet as installation dependency | #!/usr/bin/env python
from distutils.core import setup
setup(
name='freki',
version='0.3.0-develop',
description='PDF-Extraction helper for RiPLEs pipeline.',
author='Michael Goodman, Ryan Georgi',
author_email='[email protected], [email protected]',
url='https://github.com/xigt/freki',
license='MIT',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: Information Technology',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Scientific/Engineering :: Information Analysis',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Text Processing :: Linguistic',
'Topic :: Utilities'
],
keywords='nlp pdf ie text',
packages=['freki', 'freki.readers', 'freki.analyzers'],
install_requires=[
'numpy',
'matplotlib',
'chardet'
],
entry_points={
'console_scripts': [
'freki=freki.main:main'
]
},
)
| #!/usr/bin/env python
from distutils.core import setup
setup(
name='freki',
version='0.3.0-develop',
description='PDF-Extraction helper for RiPLEs pipeline.',
author='Michael Goodman, Ryan Georgi',
author_email='[email protected], [email protected]',
url='https://github.com/xigt/freki',
license='MIT',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: Information Technology',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Scientific/Engineering :: Information Analysis',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Text Processing :: Linguistic',
'Topic :: Utilities'
],
keywords='nlp pdf ie text',
packages=['freki', 'freki.readers', 'freki.analyzers'],
install_requires=[
'numpy',
'matplotlib'
],
entry_points={
'console_scripts': [
'freki=freki.main:main'
]
},
)
|
Fix service provider kernel detection | <?php
namespace SebastiaanLuca\Router;
use Illuminate\Contracts\Http\Kernel as AppKernel;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider;
use Illuminate\Routing\Router;
use SebastiaanLuca\Router\Routers\BootstrapRouter;
class RouterServiceProvider extends RouteServiceProvider
{
/**
* Map user-defined routers.
*/
protected function registerUserRouters()
{
// We can safely assume the Kernel contract is the application's
// HTTP kernel as it is bound in bootstrap/app.php to the actual
// implementation. Still need to check if it's the package's
// custom kernel though as that is an optional setup choice.
$kernel = app(AppKernel::class);
if (! $kernel instanceof Kernel) {
return;
}
$routers = $kernel->getRouters();
// Just instantiate each router as they handle the mapping itself
foreach ($routers as $router) {
app($router);
}
}
/**
* Register the service provider.
*/
public function register()
{
// Define our router extension
$this->app->singleton(ExtendedRouter::class, function ($app) {
return new ExtendedRouter($app['events'], $app);
});
// Swap the default router with our extended router
$this->app->alias(ExtendedRouter::class, 'router');
}
/**
* Define your route model bindings, pattern filters, etc using the Bootstrap router.
*
* @param \Illuminate\Routing\Router $router
*/
public function boot(Router $router)
{
// Create a router that defines route patterns and whatnot
$this->app->make(BootstrapRouter::class);
// Map user-defined routers
$this->registerUserRouters();
}
}
| <?php
namespace SebastiaanLuca\Router;
use Illuminate\Contracts\Http\Kernel as AppKernel;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider;
use Illuminate\Routing\Router;
use SebastiaanLuca\Router\Routers\BootstrapRouter;
class RouterServiceProvider extends RouteServiceProvider
{
/**
* Map user-defined routers.
*/
protected function registerUserRouters()
{
// We can safely assume the Kernel contract is the application's
// HTTP kernel as it is bound in bootstrap/app.php to the actual
// implementation.
$routers = app(AppKernel::class)->getRouters();
// Just instantiate each router, they handle the mapping itself
foreach ($routers as $router) {
app($router);
}
}
/**
* Register the service provider.
*/
public function register()
{
// Define our router extension
$this->app->singleton(ExtendedRouter::class, function ($app) {
return new ExtendedRouter($app['events'], $app);
});
// Swap the default router with our extended router
$this->app->alias(ExtendedRouter::class, 'router');
}
/**
* Define your route model bindings, pattern filters, etc using the Bootstrap router.
*
* @param \Illuminate\Routing\Router $router
*/
public function boot(Router $router)
{
// Create a router that defines route patterns and whatnot
$this->app->make(BootstrapRouter::class);
// Map user-defined routers
$this->registerUserRouters();
}
}
|
Correct test criteria for time format for scheduled skill.
Now matches current behaviour, previous behaviour is not a good idea since it depended on Locale. | from datetime import datetime, timedelta
import unittest
from mycroft.skills.scheduled_skills import ScheduledSkill
from mycroft.util.log import getLogger
__author__ = 'eward'
logger = getLogger(__name__)
class ScheduledSkillTest(unittest.TestCase):
skill = ScheduledSkill(name='ScheduledSkillTest')
def test_formatted_time_today_hours(self):
date = datetime.now() + timedelta(hours=2)
self.assertEquals(self.skill.
get_formatted_time(float(date.strftime('%s'))),
"1 hours and 59 minutes from now")
def test_formatted_time_today_min(self):
date = datetime.now() + timedelta(minutes=2)
self.assertEquals(self.skill.
get_formatted_time(float(date.strftime('%s'))),
"1 minutes and 59 seconds from now")
def test_formatted_time_days(self):
date = datetime.now() + timedelta(days=2)
self.assertEquals(self.skill.
get_formatted_time(float(date.strftime('%s'))),
date.strftime("%d %B, %Y at %H:%M"))
| from datetime import datetime, timedelta
import unittest
from mycroft.skills.scheduled_skills import ScheduledSkill
from mycroft.util.log import getLogger
__author__ = 'eward'
logger = getLogger(__name__)
class ScheduledSkillTest(unittest.TestCase):
skill = ScheduledSkill(name='ScheduledSkillTest')
def test_formatted_time_today_hours(self):
date = datetime.now() + timedelta(hours=2)
self.assertEquals(self.skill.
get_formatted_time(float(date.strftime('%s'))),
"1 hours and 59 minutes from now")
def test_formatted_time_today_min(self):
date = datetime.now() + timedelta(minutes=2)
self.assertEquals(self.skill.
get_formatted_time(float(date.strftime('%s'))),
"1 minutes and 59 seconds from now")
def test_formatted_time_days(self):
date = datetime.now() + timedelta(days=2)
self.assertEquals(self.skill.
get_formatted_time(float(date.strftime('%s'))),
date.strftime("%A, %B %d, %Y at %H:%M"))
|
Update to include the TheGame:MapBundle controller | <?php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = [
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Symfony\Bundle\MonologBundle\MonologBundle(),
new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
new AppBundle\AppBundle(),
new TheGame\MapsBundle\TheGameMapsBundle(),
];
if (in_array($this->getEnvironment(), ['dev', 'test'], true)) {
$bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle();
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
$bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
$bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
}
return $bundles;
}
public function getRootDir()
{
return __DIR__;
}
public function getCacheDir()
{
return dirname(__DIR__).'/var/cache/'.$this->getEnvironment();
}
public function getLogDir()
{
return dirname(__DIR__).'/var/logs';
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load($this->getRootDir().'/config/config_'.$this->getEnvironment().'.yml');
}
}
| <?php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = [
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Symfony\Bundle\MonologBundle\MonologBundle(),
new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
new AppBundle\AppBundle(),
];
if (in_array($this->getEnvironment(), ['dev', 'test'], true)) {
$bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle();
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
$bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
$bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
}
return $bundles;
}
public function getRootDir()
{
return __DIR__;
}
public function getCacheDir()
{
return dirname(__DIR__).'/var/cache/'.$this->getEnvironment();
}
public function getLogDir()
{
return dirname(__DIR__).'/var/logs';
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load($this->getRootDir().'/config/config_'.$this->getEnvironment().'.yml');
}
}
|
Add lang to html tag in example site | import React from 'react'
import Document, { Html, Head, Body, App, Footer } from 'react-document'
/**
* This component is a template for the HTML file. You can add webfonts, meta tags,
* or analytics to this file.
*
* To begin the development, run `npm start`.
* To create a static bundle, use `npm run build`.
* To create a server bundle, use `npm run build-server`.
*
* IMPORTANT: This file is compiled and used differently from other modules.
*
* - In development and in static builds, this code is run at build time. It
* only receives asset metadata as a prop. Nothing else.
*
* - In server builds, this code evaluates for every request. It may receive
* additional route specific props, e.g. a serialized store and meta tags.
*/
export default class extends Document {
render() {
// TODO: Remove when headProps is gone.
let helmet = this.props.helmet ||
this.props.headProps && this.props.headProps.helmet
return (
<Html lang="en">
<Head>
{helmet && [
helmet.title.toComponent(),
helmet.meta.toComponent(),
helmet.link.toComponent(),
]}
<link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:200,300,400,400i" rel="stylesheet" />
</Head>
<Body>
<App />
<Footer />
</Body>
</Html>
)
}
}
| import React from 'react'
import Document, { Html, Head, Body, App, Footer } from 'react-document'
/**
* This component is a template for the HTML file. You can add webfonts, meta tags,
* or analytics to this file.
*
* To begin the development, run `npm start`.
* To create a static bundle, use `npm run build`.
* To create a server bundle, use `npm run build-server`.
*
* IMPORTANT: This file is compiled and used differently from other modules.
*
* - In development and in static builds, this code is run at build time. It
* only receives asset metadata as a prop. Nothing else.
*
* - In server builds, this code evaluates for every request. It may receive
* additional route specific props, e.g. a serialized store and meta tags.
*/
export default class extends Document {
render() {
// TODO: Remove when headProps is gone.
let helmet = this.props.helmet ||
this.props.headProps && this.props.headProps.helmet
return (
<Html>
<Head>
{helmet && [
helmet.title.toComponent(),
helmet.meta.toComponent(),
helmet.link.toComponent(),
]}
<link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:200,300,400,400i" rel="stylesheet" />
</Head>
<Body>
<App />
<Footer />
</Body>
</Html>
)
}
}
|
BAP-4203: Convert doctrine subscribers to listeners, make all doctrine listeners lazy
- fixed unit test | <?php
namespace Oro\Bundle\PlatformBundle\Tests\Unit\DependencyInjection;
use Oro\Bundle\PlatformBundle\DependencyInjection\Compiler\LazyServicesCompilerPass;
class LazyServicesCompilerPassTest extends \PHPUnit_Framework_TestCase
{
public function testProcessLazyServicesTag()
{
$expectedTags = array(
'doctrine.event_listener'
);
$compiler = new LazyServicesCompilerPass();
$this->assertAttributeEquals($expectedTags, 'lazyServicesTags', $compiler);
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerBuilder');
$containerIteration = 0;
foreach ($expectedTags as $tagName) {
$testTags = array(
'first.' . $tagName => array(),
'second.' . $tagName => array(),
);
$container->expects($this->at(++$containerIteration))->method('findTaggedServiceIds')->with($tagName)
->will($this->returnValue($testTags));
foreach (array_keys($testTags) as $serviceId) {
$definition = $this->getMock('Symfony\Component\DependencyInjection\Definition');
$definition->expects($this->once())->method('setLazy')->with(true);
$container->expects($this->at(++$containerIteration))->method('hasDefinition')->with($serviceId)
->will($this->returnValue(true));
$container->expects($this->at(++$containerIteration))->method('getDefinition')->with($serviceId)
->will($this->returnValue($definition));
}
}
$compiler->process($container);
}
}
| <?php
namespace Oro\Bundle\PlatformBundle\Tests\Unit\DependencyInjection;
use Oro\Bundle\PlatformBundle\DependencyInjection\Compiler\LazyServicesCompilerPass;
class LazyServicesCompilerPassTest extends \PHPUnit_Framework_TestCase
{
public function testProcessLazyServicesTag()
{
$expectedTags = array();
$compiler = new LazyServicesCompilerPass();
$this->assertAttributeEquals($expectedTags, 'lazyServicesTags', $compiler);
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerBuilder');
$containerIteration = 0;
foreach ($expectedTags as $tagName) {
$testTags = array(
'first.' . $tagName => array(),
'second.' . $tagName => array(),
);
$container->expects($this->at(++$containerIteration))->method('findTaggedServiceIds')->with($tagName)
->will($this->returnValue($testTags));
foreach (array_keys($testTags) as $serviceId) {
$definition = $this->getMock('Symfony\Component\DependencyInjection\Definition');
$definition->expects($this->once())->method('setLazy')->with(true);
$container->expects($this->at(++$containerIteration))->method('hasDefinition')->with($serviceId)
->will($this->returnValue(true));
$container->expects($this->at(++$containerIteration))->method('getDefinition')->with($serviceId)
->will($this->returnValue($definition));
}
}
$compiler->process($container);
}
}
|
Refactor create_card method to take a list of card dictionaries. Rename method accordingly. | from pymongo import MongoClient
class Cards:
def __init__(self, dbname='cards'):
"""Instantiate this class.
Set up a connection to the given Mongo database.
Get to the collection we'll store cards in.
Args:
dbname (str): Database name.
"""
self.client = MongoClient()
self.db = self.client[dbname]
self.cards_coll = self.db['cards']
@property
def sets(self):
"""Return a list of all the card sets in the database.
Args:
None
Returns:
list: List of all card sets in the database.
"""
return self.cards_coll.distinct('set')
def retrieve_set(self, setname):
"""Return a list of all the cards in the given set.
Args:
setname (str): Name of set.
Returns:
list: List of all cards in the the given set.
"""
return list(self.cards_coll.find({'set': setname}))
def create_cards(self, cards):
"""Insert a new card with the given properties into the database.
Args:
cards: List of dictionaries with set, color, text, and creator keys.
Returns:
None
"""
keys = ['set', 'color', 'text', 'creator']
filtered = [ { k: card[k] for k in keys if k in card} for card in cards]
self.cards_coll.insert_many(filtered)
| from pymongo import MongoClient
class Cards:
def __init__(self, dbname='cards'):
"""Instantiate this class.
Set up a connection to the given Mongo database.
Get to the collection we'll store cards in.
Args:
dbname (str): Database name.
"""
self.client = MongoClient()
self.db = self.client[dbname]
self.cards_coll = self.db['cards']
@property
def sets(self):
"""Return a list of all the card sets in the database.
Args:
None
Returns:
list: List of all card sets in the database.
"""
return self.cards_coll.distinct('set')
def retrieve_set(self, setname):
"""Return a list of all the cards in the given set.
Args:
setname (str): Name of set.
Returns:
list: List of all cards in the the given set.
"""
return list(self.cards_coll.find({'set': setname}))
def create_card(self, setname, color, text, creator):
"""Insert a new card with the given properties into the database.
Args:
setname (str): Name of set the card will belong to.
color (str): Color the card will have.
text (str): Text that will appear on the card.
creator (str): Creator to attribute the card to.
Returns:
None
"""
card = {
'set': setname,
'color': color,
'text': text,
'creator': creator,
}
self.cards_coll.insert_one(card)
|
Fix CS issue in build | <?php
declare(strict_types = 1);
namespace App\Service\Speaker;
use League\Flysystem\FilesystemInterface;
use Psr\Http\Message\UploadedFileInterface;
use Ramsey\Uuid\Uuid;
final class FlysystemMoveSpeakerHeadshot implements MoveSpeakerHeadshotInterface
{
/**
* @var FilesystemInterface
*/
private $filesystem;
public function __construct(FilesystemInterface $filesystem)
{
$this->filesystem = $filesystem;
}
/**
* {@inheritDoc}
* @throws \League\Flysystem\FileExistsException
* @throws \InvalidArgumentException
* @throws \RuntimeException
*/
public function __invoke(UploadedFileInterface $uploadedFile): string
{
switch ($uploadedFile->getClientMediaType()) {
case 'image/png':
$extension = 'png';
break;
case 'image/gif':
$extension = 'gif';
break;
default:
$extension = 'jpg';
}
$filename = (string)Uuid::uuid4() . '.' . $extension;
$this->filesystem->write(
$filename,
$uploadedFile->getStream()->getContents(),
[
'ACL' => 'public-read',
]
);
return $filename;
}
}
| <?php
declare(strict_types = 1);
namespace App\Service\Speaker;
use League\Flysystem\FilesystemInterface;
use Psr\Http\Message\UploadedFileInterface;
use Ramsey\Uuid\Uuid;
final class FlysystemMoveSpeakerHeadshot implements MoveSpeakerHeadshotInterface
{
/**
* @var FilesystemInterface
*/
private $filesystem;
public function __construct(FilesystemInterface $filesystem)
{
$this->filesystem = $filesystem;
}
/**
* {@inheritDoc}
* @throws \League\Flysystem\FileExistsException
* @throws \InvalidArgumentException
* @throws \RuntimeException
*/
public function __invoke(UploadedFileInterface $uploadedFile): string
{
switch($uploadedFile->getClientMediaType()) {
case 'image/png':
$extension = 'png';
break;
case 'image/gif':
$extension = 'gif';
break;
default:
$extension = 'jpg';
}
$filename = (string)Uuid::uuid4() . '.' . $extension;
$this->filesystem->write(
$filename,
$uploadedFile->getStream()->getContents(),
[
'ACL' => 'public-read',
]
);
return $filename;
}
}
|
Remove upper limit for tornado's version
My use case seems to work with tornado 4.0.2. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
from tornado_redis_sentinel import __version__
tests_require = [
'mock',
'nose',
'coverage',
'yanc',
'preggy',
'tox',
'ipdb',
'coveralls',
]
setup(
name='tornado-redis-sentinel',
version=__version__,
description='Tornado redis library based in toredis that supports sentinel connections.',
long_description='''
Tornado redis library based in toredis that supports sentinel connections.
''',
keywords='tornado redis sentinel',
author='Globo.com',
author_email='[email protected]',
url='',
license='MIT',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: MacOS',
'Operating System :: POSIX',
'Operating System :: Unix',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
],
packages=find_packages(),
include_package_data=True,
install_requires=[
'tornado>3.2',
'toredis',
'six'
],
extras_require={
'tests': tests_require,
}
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
from tornado_redis_sentinel import __version__
tests_require = [
'mock',
'nose',
'coverage',
'yanc',
'preggy',
'tox',
'ipdb',
'coveralls',
]
setup(
name='tornado-redis-sentinel',
version=__version__,
description='Tornado redis library based in toredis that supports sentinel connections.',
long_description='''
Tornado redis library based in toredis that supports sentinel connections.
''',
keywords='tornado redis sentinel',
author='Globo.com',
author_email='[email protected]',
url='',
license='MIT',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: MacOS',
'Operating System :: POSIX',
'Operating System :: Unix',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
],
packages=find_packages(),
include_package_data=True,
install_requires=[
'tornado>3.2,<4.0',
'toredis',
'six'
],
extras_require={
'tests': tests_require,
}
)
|
Fix template for docker command line | import os
import subprocess
def env(image):
"""Return environment of image. """
out = docker('inspect', '-f', '{{.Config.Env}}', image)
return dict(map(lambda x: x.split('='), out.strip()[1:-1].split()))
def path(p):
"""Build the corresponding path `p` inside the container. """
return os.path.normpath(os.path.join(
os.environ.get('HOST_PREFIX', '/host'), './{}'.format(p)))
def docker(*args):
"""Execute a docker command inside the container. """
docker_binary = DOCKER
docker_socket = DOCKER_SOCKET
cmd = ('{docker_binary} -H {docker_socket}'
.format(**locals()).split())
cmd.extend(args)
return subprocess.check_output(cmd).strip()
def fig(*args):
docker_path = os.path.dirname(
path(os.environ.get('DOCKER_BINARY', '/usr/bin/docker')))
docker_socket = path(os.environ.get('DOCKER_SOCKET', '/run/docker.sock'))
arg_list = ' '.join(args)
cmd = ('DOCKER_HOST=unix://{docker_socket} PATH={docker_path}:$PATH '
'fig {arg_list}'
.format(**locals()))
return subprocess.check_output(cmd, shell=True).strip()
DOCKER = '/usr/bin/docker'
DOCKER_SOCKET = 'unix://{}'.format(
path(os.environ.get('DOCKER_SOCKET', '/run/docker.sock')))
DOCKER_RUN = os.environ.get('DOCKER_RUN')
| import os
import subprocess
def env(image):
"""Return environment of image. """
out = docker('inspect', '-f', '{{.Config.Env}}', image)
return dict(map(lambda x: x.split('='), out.strip()[1:-1].split()))
def path(p):
"""Build the corresponding path `p` inside the container. """
return os.path.normpath(os.path.join(
os.environ.get('HOST_PREFIX', '/host'), './{}'.format(p)))
def docker(*args):
"""Execute a docker command inside the container. """
docker_binary = DOCKER
docker_socket = DOCKER_SOCKET
cmd = ('{docker_binary} -H unix://{docker_socket}'
.format(**locals()).split())
cmd.extend(args)
return subprocess.check_output(cmd).strip()
def fig(*args):
docker_path = os.path.dirname(
path(os.environ.get('DOCKER_BINARY', '/usr/bin/docker')))
docker_socket = path(os.environ.get('DOCKER_SOCKET', '/run/docker.sock'))
arg_list = ' '.join(args)
cmd = ('DOCKER_HOST=unix://{docker_socket} PATH={docker_path}:$PATH '
'fig {arg_list}'
.format(**locals()))
return subprocess.check_output(cmd, shell=True).strip()
DOCKER = '/usr/bin/docker'
DOCKER_SOCKET = 'unix://{}'.format(
path(os.environ.get('DOCKER_SOCKET', '/run/docker.sock')))
DOCKER_RUN = os.environ.get('DOCKER_RUN')
|
Clean up some comments on ConfigTrait | <?php
namespace Elasticquent;
trait ElasticquentConfigTrait
{
/**
* Get the Elasticquent config
*
* @param string $key the configuration key
* @param string $prefix filename of configuration file
* @return array configuration
*/
public function getElasticConfig($key = 'config', $prefix = 'elasticquent')
{
$key = $prefix . ($key ? '.' : '') . $key;
if (function_exists('config')) {
// Get config helper for Laravel 5.1+
$config_helper = config();
} elseif (function_exists('app')) { // Laravel 4 and 5.0
// Get config helper for Laravel 4 & Laravel 5.1
$config_helper = app('config');
} else {
// Create a config helper when using stand-alone Eloquent
$config_helper = $this->getConfigHelper();
}
return $config_helper->get($key);
}
/**
* Inject given config file into an instance of Laravel's config
*
* @throws \Exception when the configuration file is not found
* @return \Illuminate\Config\Repository configuration repository
*/
protected function getConfigHelper()
{
$config_file = $this->getConfigFile();
if (!file_exists($config_file)) {
throw new \Exception('Config file not found.');
}
return new \Illuminate\Config\Repository(array('elasticquent' => require($config_file)));
}
/**
* Get the config path and file name to use when Laravel framework isn't present
* e.g. using Eloquent stand-alone or running unit tests
*
* @return string config file path
*/
protected function getConfigFile()
{
return __DIR__.'/config/elasticquent.php';
}
}
| <?php
namespace Elasticquent;
trait ElasticquentConfigTrait
{
/**
* Get the Elasticquent config
*
* @param string $key the configuration key
* @param string $prefix filename of configuration file
* @return array configuration
*/
public function getElasticConfig($key = 'config', $prefix = 'elasticquent')
{
$config = array();
$key = $prefix . ($key ? '.' : '') . $key;
if (function_exists('config')) { // Laravel 5.1+
$config_helper = config();
} elseif (function_exists('app')) { // Laravel 4 and 5.0
$config_helper = app('config');
} else { // stand-alone Eloquent
$config_helper = $this->getConfigHelper();
}
return $config_helper->get($key);
}
/**
* Inject given config file into an instance of Laravel's config
*
* @return object Illuminate\Config\Repository
*/
protected function getConfigHelper()
{
$config_file = $this->getConfigFile();
if (!file_exists($config_file)) {
throw new \Exception('Config file not found.');
}
return new \Illuminate\Config\Repository(array('elasticquent' => require($config_file)));
}
/**
* Get the config path and file name to use when Laravel framework isn't present
* e.g. using Eloquent stand-alone or running unit tests
*
* @return string config file path
*/
protected function getConfigFile()
{
return __DIR__.'/config/elasticquent.php';
}
}
|
Use https for GitHub issue link | package us.myles.ViaVersion.exception;
import java.util.HashMap;
import java.util.Map;
public class InformativeException extends Exception {
private final Map<String, Object> info = new HashMap<>();
private int sources;
public InformativeException(Throwable cause) {
super(cause);
}
public InformativeException set(String key, Object value) {
info.put(key, value);
return this;
}
public InformativeException addSource(Class<?> sourceClazz) {
return set("Source " + sources++, getSource(sourceClazz));
}
private String getSource(Class<?> sourceClazz) {
if (sourceClazz.isAnonymousClass()) {
return sourceClazz.getName() + " (Anonymous)";
} else {
return sourceClazz.getName();
}
}
@Override
public String getMessage() {
StringBuilder builder = new StringBuilder();
builder.append("Please post this error to https://github.com/ViaVersion/ViaVersion/issues\n{");
int i = 0;
for (Map.Entry<String, Object> entry : info.entrySet()) {
builder.append(i == 0 ? "" : ", ").append(entry.getKey()).append(": ").append(entry.getValue().toString());
i++;
}
builder.append("}\nActual Error: ");
return builder.toString();
}
@Override
public synchronized Throwable fillInStackTrace() {
// Don't record this stack
return this;
}
}
| package us.myles.ViaVersion.exception;
import java.util.HashMap;
import java.util.Map;
public class InformativeException extends Exception {
private final Map<String, Object> info = new HashMap<>();
private int sources;
public InformativeException(Throwable cause) {
super(cause);
}
public InformativeException set(String key, Object value) {
info.put(key, value);
return this;
}
public InformativeException addSource(Class<?> sourceClazz) {
return set("Source " + sources++, getSource(sourceClazz));
}
private String getSource(Class<?> sourceClazz) {
if (sourceClazz.isAnonymousClass()) {
return sourceClazz.getName() + " (Anonymous)";
} else {
return sourceClazz.getName();
}
}
@Override
public String getMessage() {
StringBuilder builder = new StringBuilder();
builder.append("Please post this error to http://github.com/ViaVersion/ViaVersion/issues\n{");
int i = 0;
for (Map.Entry<String, Object> entry : info.entrySet()) {
builder.append(i == 0 ? "" : ", ").append(entry.getKey()).append(": ").append(entry.getValue().toString());
i++;
}
builder.append("}\nActual Error: ");
return builder.toString();
}
@Override
public synchronized Throwable fillInStackTrace() {
// Don't record this stack
return this;
}
}
|
Make sure country userinfo response is valid. | <?php
namespace Northstar\Http\Transformers;
use Northstar\Models\User;
use League\Fractal\TransformerAbstract;
class UserInfoTransformer extends TransformerAbstract
{
/**
* @param User $user
* @return array
*/
public function transform(User $user)
{
// User data, formatted according to OpenID Connect spec, section 5.3.
// @see http://openid.net/specs/openid-connect-core-1_0.html#UserInfo
$response = [
'id' => $user->_id,
'given_name' => $user->first_name,
'family_name' => $user->last_name,
'email' => $user->email,
'phone_number' => $user->mobile,
'birthdate' => format_date($user->birthdate, 'Y-m-d'),
'address' => [
'street_address' => implode(PHP_EOL, [$user->addr_street1, $user->addr_street2]),
'locality' => $user->addr_city,
'region' => $user->addr_state,
'postal_code' => $user->addr_zip,
'country' => strlen($user->country) === 2 ? $user->country : null,
],
'updated_at' => $user->updated_at->timestamp,
'created_at' => $user->created_at->timestamp,
];
return $response;
}
}
| <?php
namespace Northstar\Http\Transformers;
use Northstar\Models\User;
use League\Fractal\TransformerAbstract;
class UserInfoTransformer extends TransformerAbstract
{
/**
* @param User $user
* @return array
*/
public function transform(User $user)
{
// User data, formatted according to OpenID Connect spec, section 5.3.
// @see http://openid.net/specs/openid-connect-core-1_0.html#UserInfo
$response = [
'id' => $user->_id,
'given_name' => $user->first_name,
'family_name' => $user->last_name,
'email' => $user->email,
'phone_number' => $user->mobile,
'birthdate' => format_date($user->birthdate, 'Y-m-d'),
'address' => [
'street_address' => implode(PHP_EOL, [$user->addr_street1, $user->addr_street2]),
'locality' => $user->addr_city,
'region' => $user->addr_state,
'postal_code' => $user->addr_zip,
'country' => $user->country,
],
'updated_at' => $user->updated_at->timestamp,
'created_at' => $user->created_at->timestamp,
];
return $response;
}
}
|
Use fat arrow syntax for callbacks. | {
angular.module('meganote.notesForm')
.controller('NotesFormController', NotesFormController);
NotesFormController.$inject = ['$state', 'Flash', 'NotesService'];
function NotesFormController($state, Flash, NotesService) {
const vm = this;
vm.note = NotesService.find($state.params.noteId);
vm.clearForm = clearForm;
vm.save = save;
vm.destroy = destroy;
/////////////////
function clearForm() {
vm.note = { title: '', body_html: '' };
}
function save() {
if (vm.note._id) {
NotesService.update(vm.note)
.then(
res => {
vm.note = angular.copy(res.data.note);
Flash.create('success', res.data.message);
},
() => Flash.create('danger', 'Oops! Something went wrong.')
);
}
else {
NotesService.create(vm.note)
.then(
res => {
vm.note = res.data.note;
Flash.create('success', res.data.message);
$state.go('notes.form', { noteId: vm.note._id });
},
() => Flash.create('danger', 'Oops! Something went wrong.')
);
}
}
function destroy() {
NotesService.destroy(vm.note)
.then(
() => vm.clearForm()
);
}
}
}
| {
angular.module('meganote.notesForm')
.controller('NotesFormController', NotesFormController);
NotesFormController.$inject = ['$state', 'Flash', 'NotesService'];
function NotesFormController($state, Flash, NotesService) {
const vm = this;
vm.note = NotesService.find($state.params.noteId);
vm.clearForm = clearForm;
vm.save = save;
vm.destroy = destroy;
/////////////////
function clearForm() {
vm.note = { title: '', body_html: '' };
}
function save() {
if (vm.note._id) {
NotesService.update(vm.note)
.then(
function(res) {
vm.note = angular.copy(res.data.note);
Flash.create('success', res.data.message);
},
function() {
Flash.create('danger', 'Oops! Something went wrong.');
});
}
else {
NotesService.create(vm.note)
.then(
function(res) {
vm.note = res.data.note;
Flash.create('success', res.data.message);
$state.go('notes.form', { noteId: vm.note._id });
},
function() {
Flash.create('danger', 'Oops! Something went wrong.');
});
}
}
function destroy() {
NotesService.destroy(vm.note)
.then(function() {
vm.clearForm();
});
}
}
}
|
Remove php 5.4 array tags | <?php
namespace Payum\Core\Tests\Mocks\Model;
use Payum\Core\Exception\LogicException;
class Propel2ModelQuery
{
const MODEL_CLASS = "Payum\\Core\\Tests\\Mocks\\Model\\Propel2Model";
protected $filters = array();
protected $modelReflection;
public function __construct()
{
$this->modelReflection = new \ReflectionClass(static::MODEL_CLASS);
}
public function filterBy($column, $value)
{
if (!$this->modelReflection->hasProperty($column)) {
throw new LogicException(sprintf(
"The model doesn't have the column '%s'",
$column
));
}
$this->filters[] = array($column, $value);
return $this;
}
public function findOne()
{
$model = new Propel2Model();
$this->applyFilters($model);
return $model;
}
public function findPk($id)
{
$model = new Propel2Model();
$model->setId($id);
return $model;
}
protected function applyFilters(Propel2Model $model)
{
foreach ($this->filters as $filter) {
$propriety = new \ReflectionProperty(static::MODEL_CLASS, $filter[0]);
$propriety->setAccessible(true);
$propriety->setValue($model, $filter[1]);
}
}
}
| <?php
namespace Payum\Core\Tests\Mocks\Model;
use Payum\Core\Exception\LogicException;
class Propel2ModelQuery
{
const MODEL_CLASS = "Payum\\Core\\Tests\\Mocks\\Model\\Propel2Model";
protected $filters = array();
protected $modelReflection;
public function __construct()
{
$this->modelReflection = new \ReflectionClass(static::MODEL_CLASS);
}
public function filterBy($column, $value)
{
if (!$this->modelReflection->hasProperty($column)) {
throw new LogicException(sprintf(
"The model doesn't have the column '%s'",
$column
));
}
$this->filters[] = [$column, $value];
return $this;
}
public function findOne()
{
$model = new Propel2Model();
$this->applyFilters($model);
return $model;
}
public function findPk($id)
{
$model = new Propel2Model();
$model->setId($id);
return $model;
}
protected function applyFilters(Propel2Model $model)
{
foreach ($this->filters as $filter) {
$propriety = new \ReflectionProperty(static::MODEL_CLASS, $filter[0]);
$propriety->setAccessible(true);
$propriety->setValue($model, $filter[1]);
}
}
}
|
Make correct context when select entity in search | 'use strict';
angular.module('mean.icu').service('context', function ($injector, $q) {
var mainMap = {
task: 'tasks',
user: 'people',
project: 'projects',
discussion: 'discussions',
officeDocument:'officeDocuments',
office: 'offices',
templateDoc: 'templateDocs',
folder: 'folders'
};
return {
entity: null,
entityName: '',
entityId: '',
main: '',
setMain: function (main) {
this.main = mainMap[main];
},
getContextFromState: function(state) {
var parts = state.name.split('.');
if (parts[0] === 'main') {
var reverseMainMap = _(mainMap).invert();
var main = 'task';
if (parts[1] !== 'search') {
main = reverseMainMap[parts[1]];
}
// When in context of search, the entity you selected is in parts[2]
if (parts[1] == 'search') {
main = reverseMainMap[parts[2]];
}
var params = state.params;
var entityName = params.entity;
if (!entityName && parts[2] === 'all') {
entityName = 'all';
}
if (!entityName && parts[2] === 'byassign') {
entityName = 'my';
}
if (!entityName && parts[2] === 'byparent') {
entityName = main;
}
return {
main: main,
entityName: entityName,
entityId: params.entityId
};
}
}
};
});
| 'use strict';
angular.module('mean.icu').service('context', function ($injector, $q) {
var mainMap = {
task: 'tasks',
user: 'people',
project: 'projects',
discussion: 'discussions',
officeDocument:'officeDocuments',
office: 'offices',
templateDoc: 'templateDocs',
folder: 'folders'
};
return {
entity: null,
entityName: '',
entityId: '',
main: '',
setMain: function (main) {
this.main = mainMap[main];
},
getContextFromState: function(state) {
var parts = state.name.split('.');
if (parts[0] === 'main') {
var reverseMainMap = _(mainMap).invert();
var main = 'task';
if (parts[1] !== 'search') {
main = reverseMainMap[parts[1]];
}
var params = state.params;
var entityName = params.entity;
if (!entityName && parts[2] === 'all') {
entityName = 'all';
}
if (!entityName && parts[2] === 'byassign') {
entityName = 'my';
}
if (!entityName && parts[2] === 'byparent') {
entityName = main;
}
return {
main: main,
entityName: entityName,
entityId: params.entityId
};
}
}
};
});
|
Add play icon to demo button | <?php echo $head; ?>
<div class="pure-g centered-row">
<div class="pure-u-1">
<div class="l-box">
<p> <?php
echo _('Hey!');
echo ' ';
?>
</p>
<p> <?php
echo ' ';
echo _('Welcome to the captive portal.');
?>
</p>
<p> <?php
echo ' ';
echo _('You need to be connected to our WLAN Hotspot for complete functionality.');
?>
</p>
<p> <?php
echo ' ';
echo _('However, you can try a demo mode!');
echo ' ';
echo _('After you log in with Facebook, you will be redirected to our website at');
echo ' ';
echo $portal_url;
echo '.';
?>
</p>
<p>
<a class="pure-button pure-button-primary" href="<?php echo $page_url; ?>">
<i class="fa fa-play lg"></i>
<?php echo 'Demo: Connect to ' . $page_name . _(' on Facebook'); ?>
</a>
</p>
</div>
</div>
</div>
<?php echo $foot; ?>
| <?php echo $head; ?>
<div class="pure-g centered-row">
<div class="pure-u-1">
<div class="l-box">
<p> <?php
echo _('Hey!');
echo ' ';
?>
</p>
<p> <?php
echo ' ';
echo _('Welcome to the captive portal.');
?>
</p>
<p> <?php
echo ' ';
echo _('You need to be connected to our WLAN Hotspot for complete functionality.');
?>
</p>
<p> <?php
echo ' ';
echo _('However, you can try a demo mode!');
echo ' ';
echo _('After you log in with Facebook, you will be redirected to our website at');
echo ' ';
echo $portal_url;
echo '.';
?>
</p>
<p>
<a class="pure-button pure-button-primary" href="<?php echo $page_url; ?>"><?php echo 'Demo: Connect to ' . $page_name . _(' on Facebook'); ?></a>
</p>
</div>
</div>
</div>
<?php echo $foot; ?>
|
Fix transformer errors for undefined source dates | <?php
namespace App\Http\Transformers;
use Illuminate\Support\Facades\Log;
use League\Fractal\TransformerAbstract;
class ApiTransformer extends TransformerAbstract
{
public $excludeIdsAndTitle = false;
public $excludeDates = false;
/**
* Turn this item object into a generic array.
*
* @param Illuminate\Database\Eloquent\Model $item
* @return array
*/
public function transform($item)
{
return array_merge(
$this->transformIdsAndTitle($item),
$this->transformFields($item),
$this->transformDates($item)
);
}
protected function transformFields($item)
{
return $item->transform();
}
protected function transformIdsAndTitle($item)
{
if ($this->excludeIdsAndTitle)
{
return [];
}
return [
'id' => $item->getAttributeValue($item->getKeyName()),
'title' => $item->title,
];
}
protected function transformDates($item)
{
if ($this->excludeDates)
{
return [];
}
$dates = [];
if ( $item->source_modified_at )
{
$dates['last_updated_source'] = $item->source_modified_at->toIso8601String();
}
if ( $item->updated_at )
{
$dates['last_updated'] = $item->updated_at->toIso8601String();
}
return $dates;
}
}
| <?php
namespace App\Http\Transformers;
use Illuminate\Support\Facades\Log;
use League\Fractal\TransformerAbstract;
class ApiTransformer extends TransformerAbstract
{
public $excludeIdsAndTitle = false;
public $excludeDates = false;
/**
* Turn this item object into a generic array.
*
* @param Illuminate\Database\Eloquent\Model $item
* @return array
*/
public function transform($item)
{
return array_merge(
$this->transformIdsAndTitle($item),
$this->transformFields($item),
$this->transformDates($item)
);
}
protected function transformFields($item)
{
return $item->transform();
}
protected function transformIdsAndTitle($item)
{
if ($this->excludeIdsAndTitle)
{
return [];
}
return [
'id' => $item->getAttributeValue($item->getKeyName()),
'title' => $item->title,
];
}
protected function transformDates($item)
{
if ($this->excludeDates)
{
return [];
}
return [
'last_updated_source' => $item->source_modified_at->toIso8601String(),
'last_updated' => $item->updated_at->toIso8601String(),
];
}
}
|
Tweak map styles to match theme | angular.module('dplaceMapDirective', [])
.directive('dplaceMap', function() {
function link(scope, element, attrs) {
element.append("<div id='mapdiv' style='width:1140px; height:480px;'></div>");
scope.map = $('#mapdiv').vectorMap({
map: 'world_mill_en',
backgroundColor: 'white',
regionStyle: {
initial: {
fill: '#428bca',
"fill-opacity": 1,
stroke: '#357ebd',
"stroke-width": 0,
"stroke-opacity": 1
},
hover: {
"fill-opacity": 0.8
},
selected: {
fill: 'yellow'
},
selectedHover: {
}
}
}).vectorMap('get','mapObject');
scope.addMarkers = function() {
scope.map.removeAllMarkers();
if(!scope.societies) {
return;
}
scope.societies.forEach(function(societyResult) {
var society = societyResult.society;
// Add a marker for each point
var marker = {latLng: society.location.coordinates.reverse(), name: society.name}
scope.map.addMarker(society.id, marker);
});
};
// Update markers when societies change
scope.$watchCollection('societies', function(oldvalue, newvalue) {
scope.addMarkers();
});
scope.$on('mapTabActivated', function(event, args) {
scope.map.setSize();
});
}
return {
restrict: 'E',
scope: {
societies: '='
},
link: link
};
}); | angular.module('dplaceMapDirective', [])
.directive('dplaceMap', function() {
function link(scope, element, attrs) {
element.append("<div id='mapdiv' style='width:1140px; height:480px;'></div>");
scope.map = $('#mapdiv').vectorMap({map: 'world_mill_en'}).vectorMap('get','mapObject');
scope.addMarkers = function() {
scope.map.removeAllMarkers();
if(!scope.societies) {
return;
}
scope.societies.forEach(function(societyResult) {
var society = societyResult.society;
// Add a marker for each point
var marker = {latLng: society.location.coordinates.reverse(), name: society.name}
scope.map.addMarker(society.id, marker);
});
};
// Update markers when societies change
scope.$watchCollection('societies', function(oldvalue, newvalue) {
scope.addMarkers();
});
scope.$on('mapTabActivated', function(event, args) {
scope.map.setSize();
});
}
return {
restrict: 'E',
scope: {
societies: '='
},
link: link
};
}); |
Add support for absolute URL in request | from ..darkobject import DarkObject
from bs4 import BeautifulSoup
import requests
import logging
import time
class Scrubber(DarkObject):
def __init__(self):
super(Scrubber, self).__init__()
def scrub(self):
"""
Get item metadata.
"""
return {}
# noinspection PyBroadException
@staticmethod
def soup(url, absolute: bool = False, **kwargs):
"""
Open URL and create tag soup.
:param url: website string
:type url: str
:param absolute: perform double get request to find absolute url
:type absolute: bool
"""
handle = ''
max_tries = 10
for i in range(max_tries):
# noinspection PyPep8
try:
if absolute:
url = requests.get(url).url
handle = requests.get(url, params=kwargs).text
break
except Exception:
logging.exception('urlopen failed (attempt %d)', i + 1)
if i == max_tries - 1:
logging.error('the maximum urlopen attempts have been reached')
raise
time.sleep(1)
s = BeautifulSoup(handle, features='html5lib')
return s
if __name__ == '__main__':
pass
| from ..darkobject import DarkObject
from bs4 import BeautifulSoup
import logging
import time
from urllib.request import urlopen
class Scrubber(DarkObject):
def __init__(self):
super(Scrubber, self).__init__()
def scrub(self):
"""
Get item metadata.
"""
return {}
# noinspection PyBroadException
@staticmethod
def soup(url):
"""
Open URL and create tag soup.
:param url: website string
:type url: str
"""
handle = ''
max_tries = 10
for i in range(max_tries):
# noinspection PyPep8
try:
handle = urlopen(url)
handle = handle.read()
break
except:
logging.exception('urlopen failed (attempt %d)', i + 1)
if i == max_tries - 1:
logging.error('the maximum urlopen attempts have been reached')
raise
time.sleep(1)
s = BeautifulSoup(handle, features='html5lib')
return s
if __name__ == '__main__':
pass
|
Update in the update function |
# Github Tray App
import rumps
import config
import contribs
class GithubTrayApp(rumps.App):
def __init__(self):
super(GithubTrayApp, self).__init__('Github')
self.count = rumps.MenuItem('commits')
self.username = config.get_username()
self.menu = [
self.count,
'Update Now',
'Change Frequency',
'Change Username'
]
self.update()
def update(self):
try:
print('Updating user')
num = str(contribs.get_contribs(self.username))
self.icon = 'github0.png' if num == '0' else 'github.png'
self.count.title = num + ' commits'
except Exception as e: print(e)
@rumps.timer(60*5)
def timer(self, _):
self.update()
@rumps.clicked('Update Now')
def update_now(self, _):
self.update()
@rumps.clicked('Change Frequency')
def change_frequency(_):
rumps.alert('jk! not ready yet!')
@rumps.clicked('Change Username')
def change_username(_):
rumps.alert('jk! not ready yet!')
if __name__ == '__main__':
GithubTrayApp().run()
|
# Github Tray App
import rumps
import config
import contribs
class GithubTrayApp(rumps.App):
def __init__(self):
super(GithubTrayApp, self).__init__('Github')
self.count = rumps.MenuItem('commits')
self.username = config.get_username()
self.menu = [
self.count,
'Update Now',
'Change Frequency',
'Change Username'
]
self.update()
def update(self):
try:
num = str(contribs.get_contribs(self.username))
self.icon = 'github0.png' if num == '0' else 'github.png'
self.count.title = num + ' commits'
except Exception as e: print(e)
@rumps.timer(60*5)
def timer(self, _):
print('Running timer')
self.update()
@rumps.clicked('Update Now')
def update_now(self, _):
self.update()
@rumps.clicked('Change Frequency')
def change_frequency(_):
rumps.alert('jk! not ready yet!')
@rumps.clicked('Change Username')
def change_username(_):
rumps.alert('jk! not ready yet!')
if __name__ == '__main__':
GithubTrayApp().run()
|
Add implementation hasTable to Mysqli schema | <?php
namespace DB\Schema;
class MySQLi implements ISchema
{
private $fields = array();
private $cons = array();
public function addField($field)
{
$this->fields[] = "`$field->name` $field->type".($field->null?'':' NOT NULL ').
($field->autoinc?' AUTO_INCREMENT ':'');
}
public function addConstraint($cons)
{
$k = '';
switch ($cons->type) {
case \DB\SchemaConstraint::TYPE_PRIMARY:
$k = 'PRIMARY KEY';
break;
case \DB\SchemaConstraint::TYPE_UNIQUE:
$k = 'UNIQUE KEY';
break;
case \DB\SchemaConstraint::TYPE_INDEX:
$k = 'INDEX KEY';
break;
}
$this->cons[] = "$k (`$cons->name`)";
}
public function hasTable($name)
{
$result = $this->db->query("SHOW TABLES LIKE `$name`");
return (!$result->isError() && $result->count() > 0);
}
public function create($table)
{
$fs = '';
foreach ($this->fields as $field)
{
if ($fs === '')
{
$fs = $field;
}
else
{
$fs .= ', '. $field;
}
}
foreach ($this->cons as $cons)
{
$fs .= ', '. $cons;
}
$sql = "CREATE TABLE `$table` ($fs)";
$result = $this->db->query($sql);
return !($result->isError());
}
}
?>
| <?php
namespace DB\Schema;
class MySQLi implements ISchema
{
private $fields = array();
private $cons = array();
public function addField($field)
{
$this->fields[] = "`$field->name` $field->type".($field->null?'':' NOT NULL ').
($field->autoinc?' AUTO_INCREMENT ':'');
}
public function addConstraint($cons)
{
$k = '';
switch ($cons->type) {
case \DB\SchemaConstraint::TYPE_PRIMARY:
$k = 'PRIMARY KEY';
break;
case \DB\SchemaConstraint::TYPE_UNIQUE:
$k = 'UNIQUE KEY';
break;
case \DB\SchemaConstraint::TYPE_INDEX:
$k = 'INDEX KEY';
break;
}
$this->cons[] = "$k (`$cons->name`)";
}
public function create($table)
{
$fs = '';
foreach ($this->fields as $field)
{
if ($fs === '')
{
$fs = $field;
}
else
{
$fs .= ', '. $field;
}
}
foreach ($this->cons as $cons)
{
$fs .= ', '. $cons;
}
$sql = "CREATE TABLE `$table` ($fs)";
$result = $this->db->query($sql);
return !($result->isError());
}
}
?>
|
Remove warning from debug toolbar. | import os
from .default import * # nopep8
DEBUG = True
TEMPLATE_DEBUG = DEBUG
if DEBUG:
INSTALLED_APPS += (
'debug_toolbar',
)
# debug toolbar settings
MIDDLEWARE_CLASSES += (
'debug_toolbar.middleware.DebugToolbarMiddleware',
)
DEBUG_TOOLBAR_PANELS = (
'debug_toolbar.panels.versions.VersionsPanel',
'debug_toolbar.panels.timer.TimerPanel',
'debug_toolbar.panels.settings.SettingsPanel',
'debug_toolbar.panels.headers.HeadersPanel',
'debug_toolbar.panels.request.RequestPanel',
'debug_toolbar.panels.templates.TemplatesPanel',
'debug_toolbar.panels.sql.SQLPanel',
'debug_toolbar.panels.signals.SignalsPanel',
'debug_toolbar.panels.logging.LoggingPanel',
)
DEBUG_TOOLBAR_CONFIG = {
'SHOW_TOOLBAR_CALLBACK': 'allmychanges.utils.show_debug_toolbar'
}
METRIKA_ID = '24627125'
ANALYTICS_ID = 'UA-49927178-2'
LOG_FILENAME = '/var/log/allmychanges/django-' + CURRENT_USER + '.log'
init_logging(LOG_FILENAME)
if not os.path.exists(TEMP_DIR):
os.makedirs(TEMP_DIR)
ALLOWED_HOSTS = ['localhost', 'art.dev.allmychanges.com']
| import os
from .default import * # nopep8
DEBUG = True
TEMPLATE_DEBUG = DEBUG
if DEBUG:
INSTALLED_APPS += (
'debug_toolbar',
)
# debug toolbar settings
MIDDLEWARE_CLASSES += (
'debug_toolbar.middleware.DebugToolbarMiddleware',
)
DEBUG_TOOLBAR_PANELS = (
'debug_toolbar.panels.versions.VersionsPanel',
'debug_toolbar.panels.timer.TimerPanel',
'debug_toolbar.panels.settings.SettingsPanel',
'debug_toolbar.panels.headers.HeadersPanel',
'debug_toolbar.panels.request.RequestPanel',
'debug_toolbar.panels.templates.TemplatesPanel',
'debug_toolbar.panels.sql.SQLPanel',
'debug_toolbar.panels.signals.SignalsPanel',
'debug_toolbar.panels.logging.LoggingPanel',
)
DEBUG_TOOLBAR_CONFIG = {
'INTERCEPT_REDIRECTS': False,
'SHOW_TOOLBAR_CALLBACK': 'allmychanges.utils.show_debug_toolbar'
}
METRIKA_ID = '24627125'
ANALYTICS_ID = 'UA-49927178-2'
LOG_FILENAME = '/var/log/allmychanges/django-' + CURRENT_USER + '.log'
init_logging(LOG_FILENAME)
if not os.path.exists(TEMP_DIR):
os.makedirs(TEMP_DIR)
ALLOWED_HOSTS = ['localhost', 'art.dev.allmychanges.com']
|
Align cfg logo right on larger screens | <footer class="row">
<div class="c-footer col-xs-12 col-md-offset-2 col-md-8">
<div class="row">
<div class="col-xs-6 col-sm-4">
<img
src="{{ asset('img/logos/okf.svg') }}"
alt="Logo der OpenKnowledge Foundation Deutschland" height="48"
/>
</div>
<div class="col-xs-6 col-sm-4 end-sm">
<img src="{{ asset('img/logos/cfg.svg') }}" alt="Logo von Code for Germany" height="48" />
</div>
<div class="col-xs-12 col-sm-4 first-sm middle-sm">
<a href="{{ route('locale.set', ['language' => 'de']) }}" title="Sprache auf Deutsch umstellen.">
<span class="flag-icon flag-icon-de flag-icon-squared u-round"></span>
</a>
<a href="{{ route('locale.set', ['language' => 'en']) }}" title="Switch language to English.">
<span class="flag-icon flag-icon-gb flag-icon-squared u-round"></span>
</a>
</div>
</div>
</div>
</footer>
| <footer class="row">
<div class="c-footer col-xs-12 col-md-offset-2 col-md-8">
<div class="row">
<div class="col-xs-6 col-sm-4">
<img
src="{{ asset('img/logos/okf.svg') }}"
alt="Logo der OpenKnowledge Foundation Deutschland" height="48"
/>
</div>
<div class="col-xs-6 col-sm-4">
<img src="{{ asset('img/logos/cfg.svg') }}" alt="Logo von Code for Germany" height="48" />
</div>
<div class="col-xs-12 col-sm-4 first-sm middle-sm">
<a href="{{ route('locale.set', ['language' => 'de']) }}" title="Sprache auf Deutsch umstellen.">
<span class="flag-icon flag-icon-de flag-icon-squared u-round"></span>
</a>
<a href="{{ route('locale.set', ['language' => 'en']) }}" title="Switch language to English.">
<span class="flag-icon flag-icon-gb flag-icon-squared u-round"></span>
</a>
</div>
</div>
</div>
</footer>
|
Add quit button functionality in menuView | /**
* Package contains all the views required by budgetreporter
*/
package com.budgetreporter.View;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
* @author jacky
*
*/
public class MenuView extends JPanel{
public MenuView(){
super();
initUI();
}
public void initUI(){
GridLayout gLayout = new GridLayout(0,1);
this.setLayout(gLayout);
//Add the "View Report" button
JButton viewReportButton = new JButton("View Report");
//Add the "New Expense" button
JButton newExpenseButton = new JButton("New Expense");
//Add the "New Income" button
JButton newIncomeButton = new JButton("New Income");
//Add the "Profile" button
JButton profileButton = new JButton("Profile");
//Add the "Quit" button
JButton quitButton = new JButton("Quit");
quitButton.addActionListener(new QuitButtonListener());
this.add(profileButton);
this.add(viewReportButton);
this.add(newExpenseButton);
this.add(newIncomeButton);
this.add(quitButton);
System.out.println("Menu page created");
}
private class QuitButtonListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
}
| /**
* Package contains all the views required by budgetreporter
*/
package com.budgetreporter.View;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
* @author jacky
*
*/
public class MenuView extends JPanel{
public MenuView(){
super();
initUI();
}
public void initUI(){
GridLayout gLayout = new GridLayout(0,1);
this.setLayout(gLayout);
//Add the "View Report" button
JButton viewReportButton = new JButton("View Report");
//Add the "New Expense" button
JButton newExpenseButton = new JButton("New Expense");
//Add the "New Income" button
JButton newIncomeButton = new JButton("New Income");
//Add the "Profile" button
JButton profileButton = new JButton("Profile");
//Add the "Quit" button
JButton quitButton = new JButton("Quit");
this.add(profileButton);
this.add(viewReportButton);
this.add(newExpenseButton);
this.add(newIncomeButton);
this.add(quitButton);
System.out.println("Menu page created");
}
}
|
Add semantic tags for devsys | import React, {PropTypes} from 'react'
import SyntaxHighlighter from 'react-syntax-highlighter'
import { docco } from 'react-syntax-highlighter/dist/styles'
import Button from '../Button'
import Avatar from '../Avatar'
export default function Card ({ avatar, message, fullname, username, snippet = {} }) {
return (
<article className='card'>
<header className='card-header'>
<Avatar img={avatar} size={'l'} />
<h4 className='card-title'>{fullname}</h4>
<h6 className='card-meta'>{username}</h6>
</header>
<section className='card-body'>{message}</section>
<SyntaxHighlighter language={snippet.language} style={docco}>
{snippet.code}
</SyntaxHighlighter>
<footer className='card-footer'>
<Button />
<button className='btn lnr lnr-bubble'></button>
<button className='btn lnr lnr-heart'></button>
<button className='btn lnr lnr-code'></button>
</footer>
</article>
)
}
Card.propTypes = {
avatar: PropTypes.string,
fullname: PropTypes.string,
username: PropTypes.string,
message: PropTypes.string,
snippet: PropTypes.shape({
language: PropTypes.string,
code: PropTypes.string
})
}
Card.defaultProps = {
avatar: 'https://picturepan2.github.io/spectre/demo/img/avatar-1.png'
}
| import React, {PropTypes} from 'react'
import SyntaxHighlighter from 'react-syntax-highlighter'
import { docco } from 'react-syntax-highlighter/dist/styles'
import Button from '../Button'
import Avatar from '../Avatar'
export default function Card ({ avatar, message, fullname, username, snippet = {} }) {
return (
<div className='card'>
<header className='card-header'>
<Avatar img={avatar} size={'l'} />
<h4 className='card-title'>{fullname}</h4>
<h6 className='card-meta'>{username}</h6>
</header>
<section className='card-body'>{message}</section>
<SyntaxHighlighter language={snippet.language} style={docco}>
{snippet.code}
</SyntaxHighlighter>
<footer className='card-footer'>
<Button />
<button className='btn lnr lnr-bubble'></button>
<button className='btn lnr lnr-heart'></button>
<button className='btn lnr lnr-code'></button>
</footer>
</div>
)
}
Card.propTypes = {
avatar: PropTypes.string,
fullname: PropTypes.string,
username: PropTypes.string,
message: PropTypes.string,
snippet: PropTypes.shape({
language: PropTypes.string,
code: PropTypes.string
})
}
Card.defaultProps = {
avatar: 'https://picturepan2.github.io/spectre/demo/img/avatar-1.png'
}
|
Handle error case for username shortening | 'use strict';
/**
* @ngdoc function
* @name dockstore.ui.controller:NavbarCtrl
* @description
* # NavbarCtrl
* Controller of the dockstore.ui
*/
angular.module('dockstore.ui')
.controller('NavbarCtrl', [
'$scope',
'$rootScope',
'$auth',
'$location',
'UserService',
'NotificationService',
function ($scope, $rootScope, $auth, $location,
UserService, NtfnService) {
$scope.userObj = UserService.getUserObj();
$scope.isAuthenticated = function() {
return $auth.isAuthenticated();
};
$scope.isHomePage = function() {
return ($location.url() === '/');
};
$scope.logout = function() {
UserService.logout();
};
$scope.$watch('searchQuery', function(newValue, oldValue) {
$rootScope.searchQuery = newValue;
});
$scope.$on('$routeChangeStart', function(event, next, current) {
if ($location.url().indexOf('/search') === -1) {
$scope.searchQuery = '';
}
});
}]).filter('shortenString', function() {
return function (string, scope) {
if (string != null && string.length > 10) {
return string.substring(0,9) + '...';
} else {
return string;
}
};
});
| 'use strict';
/**
* @ngdoc function
* @name dockstore.ui.controller:NavbarCtrl
* @description
* # NavbarCtrl
* Controller of the dockstore.ui
*/
angular.module('dockstore.ui')
.controller('NavbarCtrl', [
'$scope',
'$rootScope',
'$auth',
'$location',
'UserService',
'NotificationService',
function ($scope, $rootScope, $auth, $location,
UserService, NtfnService) {
$scope.userObj = UserService.getUserObj();
$scope.isAuthenticated = function() {
return $auth.isAuthenticated();
};
$scope.isHomePage = function() {
return ($location.url() === '/');
};
$scope.logout = function() {
UserService.logout();
};
$scope.$watch('searchQuery', function(newValue, oldValue) {
$rootScope.searchQuery = newValue;
});
$scope.$on('$routeChangeStart', function(event, next, current) {
if ($location.url().indexOf('/search') === -1) {
$scope.searchQuery = '';
}
});
}]).filter('shortenString', function() {
return function (string, scope) {
if (string.length > 10) {
return string.substring(0,9) + '...';
} else {
return string;
}
};
});
|
Revert "Revert "Revert "Revert "Reorder operator""""
This reverts commit b24a074dde5c29efee87896bd74183330fea1948. | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package tw.edu.npu.mis;
/**
* The model class of the calculator application.
*/
public class Calculator {
/**
* The available operators of the calculator.
*/
public enum Operator {
CLEAR, // C
CLEAR_ENTRY, // CE
BACKSPACE, // ⌫
EQUAL, // =
PLUS, // +
MINUS, // -
TIMES, // ×
OVER, // ⁄
PLUS_MINUS, // ±
RECIPROCAL, // 1/x
PERCENT, // %
SQRT, // √
MEM_CLEAR, // MC
MEM_SET, // MS
MEM_PLUS, // M+
MEM_MINUS, // M-
MEM_RECALL // MR
}
public void appendDigit(int digit) {
// TODO code application logic here
}
public void appendDot() {
// TODO code application logic here
}
public void performOperation(Operator operator) {
// TODO code application logic here
}
public String getDisplay() {
// TODO code application logic here
return null;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
}
}
| /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package tw.edu.npu.mis;
/**
* The model class of the calculator application.
*/
public class Calculator {
/**
* The available operators of the calculator.
*/
public enum Operator {
EQUAL, // =
PLUS, // +
MINUS, // -
TIMES, // ×
OVER, // ⁄
PLUS_MINUS, // ±
RECIPROCAL, // 1/x
PERCENT, // %
SQRT, // √
BACKSPACE, // ⌫
CLEAR, // C
CLEAR_ENTRY, // CE
MEM_SET, // MS
MEM_PLUS, // M+
MEM_MINUS, // M-
MEM_RECALL, // MR
MEM_CLEAR // MC
}
public void appendDigit(int digit) {
// TODO code application logic here
}
public void appendDot() {
// TODO code application logic here
}
public void performOperation(Operator operator) {
// TODO code application logic here
}
public String getDisplay() {
// TODO code application logic here
return null;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
}
}
|
Add note that Java 8 provides some kind of duck typing | package info.schleichardt.training.java8.lecture2;
import java.security.MessageDigest;
public class P2_FunctionalInterfacesFirstClassMembers {
@FunctionalInterface
public interface HashFunction {
byte[] hash(final String input) throws Exception;
//return type, works also in classes
static HashFunction ofAlgorithm(final String algorithm) {
return input -> MessageDigest.getInstance(algorithm).digest(input.getBytes());
}
}
//member in a class
public static final HashFunction hashFunctionClassMember = input -> MessageDigest.getInstance("SHA2").digest(input.getBytes());
//field
private final HashFunction hashFunctionAsField = input -> MessageDigest.getInstance("SHA2").digest(input.getBytes());
//input parameter
public static byte[] hashInput(final String input, final HashFunction function) throws Exception {
return function.hash(input);
}
public static void demoForReturnType() throws Exception {
final byte[] hash1 = HashFunction.ofAlgorithm("SHA1").hash("hello");
final byte[] hash2 = hashInput("hello", HashFunction.ofAlgorithm("SHA1"));
}
//example method that is not at all related to the interface HashFunction
//but still has the same signature of taking a String as input and returning a byte array
//name is not important
//little brother of duck typing
public static byte[] md5(final String input) throws Exception {
return MessageDigest.getInstance("MD5").digest(input.getBytes());
}
//method reference
public static void demoForMethodReference() throws Exception {
final HashFunction function = P2_FunctionalInterfacesFirstClassMembers::md5;//double colon for method reference
}
}
| package info.schleichardt.training.java8.lecture2;
import java.security.MessageDigest;
public class P2_FunctionalInterfacesFirstClassMembers {
@FunctionalInterface
public interface HashFunction {
byte[] hash(final String input) throws Exception;
//return type, works also in classes
static HashFunction ofAlgorithm(final String algorithm) {
return input -> MessageDigest.getInstance(algorithm).digest(input.getBytes());
}
}
//member in a class
public static final HashFunction hashFunctionClassMember = input -> MessageDigest.getInstance("SHA2").digest(input.getBytes());
//field
private final HashFunction hashFunctionAsField = input -> MessageDigest.getInstance("SHA2").digest(input.getBytes());
//input parameter
public static byte[] hashInput(final String input, final HashFunction function) throws Exception {
return function.hash(input);
}
public static void demoForReturnType() throws Exception {
final byte[] hash1 = HashFunction.ofAlgorithm("SHA1").hash("hello");
final byte[] hash2 = hashInput("hello", HashFunction.ofAlgorithm("SHA1"));
}
//example method that is not at all related to the interface HashFunction
//but still has the same signature of taking a String as input and returning a byte array
public static byte[] md5(final String input) throws Exception {
return MessageDigest.getInstance("MD5").digest(input.getBytes());
}
//method reference
public static void demoForMethodReference() throws Exception {
final HashFunction function = P2_FunctionalInterfacesFirstClassMembers::md5;//double colon for method reference
}
}
|
Fix relativ import of package | # -*- coding: utf-8 -*-
'''
Copyright (c) 2018 by Tobias Houska
This file is part of Statistical Parameter Optimization Tool for Python(SPOTPY).
:author: Tobias Houska, Philipp Kraft
'''
import unittest
import matplotlib
matplotlib.use('Agg')
import sys
if sys.version_info >= (3, 5) and matplotlib.__version__ >= '2.1':
sys.path.append(".")
try:
import spotpy
except ImportError:
import spotpy
from spotpy.gui.mpl import GUI
from .test_setup_parameters import SpotSetupMixedParameterFunction as Setup
class TestGuiMpl(unittest.TestCase):
def test_setup(self):
setup = Setup()
with GUI(setup) as gui:
self.assertTrue(hasattr(gui, 'setup'))
def test_sliders(self):
setup = Setup()
with GUI(setup) as gui:
self.assertEqual(len(gui.sliders), 4)
def test_clear(self):
setup = Setup()
with GUI(setup) as gui:
gui.clear()
self.assertEqual(len(gui.lines), 1)
def test_run(self):
setup = Setup()
with GUI(setup) as gui:
gui.clear()
gui.run()
self.assertEqual(len(gui.lines), 2)
if __name__ == '__main__':
unittest.main()
| # -*- coding: utf-8 -*-
'''
Copyright (c) 2018 by Tobias Houska
This file is part of Statistical Parameter Optimization Tool for Python(SPOTPY).
:author: Tobias Houska, Philipp Kraft
'''
import unittest
import matplotlib
matplotlib.use('Agg')
import sys
if sys.version_info >= (3, 5) and matplotlib.__version__ >= '2.1':
sys.path.append(".")
try:
import spotpy
except ImportError:
import spotpy
from spotpy.gui.mpl import GUI
from test_setup_parameters import SpotSetupMixedParameterFunction as Setup
class TestGuiMpl(unittest.TestCase):
def test_setup(self):
setup = Setup()
with GUI(setup) as gui:
self.assertTrue(hasattr(gui, 'setup'))
def test_sliders(self):
setup = Setup()
with GUI(setup) as gui:
self.assertEqual(len(gui.sliders), 4)
def test_clear(self):
setup = Setup()
with GUI(setup) as gui:
gui.clear()
self.assertEqual(len(gui.lines), 1)
def test_run(self):
setup = Setup()
with GUI(setup) as gui:
gui.clear()
gui.run()
self.assertEqual(len(gui.lines), 2)
if __name__ == '__main__':
unittest.main()
|
Update text references in the console version. | #!/usr/bin/python2
from __future__ import print_function
from board import Board
import sys
class GameOfLifeConsole:
def __init__(self):
print('Welcome to MaGol')
print('What board size do you want?')
board_size = raw_input()
while not board_size.isdigit():
print('Please enter a number for the board size:')
board_size = raw_input()
self.board = Board(int(board_size))
self.board.randomise_grid()
self.mainloop()
def mainloop(self):
while True:
print('How many turns do you want to run (0 to stop)?')
num_turns = raw_input()
while not num_turns.isdigit():
print('Please enter a number for the amount of turns:')
num_turns = raw_input()
num_turns = int(num_turns)
if num_turns <= 0:
print('Goodbye')
sys.exit()
self.board.run_turns(num_turns)
for row in self.board.grid:
for col in row:
if col:
print('0', end='')
else:
print('1', end='')
print()
GameOfLifeConsole()
| #!/usr/bin/python2
from __future__ import print_function
from board import Board
import sys
class GameOfLifeConsole:
def __init__(self):
print('Welcome to PyGol')
print('What board size do you want?')
board_size = raw_input()
while not board_size.isdigit():
print('Please enter a number for the board size:')
board_size = raw_input()
self.board = Board(int(board_size))
self.board.randomise_grid()
self.mainloop()
def mainloop(self):
while True:
print('How many turns do you want to run (0 to stop)?')
num_turns = raw_input()
while not num_turns.isdigit():
print('Please enter a number for the amount of turns:')
num_turns = raw_input()
num_turns = int(num_turns)
if num_turns <= 0:
print('Goodbye')
sys.exit()
self.board.run_turns(num_turns)
for row in self.board.grid:
for col in row:
if col:
print('0', end='')
else:
print('1', end='')
print()
GameOfLifeConsole()
|
[FIX] product_management_group: Allow superuser to skip that restriction on products
closes ingadhoc/product#409
Signed-off-by: Nicolas Mac Rouillon <[email protected]> | ##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from odoo import api, models, tools, exceptions, _
class IrModelAccess(models.Model):
_inherit = 'ir.model.access'
@api.model
@tools.ormcache_context(
'self._uid', 'model', 'mode', 'raise_exception', keys=('lang',))
def check(
self, model, mode='read', raise_exception=True):
if isinstance(model, models.BaseModel):
assert model._name == 'ir.model', 'Invalid model object'
model_name = model.model
else:
model_name = model
# we need to use this flag to know when the operation is from this modules
if self._context.get('sale_quotation_products') or self._context.get('purchase_quotation_products') or self.env.is_superuser():
return True
if mode != 'read' and model_name in [
'product.template', 'product.product']:
if self.env['res.users'].has_group(
'product_management_group.group_products_management'):
return True
elif raise_exception:
raise exceptions.AccessError(_(
"Sorry, you are not allowed to manage products."
"Only users with 'Products Management' level are currently"
" allowed to do that"))
else:
return False
return super(IrModelAccess, self).check(
model, mode=mode, raise_exception=raise_exception)
| ##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from odoo import api, models, tools, exceptions, _
class IrModelAccess(models.Model):
_inherit = 'ir.model.access'
@api.model
@tools.ormcache_context(
'self._uid', 'model', 'mode', 'raise_exception', keys=('lang',))
def check(
self, model, mode='read', raise_exception=True):
if isinstance(model, models.BaseModel):
assert model._name == 'ir.model', 'Invalid model object'
model_name = model.model
else:
model_name = model
# we need to use this flag to know when the operation is from this modules
if self._context.get('sale_quotation_products') or self._context.get('purchase_quotation_products'):
return True
if mode != 'read' and model_name in [
'product.template', 'product.product']:
if self.env['res.users'].has_group(
'product_management_group.group_products_management'):
return True
elif raise_exception:
raise exceptions.AccessError(_(
"Sorry, you are not allowed to manage products."
"Only users with 'Products Management' level are currently"
" allowed to do that"))
else:
return False
return super(IrModelAccess, self).check(
model, mode=mode, raise_exception=raise_exception)
|
Document new {{import:file.txt}} command for Anki card definitions. | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v2.0. If a copy of the MPL was not distributed with this
# file, you can obtain one at http://mozilla.org/MPL/2.0/.
import os
import re
import yaml
import lib.genanki.genanki as genanki
class Anki:
def generate_id():
"""Generate a 32-bit ID useful for Anki."""
return random.randrange(1 << 30, 1 << 31)
# return datetime.now().timestamp()
def import_card_definitions(self, yaml_filepath):
"""Import card definitions from YAML file.
Adds a Anki-like {{import:file.txt}} file import command which
works similar to the #include preprocessor command in C-like
languages, directly replacing the command with text from the
import file.
"""
path = os.path.dirname(yaml_filepath) + '/'
with open(yaml_filepath, 'r') as f:
cards = f.read()
cards = yaml.load(cards)
for subject, model in cards.items():
for template in model['templates']:
for fmt in ('qfmt', 'afmt'):
with open(path + template[fmt], 'r') as f:
lines = f.readlines()
temp = ''
for line in lines:
match = re.match('\s*{{import:(.*)}}', line)
if match:
with open(path + match.group(1), 'r') as f:
line = f.read()
temp += line
template[fmt] = temp
return cards
| # This Source Code Form is subject to the terms of the Mozilla Public
# License, v2.0. If a copy of the MPL was not distributed with this
# file, you can obtain one at http://mozilla.org/MPL/2.0/.
import os
import re
import yaml
import lib.genanki.genanki as genanki
class Anki:
def generate_id():
"""Generate a 32-bit ID useful for Anki."""
return random.randrange(1 << 30, 1 << 31)
# return datetime.now().timestamp()
def import_card_definitions(self, yaml_filepath):
"""Import card definitions from YAML file."""
path = os.path.dirname(yaml_filepath) + '/'
with open(yaml_filepath, 'r') as f:
cards = f.read()
cards = yaml.load(cards)
for subject, model in cards.items():
for template in model['templates']:
for fmt in ('qfmt', 'afmt'):
with open(path + template[fmt], 'r') as f:
lines = f.readlines()
temp = ''
for line in lines:
match = re.match('\s*{{import:(.*)}}', line)
if match:
with open(path + match.group(1), 'r') as f:
line = f.read()
temp += line
template[fmt] = temp
return cards
|
Tweak integration timeout test to match gtest |
class ServiceTests(object):
def test_bash(self):
return self.check(
input='bc -q\n1+1\nquit()',
type='org.tyrion.service.bash',
output='2',
error='',
code='0',
)
def test_python(self):
return self.check(
input='print 1+1',
type='org.tyrion.service.python',
output='2',
error='',
code='0',
)
def test_ruby(self):
return self.check(
input='puts 1+1',
type='org.tyrion.service.ruby',
output='2',
error='',
code='0',
)
def test_timeout_error(self):
return self.check(
input='echo test\nsleep 10',
type='org.tyrion.service.bash',
output='test',
error=None,
code='15',
timeout=1,
)
|
class ServiceTests(object):
def test_bash(self):
return self.check(
input='bc -q\n1+1\nquit()',
type='org.tyrion.service.bash',
output='2',
error='',
code='0',
)
def test_python(self):
return self.check(
input='print 1+1',
type='org.tyrion.service.python',
output='2',
error='',
code='0',
)
def test_ruby(self):
return self.check(
input='puts 1+1',
type='org.tyrion.service.ruby',
output='2',
error='',
code='0',
)
def test_timeout_error(self):
return self.check(
input='sleep 10',
type='org.tyrion.service.bash',
output='',
error=None,
code='15',
timeout=2,
)
|
Add --group option to CLI | import argparse
import sys
def main(raw_args=sys.argv[1:]):
"""
A tool to automatically request, renew and distribute Let's Encrypt
certificates for apps running on Marathon and served by marathon-lb.
"""
parser = argparse.ArgumentParser(
description='Automatically manage ACME certificates for Marathon apps')
parser.add_argument('-a', '--acme',
help='The address for the ACME Directory Resource '
'(default: %(default)s)',
default=(
'https://acme-v01.api.letsencrypt.org/directory'))
parser.add_argument('-m', '--marathon', nargs='+',
help='The address for the Marathon HTTP API (default: '
'%(default)s)',
default='http://marathon.mesos:8080')
parser.add_argument('-l', '--lb', nargs='+',
help='The address for the marathon-lb HTTP API '
'(default: %(default)s)',
default='http://marathon-lb.marathon.mesos:9090')
parser.add_argument('-g', '--group',
help='The marathon-lb group to issue certificates for '
'(default: %(default)s)',
default='external')
parser.add_argument('storage-dir',
help='Path to directory for storing certificates')
args = parser.parse_args(raw_args) # noqa
if __name__ == '__main__':
main()
| import argparse
import sys
def main(raw_args=sys.argv[1:]):
"""
A tool to automatically request, renew and distribute Let's Encrypt
certificates for apps running on Marathon and served by marathon-lb.
"""
parser = argparse.ArgumentParser(
description='Automatically manage ACME certificates for Marathon apps')
parser.add_argument('-a', '--acme',
help='The address for the ACME Directory Resource '
'(default: %(default)s)',
default=(
'https://acme-v01.api.letsencrypt.org/directory'))
parser.add_argument('-m', '--marathon', nargs='+',
help='The address for the Marathon HTTP API (default: '
'%(default)s)',
default='http://marathon.mesos:8080')
parser.add_argument('-l', '--lb', nargs='+',
help='The address for the marathon-lb HTTP API '
'(default: %(default)s)',
default='http://marathon-lb.marathon.mesos:9090')
parser.add_argument('storage-dir',
help='Path to directory for storing certificates')
args = parser.parse_args(raw_args) # noqa
if __name__ == '__main__':
main()
|
Add test to check registration button exists on login page | <?php
namespace AppBundle\Tests\Functional\Controller;
class SecurityControllerTest extends \AppBundle\Tests\Functional\TestCase
{
public function testRedirectForAnonymous()
{
$client = static::createClient();
$client->request('GET', '/');
$this->assertTrue($client->getResponse()->isRedirect('http://localhost/login'));
}
public function testLogin()
{
$client = static::createClient();
$crawler = $client->request('GET', '/login');
$form = $crawler->filter('button')->form([
'_username' => 'admin',
'_password' => 'secret',
]);
$client->submit($form);
$this->assertTrue($client->getResponse()->isRedirect('http://localhost/'));
}
public function testLoginInvalidCredentials()
{
$client = static::createClient();
$crawler = $client->request('GET', '/login');
$form = $crawler->filter('button')->form([
'_username' => 'failed',
'_password' => 'failed',
]);
$client->submit($form);
$crawler = $client->followRedirect();
$this->assertEquals('Invalid credentials.', $crawler->filter('div.login > div')->html());
}
public function testLoginRegistrationButton()
{
$client = static::createClient();
$crawler = $client->request('GET', '/login');
$link = $crawler->filter('a[href="/sign_up"]')->link();
$crawler = $client->click($link);
$this->assertEquals('Sign up', $crawler->filter('title')->html());
}
}
| <?php
namespace AppBundle\Tests\Functional\Controller;
class SecurityControllerTest extends \AppBundle\Tests\Functional\TestCase
{
public function testRedirectForAnonymous()
{
$client = static::createClient();
$client->request('GET', '/');
$this->assertTrue($client->getResponse()->isRedirect('http://localhost/login'));
}
public function testLogin()
{
$client = static::createClient();
$client->request('GET', '/');
$this->assertTrue($client->getResponse()->isRedirect('http://localhost/login'));
$crawler = $client->followRedirect();
$form = $crawler->filter('button')->form([
'_username' => 'admin',
'_password' => 'secret',
]);
$client->submit($form);
$this->assertTrue($client->getResponse()->isRedirect('http://localhost/'));
}
public function testLoginFailed()
{
$client = static::createClient();
$client->request('GET', '/');
$this->assertTrue($client->getResponse()->isRedirect('http://localhost/login'));
$crawler = $client->followRedirect();
$form = $crawler->filter('button')->form([
'_username' => 'failed',
'_password' => 'failed',
]);
$client->submit($form);
$crawler = $client->followRedirect();
$this->assertEquals(
'Invalid credentials.',
$crawler->filter('div.login > div')->extract(['_text'])[0]
);
}
}
|
Revert "fix(client: spec): change jasmine timeout from 120 to 180 s"
This reverts commit a5f8f6d08b31d20dfec1cd89ada0b1b0b23c5b36. | 'use strict';
//var ScreenShotReporter = require('protractor-screenshot-reporter');
exports.config = {
allScriptsTimeout: 30000,
baseUrl: 'http://localhost:9090',
params: {
baseBackendUrl: 'http://localhost:5000/api/',
username: 'admin',
password: 'admin'
},
specs: ['spec/setup.js', 'spec/**/*[Ss]pec.js'],
capabilities: {
browserName: 'chrome',
chromeOptions: {
args: ['--no-sandbox']
}
},
restartBrowserBetweenTests: process.env.bamboo_working_directory || false, // any bamboo env var will do
directConnect: true,
framework: 'jasmine',
jasmineNodeOpts: {
showColors: true,
isVerbose: true,
includeStackTrace: true,
defaultTimeoutInterval: 120000
},
/* global jasmine */
onPrepare: function() {
/*
jasmine.getEnv().addReporter(new ScreenShotReporter({
baseDirectory: './screenshots',
pathBuilder:
function pathBuilder(spec, descriptions, results, capabilities) {
return results.passed() + '_' + descriptions.reverse().join('-');
},
takeScreenShotsOnlyForFailedSpecs: true
}));
*/
require('jasmine-reporters');
jasmine.getEnv().addReporter(
new jasmine.JUnitXmlReporter('e2e-test-results', true, true)
);
}
};
| 'use strict';
//var ScreenShotReporter = require('protractor-screenshot-reporter');
exports.config = {
allScriptsTimeout: 30000,
baseUrl: 'http://localhost:9090',
params: {
baseBackendUrl: 'http://localhost:5000/api/',
username: 'admin',
password: 'admin'
},
specs: ['spec/setup.js', 'spec/**/*[Ss]pec.js'],
capabilities: {
browserName: 'chrome',
chromeOptions: {
args: ['--no-sandbox']
}
},
restartBrowserBetweenTests: process.env.bamboo_working_directory || false, // any bamboo env var will do
directConnect: true,
framework: 'jasmine',
jasmineNodeOpts: {
showColors: true,
isVerbose: true,
includeStackTrace: true,
defaultTimeoutInterval: 180000
},
/* global jasmine */
onPrepare: function() {
/*
jasmine.getEnv().addReporter(new ScreenShotReporter({
baseDirectory: './screenshots',
pathBuilder:
function pathBuilder(spec, descriptions, results, capabilities) {
return results.passed() + '_' + descriptions.reverse().join('-');
},
takeScreenShotsOnlyForFailedSpecs: true
}));
*/
require('jasmine-reporters');
jasmine.getEnv().addReporter(
new jasmine.JUnitXmlReporter('e2e-test-results', true, true)
);
}
};
|
Use app logging instead of celery | from datetime import datetime
from flask import current_app
from changes.config import db, queue
from changes.models import Repository
def sync_repo(repo_id):
repo = Repository.query.get(repo_id)
if not repo:
return
vcs = repo.get_vcs()
if vcs is None:
return
repo.last_update_attempt = datetime.utcnow()
db.session.add(repo)
db.session.commit()
try:
if vcs.exists():
vcs.update()
else:
vcs.clone()
# TODO(dcramer): this doesnt scrape everything, and really we wouldn't
# want to do this all in a single job so we should split this into a
# backfill task
might_have_more = True
parent = None
while might_have_more:
might_have_more = False
for commit in vcs.log(parent=parent):
revision, created = commit.save(repo)
db.session.commit()
if not created:
break
might_have_more = True
parent = commit.id
repo.last_update = datetime.utcnow()
db.session.add(repo)
db.session.commit()
queue.delay('sync_repo', kwargs={
'repo_id': repo_id
}, countdown=15)
except Exception as exc:
# should we actually use retry support here?
current_app.logger.exception('Failed to sync repository %s', repo_id)
raise queue.retry('sync_repo', kwargs={
'repo_id': repo_id,
}, exc=exc, countdown=120)
| from datetime import datetime
from changes.config import db, queue
from changes.models import Repository
def sync_repo(repo_id):
repo = Repository.query.get(repo_id)
if not repo:
return
vcs = repo.get_vcs()
if vcs is None:
return
repo.last_update_attempt = datetime.utcnow()
db.session.add(repo)
db.session.commit()
try:
if vcs.exists():
vcs.update()
else:
vcs.clone()
# TODO(dcramer): this doesnt scrape everything, and really we wouldn't
# want to do this all in a single job so we should split this into a
# backfill task
might_have_more = True
parent = None
while might_have_more:
might_have_more = False
for commit in vcs.log(parent=parent):
revision, created = commit.save(repo)
db.session.commit()
if not created:
break
might_have_more = True
parent = commit.id
repo.last_update = datetime.utcnow()
db.session.add(repo)
db.session.commit()
queue.delay('sync_repo', kwargs={
'repo_id': repo_id
}, countdown=15)
except Exception as exc:
# should we actually use retry support here?
raise queue.retry('sync_repo', kwargs={
'repo_id': repo_id,
}, exc=exc, countdown=120)
|
Make tooltip's container the page's body | import Ember from 'ember';
export default Ember.Mixin.create({
/**
* Enables the tooltip functionality, based on component's `title` attribute
* @method enableTooltip
*/
enableTooltip: function () {
var popoverContent = this.get( 'popover' );
var title = this.get( 'title' );
if ( !popoverContent && !title ) {
return;
}
if ( this.get( 'isPopover' )) {
this.$().popover( 'destroy' );
this.set( 'isPopover', false );
}
if ( this.get( 'isTooltip' )) {
this.$().tooltip( 'destroy' );
this.set( 'isTooltip', false );
}
if ( popoverContent ) {
this.set( 'data-toggle', 'popover' );
this.$().popover({
content: popoverContent,
placement: 'top'
});
this.set( 'isPopover', false );
} else if ( title ) {
this.set( 'data-toggle', 'tooltip' );
this.$().tooltip({
container: 'body',
title: title
});
this.set( 'isTooltip', true );
}
}.observes( 'popover', 'title' ).on( 'didInsertElement' ),
/**
* Whether the component has been set up as a popover
* @property {boolean} isPopover
* @default false
*/
isPopover: false,
/**
* Whether the component has been set up as a tooltip
* @property {boolean} isTooltip
* @default false
*/
isTooltip: false
}); | import Ember from 'ember';
export default Ember.Mixin.create({
/**
* Enables the tooltip functionality, based on component's `title` attribute
* @method enableTooltip
*/
enableTooltip: function () {
var popoverContent = this.get( 'popover' );
var title = this.get( 'title' );
if ( !popoverContent && !title ) {
return;
}
if ( this.get( 'isPopover' )) {
this.$().popover( 'destroy' );
this.set( 'isPopover', false );
}
if ( this.get( 'isTooltip' )) {
this.$().tooltip( 'destroy' );
this.set( 'isTooltip', false );
}
if ( popoverContent ) {
this.set( 'data-toggle', 'popover' );
this.$().popover({
content: popoverContent,
placement: 'top'
});
this.set( 'isPopover', false );
} else if ( title ) {
this.set( 'data-toggle', 'tooltip' );
this.$().tooltip({ title: title });
this.set( 'isTooltip', true );
}
}.observes( 'popover', 'title' ).on( 'didInsertElement' ),
/**
* Whether the component has been set up as a popover
* @property {boolean} isPopover
* @default false
*/
isPopover: false,
/**
* Whether the component has been set up as a tooltip
* @property {boolean} isTooltip
* @default false
*/
isTooltip: false
}); |
Add correct $_SESSION[user] variable to Projects Test Class | <?php
namespace fennecweb;
class ProjectsTest extends \PHPUnit_Framework_TestCase
{
const NICKNAME = 'listingProjectsTestUser';
const USERID = 'listingProjectsTestUser';
const PROVIDER = 'listingProjectsTestUser';
public function testExecute()
{
//Test for error returned by user is not logged in
list($service) = WebService::factory('listing/Projects');
$results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION)));
$expected = array("error" => \fennecweb\ajax\listing\Projects::ERROR_NOT_LOGGED_IN);
$this->assertEquals($expected, $results);
//Test for correct project
$_SESSION['user'] = array(
'nickname' => ProjectsTest::NICKNAME,
'id' => ProjectsTest::USERID,
'provider' => ProjectsTest::PROVIDER,
'token' => 'listingProjectsTestUserToken'
);
list($service) = WebService::factory('listing/Projects');
$results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION)));
$expected = array(
array(
"This is a Table ID",
"2016-05-17 10:00:52.627236+00",
10,
5
)
);
$this->assertEquals($expected, $results);
}
}
| <?php
namespace fennecweb;
class ProjectsTest extends \PHPUnit_Framework_TestCase
{
const NICKNAME = 'listingProjectsTestUser';
const USERID = 'listingProjectsTestUser';
const PROVIDER = 'listingProjectsTestUser';
public function testExecute()
{
//Test for error returned by user is not logged in
list($service) = WebService::factory('listing/Projects');
$results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION)));
$expected = array("error" => \fennecweb\ajax\listing\Projects::ERROR_NOT_LOGGED_IN);
$this->assertEquals($expected, $results);
//Test for correct project
$_SESSION['user'] = array(
'nickname' => ProjectTest::NICKNAME,
'id' => ProjectTest::USERID,
'provider' => ProjectTest::PROVIDER,
'token' => 'listingProjectsTestUserToken'
);
list($service) = WebService::factory('listing/Projects');
$results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION)));
$expected = array(
array(
"This is a Table ID",
"2016-05-17 10:00:52.627236+00",
10,
5
)
);
$this->assertEquals($expected, $results);
}
}
|
Update config for Symfony 4.2 change | <?php
namespace Gos\Bundle\PubSubRouterBundle\DependencyInjection;
use Gos\Bundle\PubSubRouterBundle\Generator\Generator;
use Gos\Bundle\PubSubRouterBundle\Matcher\Matcher;
use Gos\Bundle\PubSubRouterBundle\Router\Router;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* @author Johann Saunier <[email protected]>
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder('gos_pubsub_router');
if (method_exists($treeBuilder, 'getRootNode')) {
$rootNode = $treeBuilder->getRootNode();
} else {
// BC layer for symfony/config 4.1 and older
$rootNode = $treeBuilder->root('gos_pubsub_router');
$rootNode
->addDefaultsIfNotSet()
->children()
->scalarNode('matcher_class')->defaultValue(Matcher::class)->end()
->scalarNode('generator_class')->defaultValue(Generator::class)->end()
->scalarNode('router_class')->defaultValue(Router::class)->end()
->arrayNode('routers')
->useAttributeAsKey('name')
->requiresAtLeastOneElement()
->prototype('array')
->children()
->arrayNode('resources')
->prototype('scalar')->end()
->end()
->end()
->end()
->end()
->end()
->end();
return $treeBuilder;
}
}
| <?php
namespace Gos\Bundle\PubSubRouterBundle\DependencyInjection;
use Gos\Bundle\PubSubRouterBundle\Generator\Generator;
use Gos\Bundle\PubSubRouterBundle\Matcher\Matcher;
use Gos\Bundle\PubSubRouterBundle\Router\Router;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* @author Johann Saunier <[email protected]>
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('gos_pubsub_router');
$rootNode
->addDefaultsIfNotSet()
->children()
->scalarNode('matcher_class')->defaultValue(Matcher::class)->end()
->scalarNode('generator_class')->defaultValue(Generator::class)->end()
->scalarNode('router_class')->defaultValue(Router::class)->end()
->arrayNode('routers')
->useAttributeAsKey('name')
->requiresAtLeastOneElement()
->prototype('array')
->children()
->arrayNode('resources')
->prototype('scalar')->end()
->end()
->end()
->end()
->end()
->end()
->end();
return $treeBuilder;
}
}
|
Add audio/video support and bail on findings | from django.core.management.base import BaseCommand
from corehq.apps.domain.models import Domain
import csv
class Command(BaseCommand):
help = 'Find domains with secure submissions and image questions'
def check_domain(self, domain, csv_writer):
if domain.secure_submissions:
for app in domain.full_applications(include_builds=False):
for module in app.modules:
for form in module.forms:
for question in form.get_questions(app.langs):
if question['type'] in ('Image', 'Audio', 'Video'):
csv_writer.writerow([
domain.name,
app.name,
domain.creating_user
])
return
def handle(self, *args, **options):
with open('domain_results.csv', 'wb+') as csvfile:
csv_writer = csv.writer(
csvfile,
delimiter=',',
quotechar='|',
quoting=csv.QUOTE_MINIMAL
)
csv_writer.writerow(['domain', 'app', 'domain_creator'])
for domain in Domain.get_all(include_docs=True):
self.check_domain(domain, csv_writer)
| from django.core.management.base import BaseCommand
from corehq.apps.domain.models import Domain
import csv
class Command(BaseCommand):
help = 'Find domains with secure submissions and image questions'
def handle(self, *args, **options):
with open('domain_results.csv', 'wb+') as csvfile:
csv_writer = csv.writer(
csvfile,
delimiter=',',
quotechar='|',
quoting=csv.QUOTE_MINIMAL
)
csv_writer.writerow(['domain', 'app', 'domain_creator'])
for domain in Domain.get_all(include_docs=True):
if domain.secure_submissions:
for app in domain.full_applications(include_builds=False):
for module in app.modules:
for form in module.forms:
for question in form.get_questions(app.langs):
if question['type'] == 'Image':
csv_writer.writerow([
domain.name,
app.name,
domain.creating_user
])
|
Include uncategorised spending in overview pie chart
Also, only show last 120 days | from datetime import date, timedelta
from django.db.models import Sum
from django.views.generic import TemplateView
from djofx.forms import OFXForm
from djofx.views.base import PageTitleMixin, UserRequiredMixin
from djofx import models
from operator import itemgetter
class HomePageView(PageTitleMixin, UserRequiredMixin, TemplateView):
template_name = "djofx/home.html"
def get_context_data(self, **kwargs):
context = super(HomePageView, self).get_context_data(**kwargs)
context['accounts'] = models.Account.objects.filter(
owner=self.request.user
)
context['form'] = OFXForm()
cutoff = date.today() - timedelta(days=120)
uncategorised_breakdown = models.Transaction.objects.filter(
amount__lt=0,
transaction_category__isnull=True,
date__gte=cutoff
).aggregate(
total=Sum('amount')
)
breakdown = models.Transaction.objects.filter(
amount__lt=0,
transaction_category__is_void=False,
date__gte=cutoff
).values(
'transaction_category__pk',
'transaction_category__name'
).annotate(
total=Sum('amount')
).order_by('-total')
context['breakdown'] = [
(
abs(item['total']),
item['transaction_category__pk'],
item['transaction_category__name']
)
for item in breakdown
]
context['breakdown'].append(
(
uncategorised_breakdown['total'] * -1,
0,
'Uncategorised'
)
)
context['breakdown'] = sorted(context['breakdown'],
key=itemgetter(0),
reverse=True)
return context
| from django.db.models import Sum
from django.views.generic import TemplateView
from djofx.forms import OFXForm
from djofx.views.base import PageTitleMixin, UserRequiredMixin
from djofx import models
class HomePageView(PageTitleMixin, UserRequiredMixin, TemplateView):
template_name = "djofx/home.html"
def get_context_data(self, **kwargs):
context = super(HomePageView, self).get_context_data(**kwargs)
context['accounts'] = models.Account.objects.filter(
owner=self.request.user
)
context['form'] = OFXForm()
breakdown = models.Transaction.objects.filter(
amount__lt=0,
transaction_category__is_void=False
).values(
'transaction_category__pk',
'transaction_category__name'
).annotate(
total=Sum('amount')
).order_by('-total')
context['breakdown'] = [
(
abs(item['total']),
item['transaction_category__pk'],
item['transaction_category__name']
)
for item in breakdown
]
return context
|
Add edit icon for password fields | /*eslint-disable no-unused-vars */
import React from "react";
/*eslint-enable no-unused-vars */
import FieldInput from "./FieldInput";
import IconEdit from "./icons/IconEdit";
const DEFAULT_PASSWORD_TEXT = "••••••";
const METHODS_TO_BIND = ["handleOnFocus"];
export default class FieldPassword extends FieldInput {
constructor() {
super();
METHODS_TO_BIND.forEach((method) => {
this[method] = this[method].bind(this);
});
}
handleOnFocus(event) {
if (!this.focused) {
this.focused = true;
this.forceUpdate();
}
this.props.handleEvent("focus", this.props.name, event);
}
getInputElement(attributes) {
attributes = this.bindEvents(attributes, this.props.handleEvent);
attributes.onFocus = this.handleOnFocus;
let startValue = DEFAULT_PASSWORD_TEXT;
if (this.focused) {
startValue = attributes.startValue;
}
if (this.isEditing() || this.props.writeType === "input") {
return (
<input
ref="inputElement"
className={this.props.inputClass}
{...attributes}
value={startValue} />
);
}
return (
<span
ref="inputElement"
{...attributes}
className={this.props.readClass}
onClick={attributes.onFocus}>
{attributes.defaultPasswordValue || DEFAULT_PASSWORD_TEXT}
<IconEdit />
</span>
);
}
}
| /*eslint-disable no-unused-vars */
import React from "react";
/*eslint-enable no-unused-vars */
import FieldInput from "./FieldInput";
const DEFAULT_PASSWORD_TEXT = "••••••";
const METHODS_TO_BIND = ["handleOnFocus"];
export default class FieldPassword extends FieldInput {
constructor() {
super();
METHODS_TO_BIND.forEach((method) => {
this[method] = this[method].bind(this);
});
}
handleOnFocus(event) {
if (!this.focused) {
this.focused = true;
this.forceUpdate();
}
this.props.handleEvent("focus", this.props.name, event);
}
getInputElement(attributes) {
attributes = this.bindEvents(attributes, this.props.handleEvent);
attributes.onFocus = this.handleOnFocus;
let startValue = DEFAULT_PASSWORD_TEXT;
if (this.focused) {
startValue = attributes.startValue;
}
if (this.isEditing() || this.props.writeType === "input") {
return (
<input
ref="inputElement"
className={this.props.inputClass}
{...attributes}
value={startValue} />
);
}
return (
<span
ref="inputElement"
{...attributes}
className={this.props.readClass}
onClick={attributes.onFocus}>
{attributes.defaultPasswordValue || DEFAULT_PASSWORD_TEXT}
</span>
);
}
}
|
Define mocha as testing framework.
We don't use jasmine that is the wallaby default. | module.exports = function (wallaby) {
'use strict'
return {
testFramework: 'mocha',
files: [
{pattern: 'node_modules/systemjs/dist/system.js', instrument: false},
{pattern: 'node_modules/es6-shim/es6-shim.js', instrument: false},
{pattern: 'src/jspm.conf.js', instrument: false},
{pattern: 'src/app/**/*.ts', load: false},
{pattern: 'test/stubs.ts', load: false}
],
tests: [
{pattern: 'test/**/*.spec.ts', load: false}
],
// telling wallaby to serve jspm_packages project folder
// as is from wallaby web server
middleware: (app, express) => {
app.use('/node_modules/systemjs/dist',
express.static('node_modules/systemjs/dist'))
app.use('/jspm_packages',
express.static('src/jspm_packages'))
},
setup: function (wallaby) {
// Preventing wallaby from starting the test run
wallaby.delayStart()
var promises = []
for (var i = 0, len = wallaby.tests.length; i < len; i++) {
promises.push(System['import'](wallaby.tests[i]))
}
// starting wallaby test run when everything required is loaded
Promise.all(promises).then(function () {
wallaby.start()
}).catch(function (e) { setTimeout(function () { throw e }, 0) })
}
}
}
| module.exports = function (wallaby) {
'use strict'
return {
files: [
{pattern: 'node_modules/systemjs/dist/system.js', instrument: false},
{pattern: 'node_modules/es6-shim/es6-shim.js', instrument: false},
{pattern: 'src/jspm.conf.js', instrument: false},
{pattern: 'src/app/**/*.ts', load: false},
{pattern: 'test/stubs.ts', load: false}
],
tests: [
{pattern: 'test/**/*.spec.ts', load: false}
],
// telling wallaby to serve jspm_packages project folder
// as is from wallaby web server
middleware: (app, express) => {
app.use('/node_modules/systemjs/dist',
express.static('node_modules/systemjs/dist'))
app.use('/jspm_packages',
express.static('src/jspm_packages'))
},
setup: function (wallaby) {
// Preventing wallaby from starting the test run
wallaby.delayStart()
var promises = []
for (var i = 0, len = wallaby.tests.length; i < len; i++) {
promises.push(System['import'](wallaby.tests[i]))
}
// starting wallaby test run when everything required is loaded
Promise.all(promises).then(function () {
wallaby.start()
}).catch(function (e) { setTimeout(function () { throw e }, 0) })
}
}
}
|
Update status results in React app | import React, { Component } from 'react';
class IssueList extends Component {
constructor() {
super();
this.renderIssue = this.renderIssue.bind(this);
}
renderIssue(issue) {
return (
<div className="col-2" key={issue.key}>
<div className={"card card-inverse issue-card mt-3 " + this.cardStyle(issue)}>
<div className="card-block">
<h4 className="card-title">{issue.key}</h4>
<h6 className="card-subtitle">{issue.title}</h6>
</div>
<div className="card-footer text-muted">
{issue.type} {issue.state}
</div>
</div>
</div>
);
}
cardStyle(issue) {
if (issue.status) {
switch(issue.status.result){
case 'SUCCESS':
return 'card-success';
case 'RUNNING':
return 'card-info';
case 'FAILURE':
return 'card-danger';
}
}
return "card-outline-secondary";
}
render() {
return (
<div className="row">
{this.props.issues.map(this.renderIssue)}
</div>
)
}
}
export default IssueList;
| import React, { Component } from 'react';
class IssueList extends Component {
constructor() {
super();
this.renderIssue = this.renderIssue.bind(this);
}
renderIssue(issue) {
return (
<div className="col-2" key={issue.key}>
<div className={"card card-inverse issue-card mt-3 " + this.cardStyle(issue)}>
<div className="card-block">
<h4 className="card-title">{issue.key}</h4>
<h6 className="card-subtitle">{issue.title}</h6>
</div>
<div className="card-footer text-muted">
{issue.type} {issue.state}
</div>
</div>
</div>
);
}
cardStyle(issue) {
if (issue.status) {
switch(issue.status.result){
case 'SUCCESS':
return 'card-success';
case 'RUNNING':
return 'card-info';
case 'ERROR':
return 'card-danger';
}
}
return "card-outline-secondary";
}
render() {
return (
<div className="row">
{this.props.issues.map(this.renderIssue)}
</div>
)
}
}
export default IssueList;
|
Move flush logic into close | from __future__ import absolute_import
from tempfile import NamedTemporaryFile
class LogBuffer(object):
def __init__(self, chunk_size=4096):
self.chunk_size = chunk_size
self.fp = NamedTemporaryFile()
def fileno(self):
return self.fp.fileno()
def write(self, chunk):
self.fp.write(chunk)
self.fp.flush()
def close(self, force=False):
self.fp.flush()
if force:
self.fp.close()
def flush(self):
self.fp.flush()
def iter_chunks(self):
chunk_size = self.chunk_size
result = ''
offset = 0
with open(self.fp.name) as fp:
for chunk in fp:
result += chunk
while len(result) >= chunk_size:
newline_pos = result.rfind('\n', 0, chunk_size)
if newline_pos == -1:
newline_pos = chunk_size
else:
newline_pos += 1
yield (offset, result[:newline_pos])
offset += newline_pos
result = result[newline_pos:]
if result:
yield(offset, result)
self.close(True)
| from __future__ import absolute_import
from tempfile import NamedTemporaryFile
class LogBuffer(object):
def __init__(self, chunk_size=4096):
self.chunk_size = chunk_size
self.fp = NamedTemporaryFile()
def fileno(self):
return self.fp.fileno()
def write(self, chunk):
self.fp.write(chunk)
self.fp.flush()
def close(self, force=False):
if force:
self.fp.close()
def flush(self):
self.fp.flush()
def iter_chunks(self):
self.flush()
chunk_size = self.chunk_size
result = ''
offset = 0
with open(self.fp.name) as fp:
for chunk in fp:
result += chunk
while len(result) >= chunk_size:
newline_pos = result.rfind('\n', 0, chunk_size)
if newline_pos == -1:
newline_pos = chunk_size
else:
newline_pos += 1
yield (offset, result[:newline_pos])
offset += newline_pos
result = result[newline_pos:]
if result:
yield(offset, result)
self.close(True)
|
Fix: Use `active_attachments_pro` instead of `active_comments`. | from django.db import models
import logging
logger = logging.getLogger(__name__)
class FMSProxy(models.Model):
name = models.CharField(max_length=20, unique=True)
def __unicode__(self):
return self.name
def get_assign_payload(report):
creator = report.get_creator()
payload = {
"application": report.contractor.fmsproxy.name.lower(),
"report":{
"id": report.id,
"created_at": report.created.isoformat(),
"modified_at": report.modified.isoformat(),
"category": report.display_category(),
"pdf_url": report.get_pdf_url_pro(),
"address": report.address,
"address_number": report.address_number,
"postal_code": report.postalcode,
"municipality": report.get_address_commune_name(),
"creator": {
"type": "pro" if report.is_pro() else "citizen",
"first_name": creator.first_name,
"last_name": creator.last_name,
"phone": creator.telephone,
"email": creator.email,
},
"comments": [],
},
}
comments = report.active_attachments_pro()
for comment in comments:
payload["report"]["comments"].append({
"created_at": comment.created.isoformat(),
"name": comment.get_display_name(),
"text": comment.text,
})
return payload
| from django.db import models
import logging
logger = logging.getLogger(__name__)
class FMSProxy(models.Model):
name = models.CharField(max_length=20, unique=True)
def __unicode__(self):
return self.name
def get_assign_payload(report):
creator = report.get_creator()
payload = {
"application": report.contractor.fmsproxy.name.lower(),
"report":{
"id": report.id,
"created_at": report.created.isoformat(),
"modified_at": report.modified.isoformat(),
"category": report.display_category(),
"pdf_url": report.get_pdf_url_pro(),
"address": report.address,
"address_number": report.address_number,
"postal_code": report.postalcode,
"municipality": report.get_address_commune_name(),
"creator": {
"type": "pro" if report.is_pro() else "citizen",
"first_name": creator.first_name,
"last_name": creator.last_name,
"phone": creator.telephone,
"email": creator.email,
},
"comments": None,
},
}
comments = report.active_comments()
if comments:
payload["report"]["comments"] = []
for comment in comments:
payload["report"]["comments"].append({
"created_at": comment.created.isoformat(),
"name": comment.get_display_name(),
"text": comment.text,
})
return payload
|
Add Cookiecutter v1.1 to install requirements | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import codecs
from setuptools import setup
def read(fname):
file_path = os.path.join(os.path.dirname(__file__), fname)
return codecs.open(file_path, encoding='utf-8').read()
setup(
name='pytest-cookies',
version='0.1.0',
author='Raphael Pierzina',
author_email='[email protected]',
maintainer='Raphael Pierzina',
maintainer_email='[email protected]',
license='MIT',
url='https://github.com/hackebrot/pytest-cookies',
description='A Pytest plugin for your Cookiecutter templates',
long_description=read('README.rst'),
py_modules=['pytest_cookies'],
install_requires=[
'pytest>=2.8.1',
'cookiecutter>=1.1.0'
],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Topic :: Software Development :: Testing',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python',
'Operating System :: OS Independent',
'License :: OSI Approved :: MIT License',
],
entry_points={
'pytest11': [
'cookies = pytest_cookies',
],
},
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import codecs
from setuptools import setup
def read(fname):
file_path = os.path.join(os.path.dirname(__file__), fname)
return codecs.open(file_path, encoding='utf-8').read()
setup(
name='pytest-cookies',
version='0.1.0',
author='Raphael Pierzina',
author_email='[email protected]',
maintainer='Raphael Pierzina',
maintainer_email='[email protected]',
license='MIT',
url='https://github.com/hackebrot/pytest-cookies',
description='A Pytest plugin for your Cookiecutter templates',
long_description=read('README.rst'),
py_modules=['pytest_cookies'],
install_requires=['pytest>=2.8.1'],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Topic :: Software Development :: Testing',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python',
'Operating System :: OS Independent',
'License :: OSI Approved :: MIT License',
],
entry_points={
'pytest11': [
'cookies = pytest_cookies',
],
},
)
|
tests.features: Fix OS X test skip. | from __future__ import print_function
import sys
import subprocess
import os
@given('a system executable {exe}')
def step_impl(context, exe):
binary = None
if sys.platform.startswith('win'):
try:
binary = subprocess.check_output(["where", exe]).decode('utf8').strip()
except:
pass
else:
try:
binary = subprocess.check_output(["which", exe]).decode('utf8').strip()
except:
pass
if binary is None:
print(
"Skipping scenario", context.scenario,
"(executable %s not found)" % exe,
file = sys.stderr
)
context.scenario.skip("The executable '%s' is not present" % exe)
else:
print(
"Found executable '%s' at '%s'" % (exe, binary),
file = sys.stderr
)
@then('{exe} is a static executable')
def step_impl(ctx, exe):
if sys.platform.lower().startswith('darwin'):
ctx.scenario.skip("Static runtime linking is not supported on OS X")
return
if sys.platform.startswith('win'):
lines = subprocess.check_output(["dumpbin.exe", "/DEPENDENTS", exe]).decode('utf8').split('\r\n')
for line in lines:
if 'msvcrt' in line.lower():
assert False, 'Found MSVCRT: %s' % line
else:
out = subprocess.check_output(["file", exe]).decode('utf8')
assert 'statically linked' in out, "Not a static executable: %s" % out
| from __future__ import print_function
import sys
import subprocess
import os
@given('a system executable {exe}')
def step_impl(context, exe):
binary = None
if sys.platform.startswith('win'):
try:
binary = subprocess.check_output(["where", exe]).decode('utf8').strip()
except:
pass
else:
try:
binary = subprocess.check_output(["which", exe]).decode('utf8').strip()
except:
pass
if binary is None:
print(
"Skipping scenario", context.scenario,
"(executable %s not found)" % exe,
file = sys.stderr
)
context.scenario.skip("The executable '%s' is not present" % exe)
else:
print(
"Found executable '%s' at '%s'" % (exe, binary),
file = sys.stderr
)
@then('{exe} is a static executable')
def step_impl(ctx, exe):
if sys.platform.lower().startswith('darwin'):
context.scenario.skip("Static runtime linking is not supported on OS X")
if sys.platform.startswith('win'):
lines = subprocess.check_output(["dumpbin.exe", "/DEPENDENTS", exe]).decode('utf8').split('\r\n')
for line in lines:
if 'msvcrt' in line.lower():
assert False, 'Found MSVCRT: %s' % line
else:
out = subprocess.check_output(["file", exe]).decode('utf8')
assert 'statically linked' in out, "Not a static executable: %s" % out
|
Add Ctrl-/ shortcut to clear search. | // -------------------------------------------------------------------------- \\
// File: SearchTextView.js \\
// Module: ControlViews \\
// Requires: TextView.js \\
// Author: Neil Jenkins \\
// License: © 2010-2014 FastMail Pty Ltd. MIT Licensed. \\
// -------------------------------------------------------------------------- \\
"use strict";
( function ( NS ) {
var SearchTextView = NS.Class({
Extends: NS.TextView,
type: 'v-SearchText',
draw: function ( layer, Element, el ) {
var children =
SearchTextView.parent.draw.call( this, layer, Element, el );
children.push(
el( 'i.icon.icon-search' ),
new NS.ButtonView({
type: NS.bind( this, 'value', function ( value ) {
return value ?
'v-SearchText-reset v-Button--iconOnly' : 'u-hidden';
}),
icon: 'icon-clear',
positioning: 'absolute',
label: NS.loc( 'Clear Search' ),
shortcut: 'ctrl-/',
target: this,
method: 'reset'
})
);
return children;
},
reset: function () {
this.set( 'value', '' )
.blur();
}
});
NS.SearchTextView = SearchTextView;
}( O ) );
| // -------------------------------------------------------------------------- \\
// File: SearchTextView.js \\
// Module: ControlViews \\
// Requires: TextView.js \\
// Author: Neil Jenkins \\
// License: © 2010-2014 FastMail Pty Ltd. MIT Licensed. \\
// -------------------------------------------------------------------------- \\
"use strict";
( function ( NS ) {
var SearchTextView = NS.Class({
Extends: NS.TextView,
type: 'v-SearchText',
draw: function ( layer, Element, el ) {
var children =
SearchTextView.parent.draw.call( this, layer, Element, el );
children.push(
el( 'i.icon.icon-search' ),
new NS.ButtonView({
type: NS.bind( this, 'value', function ( value ) {
return value ?
'v-SearchText-reset v-Button--iconOnly' : 'u-hidden';
}),
icon: 'icon-clear',
positioning: 'absolute',
label: NS.loc( 'Clear Search' ),
target: this,
method: 'reset'
})
);
return children;
},
reset: function () {
this.set( 'value', '' )
.blur();
}
});
NS.SearchTextView = SearchTextView;
}( O ) );
|
Set pypi development status to Pre-Alpha | from setuptools import find_packages
from setuptools import setup
setup(
name='caravan',
version='0.0.3.dev0',
description='Light python framework for AWS SWF',
long_description=open('README.rst').read(),
keywords='AWS SWF workflow distributed background task',
author='Pior Bastida',
author_email='[email protected]',
url='https://github.com/pior/caravan',
license='MIT',
packages=find_packages(),
zip_safe=False,
install_requires=['boto3'],
extras_require={
'dev': ['zest.releaser[recommended]'],
},
entry_points={
"console_scripts": [
"caravan-decider = caravan.commands.decider:Command.main",
"caravan-start = caravan.commands.start:Command.main",
"caravan-signal = caravan.commands.signal:Command.main",
]
},
classifiers=[
"Development Status :: 2 - Pre-Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Topic :: Internet",
"Programming Language :: Python :: 2.7",
# "Programming Language :: Python :: 3.4",
# "Programming Language :: Python :: 3.5"
],
)
| from setuptools import find_packages
from setuptools import setup
setup(
name='caravan',
version='0.0.3.dev0',
description='Light python framework for AWS SWF',
long_description=open('README.rst').read(),
keywords='AWS SWF workflow distributed background task',
author='Pior Bastida',
author_email='[email protected]',
url='https://github.com/pior/caravan',
license='MIT',
packages=find_packages(),
zip_safe=False,
install_requires=['boto3'],
extras_require={
'dev': ['zest.releaser[recommended]'],
},
entry_points={
"console_scripts": [
"caravan-decider = caravan.commands.decider:Command.main",
"caravan-start = caravan.commands.start:Command.main",
"caravan-signal = caravan.commands.signal:Command.main",
]
},
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Topic :: Internet",
"Programming Language :: Python :: 2.7",
# "Programming Language :: Python :: 3.4",
# "Programming Language :: Python :: 3.5"
],
)
|
Include the official nydus release | #!/usr/bin/python
from setuptools import setup, find_packages
tests_require=[
'nose',
'mock',
]
setup(
name="sunspear",
license='Apache License 2.0',
version="0.1.0a",
description="Activity streams backed by Riak.",
zip_safe=False,
long_description=open('README.rst', 'r').read(),
author="Numan Sachwani",
author_email="[email protected]",
url="https://github.com/numan/sunspear",
packages=find_packages(exclude=['tests']),
test_suite='nose.collector',
install_requires=[
'nydus==0.10.4',
'riak==1.5.1',
'python-dateutil==1.5',
'protobuf==2.4.1',
],
dependency_links=[
'https://github.com/disqus/nydus/tarball/master#egg=nydus-0.10.4',
],
options={'easy_install': {'allow_hosts': 'pypi.python.org'}},
tests_require=tests_require,
extras_require={"test": tests_require, "nosetests": tests_require},
include_package_data=True,
classifiers=[
"Intended Audience :: Developers",
'Intended Audience :: System Administrators',
"Programming Language :: Python",
"Topic :: Software Development",
"Topic :: Utilities",
],
)
| #!/usr/bin/python
from setuptools import setup, find_packages
tests_require=[
'nose',
'mock',
]
setup(
name="sunspear",
license='Apache License 2.0',
version="0.1.0a",
description="Activity streams backed by Riak.",
zip_safe=False,
long_description=open('README.rst', 'r').read(),
author="Numan Sachwani",
author_email="[email protected]",
url="https://github.com/numan/sunspear",
packages=find_packages(exclude=['tests']),
test_suite='nose.collector',
install_requires=[
'nydus==0.10.4',
'riak==1.5.1',
'python-dateutil==1.5',
'protobuf==2.4.1',
],
dependency_links=[
'https://github.com/numan/nydus/tarball/0.10.4#egg=nydus-0.10.4',
],
options={'easy_install': {'allow_hosts': 'pypi.python.org'}},
tests_require=tests_require,
extras_require={"test": tests_require, "nosetests": tests_require},
include_package_data=True,
classifiers=[
"Intended Audience :: Developers",
'Intended Audience :: System Administrators',
"Programming Language :: Python",
"Topic :: Software Development",
"Topic :: Utilities",
],
)
|
Use Python importlib instead of sjango.utils.importlib | from django.conf import settings
from importlib import import_module
class InvalidTemplateFixture(Exception):
pass
# holds all the fixtures
template_fixtures = {}
def get_template_fixtures():
"""
Return the list of all available template fixtures.
Caches the result for faster access.
Code modified from django/template/base.py/get_templatetags_modules()
"""
global template_fixtures
if not template_fixtures:
_template_fixtures = {}
# Populate list once per process. Mutate the local list first, and
# then assign it to the global name to ensure there are no cases where
# two threads try to populate it simultaneously.
for app_module in list(settings.INSTALLED_APPS):
try:
templatefixture_module = '%s.templatefixtures' % app_module
mod = import_module(templatefixture_module)
try:
fixtures = mod.fixtures
# TODO: validate fixtures structure
_template_fixtures.update(fixtures)
except AttributeError:
raise InvalidTemplateFixture('Template fixture module %s '
'does not have a variable'
'named "fixtures"' %
templatefixture_module)
except ValueError:
raise InvalidTemplateFixture('%s.fixture should be a '
'dictionary' %
templatefixture_module)
except ImportError as e:
#print app_module, e
continue
template_fixtures = _template_fixtures
return template_fixtures
| from django.conf import settings
from django.utils.importlib import import_module
class InvalidTemplateFixture(Exception):
pass
# holds all the fixtures
template_fixtures = {}
def get_template_fixtures():
"""
Return the list of all available template fixtures.
Caches the result for faster access.
Code modified from django/template/base.py/get_templatetags_modules()
"""
global template_fixtures
if not template_fixtures:
_template_fixtures = {}
# Populate list once per process. Mutate the local list first, and
# then assign it to the global name to ensure there are no cases where
# two threads try to populate it simultaneously.
for app_module in list(settings.INSTALLED_APPS):
try:
templatefixture_module = '%s.templatefixtures' % app_module
mod = import_module(templatefixture_module)
try:
fixtures = mod.fixtures
# TODO: validate fixtures structure
_template_fixtures.update(fixtures)
except AttributeError:
raise InvalidTemplateFixture('Template fixture module %s '
'does not have a variable'
'named "fixtures"' %
templatefixture_module)
except ValueError:
raise InvalidTemplateFixture('%s.fixture should be a '
'dictionary' %
templatefixture_module)
except ImportError as e:
#print app_module, e
continue
template_fixtures = _template_fixtures
return template_fixtures
|
Make the reply parser for INFO < 2.4 somewhat backwards compatible when used against Redis >= 2.4. | <?php
namespace Predis\Commands;
class Info extends Command {
public function canBeHashed() { return false; }
public function getId() { return 'INFO'; }
public function parseResponse($data) {
$info = array();
$infoLines = explode("\r\n", $data, -1);
foreach ($infoLines as $row) {
@list($k, $v) = explode(':', $row);
if ($row === '' || !isset($v)) {
continue;
}
if (!preg_match('/^db\d+$/', $k)) {
if ($k === 'allocation_stats') {
$info[$k] = $this->parseAllocationStats($v);
continue;
}
$info[$k] = $v;
}
else {
$db = array();
foreach (explode(',', $v) as $dbvar) {
list($dbvk, $dbvv) = explode('=', $dbvar);
$db[trim($dbvk)] = $dbvv;
}
$info[$k] = $db;
}
}
return $info;
}
protected function parseAllocationStats($str) {
$stats = array();
foreach (explode(',', $str) as $kv) {
@list($size, $objects, $extra) = explode('=', $kv);
// hack to prevent incorrect values when parsing the >=256 key
if (isset($extra)) {
$size = ">=$objects";
$objects = $extra;
}
$stats[$size] = $objects;
}
return $stats;
}
}
| <?php
namespace Predis\Commands;
class Info extends Command {
public function canBeHashed() { return false; }
public function getId() { return 'INFO'; }
public function parseResponse($data) {
$info = array();
$infoLines = explode("\r\n", $data, -1);
foreach ($infoLines as $row) {
list($k, $v) = explode(':', $row);
if (!preg_match('/^db\d+$/', $k)) {
if ($k === 'allocation_stats') {
$info[$k] = $this->parseAllocationStats($v);
continue;
}
$info[$k] = $v;
}
else {
$db = array();
foreach (explode(',', $v) as $dbvar) {
list($dbvk, $dbvv) = explode('=', $dbvar);
$db[trim($dbvk)] = $dbvv;
}
$info[$k] = $db;
}
}
return $info;
}
protected function parseAllocationStats($str) {
$stats = array();
foreach (explode(',', $str) as $kv) {
list($size, $objects, $extra) = explode('=', $kv);
// hack to prevent incorrect values when parsing the >=256 key
if (isset($extra)) {
$size = ">=$objects";
$objects = $extra;
}
$stats[$size] = $objects;
}
return $stats;
}
}
|
Use same tag for exception location | <?php
class CM_ExceptionHandling_Formatter_Html extends CM_ExceptionHandling_Formatter_Abstract {
public function getHeader(CM_ExceptionHandling_SerializableException $exception) {
return '<h1>' . $exception->getClass() . '</h1><h2>' . $exception->getMessage() . '</h2><pre>' . $exception->getFile() . ' on line ' .
$exception->getLine() . '</pre>';
}
public function getTrace(CM_ExceptionHandling_SerializableException $exception) {
$traceString = '<pre>';
$indent = strlen(count($exception->trace)) + 4;
foreach ($exception->trace as $number => $entry) {
$traceString .= str_pad($number, $indent, ' ', STR_PAD_LEFT) . '. ';
$traceString .= $entry['code'] . ' ' . $entry['file'];
if (null !== $entry['line']) {
$traceString .= ':' . $entry['line'];
}
$traceString .= PHP_EOL;
}
$traceString .= '</pre>';
return $traceString;
}
public function getMetaInfo(CM_ExceptionHandling_SerializableException $exception) {
if (empty($exception->metaInfo)) {
return '';
}
$metaInfoString = '<pre>';
foreach ($exception->metaInfo as $key => $value) {
$metaInfoString .= $key . ': ' . $value . PHP_EOL;
}
$metaInfoString .= '</pre>';
return $metaInfoString;
}
}
| <?php
class CM_ExceptionHandling_Formatter_Html extends CM_ExceptionHandling_Formatter_Abstract {
public function getHeader(CM_ExceptionHandling_SerializableException $exception) {
return '<h1>' . $exception->getClass() . '</h1><h2>' . $exception->getMessage() . '</h2><code>' . $exception->getFile() . ' on line ' .
$exception->getLine() . '</pre>';
}
public function getTrace(CM_ExceptionHandling_SerializableException $exception) {
$traceString = '<pre>';
$indent = strlen(count($exception->trace)) + 4;
foreach ($exception->trace as $number => $entry) {
$traceString .= str_pad($number, $indent, ' ', STR_PAD_LEFT) . '. ';
$traceString .= $entry['code'] . ' ' . $entry['file'];
if (null !== $entry['line']) {
$traceString .= ':' . $entry['line'];
}
$traceString .= PHP_EOL;
}
$traceString .= '</pre>';
return $traceString;
}
public function getMetaInfo(CM_ExceptionHandling_SerializableException $exception) {
if (empty($exception->metaInfo)) {
return '';
}
$metaInfoString = '<pre>';
foreach ($exception->metaInfo as $key => $value) {
$metaInfoString .= $key . ': ' . $value . PHP_EOL;
}
$metaInfoString .= '</pre>';
return $metaInfoString;
}
}
|
Add container spacing to 404 page | // @flow
/**
* Part of GDL gdl-frontend.
* Copyright (C) 2018 GDL
*
* See LICENSE
*/
import * as React from 'react';
import Taken from './Taken';
import { Trans } from '@lingui/react';
import Link from 'next/link';
import { Typography } from '@material-ui/core';
import Container from '../../elements/Container';
import A from '../../elements/A';
import Head from '../Head';
import Layout from '../Layout';
import { spacing } from '../../style/theme/';
const NotFound = () => (
<Layout>
<Head title="Page not found" />
<Container my="30px">
<Typography component="h1" align="center" variant="headline" gutterBottom>
<Trans>Oh no!</Trans>
</Typography>
<Typography
component="h2"
align="center"
variant="subheading"
gutterBottom
>
<Trans>The page you were looking for was taken by a 404.</Trans>
</Typography>
<div
css={{
textAlign: 'center',
marginTop: spacing.medium,
marginBottom: spacing.medium
}}
>
<Taken height="100%" />
</div>
<Link href="/" passHref>
<A align="center">
<Trans>Take me home</Trans>
</A>
</Link>
</Container>
</Layout>
);
export default NotFound;
| // @flow
/**
* Part of GDL gdl-frontend.
* Copyright (C) 2018 GDL
*
* See LICENSE
*/
import * as React from 'react';
import Taken from './Taken';
import { Trans } from '@lingui/react';
import Link from 'next/link';
import { Typography } from '@material-ui/core';
import Container from '../../elements/Container';
import A from '../../elements/A';
import Head from '../Head';
import Layout from '../Layout';
import { spacing } from '../../style/theme/';
const NotFound = () => (
<Layout>
<Head title="Page not found" />
<Container>
<Typography component="h1" align="center" variant="headline" gutterBottom>
<Trans>Oh no!</Trans>
</Typography>
<Typography
component="h2"
align="center"
variant="subheading"
gutterBottom
>
<Trans>The page you were looking for was taken by a 404.</Trans>
</Typography>
<div
css={{
textAlign: 'center',
marginTop: spacing.medium,
marginBottom: spacing.medium
}}
>
<Taken height="100%" />
</div>
<Link href="/" passHref>
<A align="center">
<Trans>Take me home</Trans>
</A>
</Link>
</Container>
</Layout>
);
export default NotFound;
|
Use second callback to then instead of catch | import createLocalStorageStore from './storage/localStorage'
import { AUTHENTICATE } from './actionTypes'
import { authenticateFailed, authenticateSucceeded, restore } from './actions'
const createAuthMiddleware = (config = {}) => {
const storage = config.storage || createLocalStorageStore()
const authenticators = config.authenticators || []
const findAuthenticator = name =>
authenticators.find(authenticator => authenticator.name === name)
return ({ dispatch, getState }) => {
storage
.restore()
.then(({ authenticated = {}}) => {
const authenticator = findAuthenticator(authenticated.authenticator)
if (authenticator) {
return authenticator
.restore(authenticated)
.then(() => dispatch(restore(authenticated)))
}
})
return next => action => {
switch (action.type) {
case AUTHENTICATE:
const authenticator = findAuthenticator(action.authenticator)
return authenticator
.authenticate(action.payload)
.then(data => {
storage.persist({
authenticated: {
...data,
authenticator: action.authenticator
}
})
dispatch(authenticateSucceeded(authenticator.name, data))
}, () => {
storage.clear()
dispatch(authenticateFailed())
})
default:
const { session: prevSession } = getState()
next(action)
const { session } = getState()
if (prevSession.isAuthenticated && !session.isAuthenticated) {
storage.clear()
}
}
}
}
}
export default createAuthMiddleware
| import createLocalStorageStore from './storage/localStorage'
import { AUTHENTICATE } from './actionTypes'
import { authenticateFailed, authenticateSucceeded, restore } from './actions'
const createAuthMiddleware = (config = {}) => {
const storage = config.storage || createLocalStorageStore()
const authenticators = config.authenticators || []
const findAuthenticator = name =>
authenticators.find(authenticator => authenticator.name === name)
return ({ dispatch, getState }) => {
storage
.restore()
.then(({ authenticated = {}}) => {
const authenticator = findAuthenticator(authenticated.authenticator)
if (authenticator) {
return authenticator
.restore(authenticated)
.then(() => dispatch(restore(authenticated)))
}
})
return next => action => {
switch (action.type) {
case AUTHENTICATE:
const authenticator = findAuthenticator(action.authenticator)
return authenticator
.authenticate(action.payload)
.then(data => {
storage.persist({
authenticated: {
...data,
authenticator: action.authenticator
}
})
dispatch(authenticateSucceeded(authenticator.name, data))
})
.catch(() => {
storage.clear()
dispatch(authenticateFailed())
})
default:
const { session: prevSession } = getState()
next(action)
const { session } = getState()
if (prevSession.isAuthenticated && !session.isAuthenticated) {
storage.clear()
}
}
}
}
}
export default createAuthMiddleware
|
Subsets and Splits