text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Add logging for graceful shutdown errors | const http = require('http');
const mongoose = require('mongoose');
const { logger } = require('./middleware/logger');
const app = require('./app');
const PORT = process.env.PORT || 6673;
const SERVER = http.createServer(app.callback());
// Gracefully close Mongo connection
const gracefulShutdown = (msg) => {
logger.info(`Shutdown initiated: ${msg}`);
mongoose.connection.close(false, () => {
logger.info('Mongo closed');
SERVER.close(() => {
logger.info('Shutting down...');
process.exit();
});
});
};
// Server start
app.on('ready', () => {
SERVER.listen(PORT, '0.0.0.0', () => {
logger.info(`Running on port: ${PORT}`);
// Handle kill commands
process.on('SIGTERM', gracefulShutdown);
// Handle interrupts
process.on('SIGINT', gracefulShutdown);
// Prevent dirty exit on uncaught exceptions:
process.on('uncaughtException', gracefulShutdown);
// Prevent dirty exit on unhandled promise rejection
process.on('unhandledRejection', gracefulShutdown);
});
});
| const http = require('http');
const mongoose = require('mongoose');
const { logger } = require('./middleware/logger');
const app = require('./app');
const PORT = process.env.PORT || 6673;
const SERVER = http.createServer(app.callback());
// Gracefully close Mongo connection
const gracefulShutdown = () => {
mongoose.connection.close(false, () => {
logger.info('Mongo closed');
SERVER.close(() => {
logger.info('Shutting down...');
process.exit();
});
});
};
// Server start
app.on('ready', () => {
SERVER.listen(PORT, '0.0.0.0', () => {
logger.info(`Running on port: ${PORT}`);
// Handle kill commands
process.on('SIGTERM', gracefulShutdown);
// Prevent dirty exit on code-fault crashes:
process.on('uncaughtException', gracefulShutdown);
// Prevent promise rejection exits
process.on('unhandledRejection', gracefulShutdown);
});
});
|
Use exact version instead of latest in the migration dependencies
Changed to use the latest migration of wagtail-blog v1.6.9.
Refs
https://github.com/thelabnyc/wagtail_blog/blob/5147d8129127102009c9bd63b1886e7665f6ccfb/blog/migrations/0005_auto_20151019_1121.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.9 on 2016-08-04 11:22
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import wagtail.wagtailcore.blocks
import wagtail.wagtailcore.fields
class Migration(migrations.Migration):
dependencies = [
('blog', '0005_auto_20151019_1121'),
('digi', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='themepage',
name='blog_category',
field=models.ForeignKey(blank=True, help_text='Corresponding blog category', null=True, on_delete=django.db.models.deletion.SET_NULL, to='blog.BlogCategory'),
),
migrations.AddField(
model_name='themepage',
name='body',
field=wagtail.wagtailcore.fields.StreamField((('paragraph', wagtail.wagtailcore.blocks.RichTextBlock()),), blank=True, null=True),
),
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.9.9 on 2016-08-04 11:22
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import wagtail.wagtailcore.blocks
import wagtail.wagtailcore.fields
class Migration(migrations.Migration):
dependencies = [
('blog', '__latest__'),
('digi', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='themepage',
name='blog_category',
field=models.ForeignKey(blank=True, help_text='Corresponding blog category', null=True, on_delete=django.db.models.deletion.SET_NULL, to='blog.BlogCategory'),
),
migrations.AddField(
model_name='themepage',
name='body',
field=wagtail.wagtailcore.fields.StreamField((('paragraph', wagtail.wagtailcore.blocks.RichTextBlock()),), blank=True, null=True),
),
]
|
[fix] Connect over the correct browser channel path | 'use strict';
/**
* Minimum viable Browserchannel server for Node.js that works through the primus
* interface.
*
* @runat server
* @api private
*/
module.exports = function server() {
var browserchannel = require('browserchannel')
, Spark = this.Spark
, primus = this.primus;
//
// We've received a new connection, create a new Spark. The Spark will
// automatically announce it self as a new connection once it's created (after
// the next tick).
//
this.service = browserchannel.server({
base: primus.pathname
}, function connection(socket) {
var spark = new Spark(
socket.headers
, socket.address
, socket.id
);
spark.on('incoming::end', function end() {
socket.close();
}).on('incoming::data', function write(data) {
socket.send(data);
});
socket.on('close', spark.emits('end'));
socket.on('message', spark.emits('data'));
});
//
// Listen to upgrade requests.
//
this.on('request', function request(req, res, next) {
//
// The browser.channel returns a middleware layer.
//
this.service(req, res, next);
});
};
| 'use strict';
/**
* Minimum viable Browserchannel server for Node.js that works through the primus
* interface.
*
* @runat server
* @api private
*/
module.exports = function server() {
var browserchannel = require('browserchannel')
, Spark = this.Spark
, primus = this.primus;
//
// We've received a new connection, create a new Spark. The Spark will
// automatically announce it self as a new connection once it's created (after
// the next tick).
//
this.service = browserchannel.server(function connection(socket) {
var spark = new Spark(
socket.headers
, socket.address
, socket.id
);
spark.on('incoming::end', function end() {
socket.close();
}).on('incoming::data', function write(data) {
socket.send(data);
});
socket.on('close', spark.emits('end'));
socket.on('message', spark.emits('data'));
});
//
// Listen to upgrade requests.
//
this.on('request', function request(req, res, next) {
//
// The browser.channel returns a middleware layer.
//
this.service(req, res, next);
});
};
|
Allow dropdown to select work site | //= require signature_pad
$( document ).ready(function() {
$('select').material_select();
var wrapper = document.getElementById("Signature"),
clearButton = document.getElementById("clear"),
saveButton = wrapper.querySelector("[data-action=save]"),
canvas = wrapper.querySelector("canvas"),
signaturePad;
signaturePad = new SignaturePad(canvas);
clearButton.addEventListener("click", function (event) {
signaturePad.clear();
});
$('#new_check_in_form').submit(function(e) {
if (signaturePad.isEmpty()) {
$('.Signature-pad').addClass('Signature-pad-error');
$('.description').addClass('Signature-error');
return false;
} else {
$('#check_in_form_signature').val(signaturePad.toDataURL());
}
});
})
| //= require signature_pad
$( document ).ready(function() {
var wrapper = document.getElementById("Signature"),
clearButton = document.getElementById("clear"),
saveButton = wrapper.querySelector("[data-action=save]"),
canvas = wrapper.querySelector("canvas"),
signaturePad;
signaturePad = new SignaturePad(canvas);
clearButton.addEventListener("click", function (event) {
signaturePad.clear();
});
$('#new_check_in_form').submit(function(e) {
if (signaturePad.isEmpty()) {
$('.Signature-pad').addClass('Signature-pad-error');
$('.description').addClass('Signature-error');
return false;
} else {
$('#check_in_form_signature').val(signaturePad.toDataURL());
}
});
})
|
Add specific version of rest framework | import ez_setup
ez_setup.use_setuptools()
from setuptools import setup, find_packages
setup(
name = "mobile-city-history",
version = "1.0.0b2",
author = "Jan-Christopher Pien",
author_email = "jan_christopher.pien@fokus.fraunhofer.de",
url = "http://www.foo.bar",
license = "MIT",
description = "A mobile city history to enable citizens to explore the history of their surroundings.",
packages = find_packages(),
zip_safe = False,
include_package_data = True,
install_requires = [
"sparqlwrapper",
"django >= 1.6",
"jsonpickle >= 0.7.0",
"django-apptemplates",
"djangorestframework = 2.3",
"schedule",
"django-cache-machine >= 0.8",
],
classifiers = [
"Programming Language :: Python",
"Development Status :: 4 - Beta",
"Environment :: Web Environment",
"Intended Audience :: Other Audience",
"Framework :: Django",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content :: News/Diary",
],
) | import ez_setup
ez_setup.use_setuptools()
from setuptools import setup, find_packages
setup(
name = "mobile-city-history",
version = "1.0.0b2",
author = "Jan-Christopher Pien",
author_email = "jan_christopher.pien@fokus.fraunhofer.de",
url = "http://www.foo.bar",
license = "MIT",
description = "A mobile city history to enable citizens to explore the history of their surroundings.",
packages = find_packages(),
zip_safe = False,
include_package_data = True,
install_requires = [
"sparqlwrapper",
"django >= 1.6",
"jsonpickle >= 0.7.0",
"django-apptemplates",
"djangorestframework",
"schedule",
"django-cache-machine >= 0.8",
],
classifiers = [
"Programming Language :: Python",
"Development Status :: 4 - Beta",
"Environment :: Web Environment",
"Intended Audience :: Other Audience",
"Framework :: Django",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content :: News/Diary",
],
) |
FIX - debug mode value converted to boolean | <?php
class app {
public static function get_value($key)
{
$app_info = new App_Info_Model($key);
return $app_info->get_value();
}
/**
* Return version of deployed DB. This version number is increased with each migrate.
* @static
* @return int version number (e.g. 8)
*/
public static function get_db_version()
{
return (int)self::get_value('database_version');
}
/**
* Check if application is in debug mode. Application could change it's behvaior according to that.
* E.g. profiler could be shown, error messages can have set lower threshold etc.
* @static
* @return bool TRUE if app is in debug mode
*/
public static function in_debug_mode()
{
return (self::get_value('application_debug_mode') == 'FALSE') ? FALSE : TRUE;
}
/**
* Return string representation of app version.
* @static
* @return string application version in format MAJOR.MINOR (e.g. 2.35)
*/
public static function get_full_version()
{
$major = self::get_value('application_version');
$minor = self::get_value('application_build');
return "$major.$minor";
}
}
| <?php
class app {
public static function get_value($key)
{
$app_info = new App_Info_Model($key);
return $app_info->get_value();
}
/**
* Return version of deployed DB. This version number is increased with each migrate.
* @static
* @return int version number (e.g. 8)
*/
public static function get_db_version()
{
return (int)self::get_value('database_version');
}
/**
* Check if application is in debug mode. Application could change it's behvaior according to that.
* E.g. profiler could be shown, error messages can have set lower threshold etc.
* @static
* @return bool TRUE if app is in debug mode
*/
public static function in_debug_mode()
{
return (boolean)self::get_value('application_debug_mode');
}
/**
* Return string representation of app version.
* @static
* @return string application version in format MAJOR.MINOR (e.g. 2.35)
*/
public static function get_full_version()
{
$major = self::get_value('application_version');
$minor = self::get_value('application_build');
return "$major.$minor";
}
}
|
Deal with comma-separated tags lists HNGH | import logging
from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect
import porick.lib.helpers as h
from porick.lib.auth import authorize
from porick.lib.base import BaseController, render
from porick.lib.create import create_quote, create_user
log = logging.getLogger(__name__)
class CreateController(BaseController):
def quote(self):
authorize()
c.page = 'new quote'
if request.environ['REQUEST_METHOD'] == 'GET':
return render('/create/form.mako')
elif request.environ['REQUEST_METHOD'] == 'POST':
quote_body = request.params.get('quote_body', '')
if not quote_body:
abort(400)
notes = request.params.get('notes', '')
tags = filter(None, request.params.get('tags', '').replace(',', ' ').split(' '))
result = create_quote(quote_body, notes, tags)
if result:
return render('/create/success.mako')
else:
abort(500)
else:
abort(400)
| import logging
from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect
import porick.lib.helpers as h
from porick.lib.auth import authorize
from porick.lib.base import BaseController, render
from porick.lib.create import create_quote, create_user
log = logging.getLogger(__name__)
class CreateController(BaseController):
def quote(self):
authorize()
c.page = 'new quote'
if request.environ['REQUEST_METHOD'] == 'GET':
return render('/create/form.mako')
elif request.environ['REQUEST_METHOD'] == 'POST':
quote_body = request.params.get('quote_body', '')
if not quote_body:
abort(400)
notes = request.params.get('notes', '')
tags = request.params.get('tags', '').split(' ')
result = create_quote(quote_body, notes, tags)
if result:
return render('/create/success.mako')
else:
abort(500)
else:
abort(400)
|
Remove unneeded usage of state | var App = (function () { "use strict";
var pub = {};
var scores = {
1: 0,
2: 0,
};
function render() {
React.unmountComponentAtNode(document.getElementById('scoreboard'));
React.render(
<ScoreBoard scores={scores} />,
document.getElementById('scoreboard')
);
}
pub.start = function () {
socket.on('update scores', function (newScores) {
scores = newScores;
render();
});
render();
};
return pub;
})();
var ScoreBoard = React.createClass({
render: function() {
return (
<div>
<div>
P1 Score: { this.props.scores[1] }
</div>
<div>
P2 Score: { this.props.scores[2] }
</div>
</div>
);
}
});
$(App.start);
| var App = (function () { "use strict";
var pub = {};
var scores = {
1: 0,
2: 0,
};
function render() {
React.unmountComponentAtNode(document.getElementById('scoreboard'));
React.render(
<ScoreBoard scores={scores} />,
document.getElementById('scoreboard')
);
}
pub.start = function () {
socket.on('update scores', function (newScores) {
scores = newScores;
render();
});
render();
};
return pub;
})();
var ScoreBoard = React.createClass({
render: function() {
return (
<div>
<div>
P1 Score: { this.state.scores[1] }
</div>
<div>
P2 Score: { this.state.scores[2] }
</div>
</div>
);
},
getInitialState: function () {
return this.props;
}
});
$(App.start);
|
Fix mem build - implement no-op method. | package com.splicemachine.derby.impl.sql;
import java.sql.SQLException;
import java.util.Properties;
import com.splicemachine.backup.BackupManager;
import com.splicemachine.colperms.ColPermsManager;
import com.splicemachine.db.authentication.UserAuthenticator;
import com.splicemachine.db.impl.jdbc.authentication.AuthenticationServiceBase;
import com.splicemachine.management.Manager;
/**
* Fake manager impl for mem db
*/
public class NoOpManager implements Manager {
private static NoOpManager ourInstance=new NoOpManager();
public static NoOpManager getInstance(){
return ourInstance;
}
private NoOpManager(){ }
@Override
public void enableEnterprise(char[] value) throws SQLException {
// no-op
}
@Override
public BackupManager getBackupManager() throws SQLException {
return NoOpBackupManager.getInstance();
}
@Override
public UserAuthenticator getAuthenticationManager(AuthenticationServiceBase svc, Properties properties) throws SQLException {
return null;
}
@Override
public ColPermsManager getColPermsManager() throws SQLException {
return null;
}
}
| package com.splicemachine.derby.impl.sql;
import java.sql.SQLException;
import java.util.Properties;
import com.splicemachine.backup.BackupManager;
import com.splicemachine.db.authentication.UserAuthenticator;
import com.splicemachine.db.impl.jdbc.authentication.AuthenticationServiceBase;
import com.splicemachine.management.Manager;
/**
* Fake manager impl for mem db
*/
public class NoOpManager implements Manager {
private static NoOpManager ourInstance=new NoOpManager();
public static NoOpManager getInstance(){
return ourInstance;
}
private NoOpManager(){ }
@Override
public void enableEnterprise(char[] value) throws SQLException {
// no-op
}
@Override
public BackupManager getBackupManager() throws SQLException {
return NoOpBackupManager.getInstance();
}
@Override
public UserAuthenticator getAuthenticationManager(AuthenticationServiceBase svc, Properties properties) throws SQLException {
return null;
}
}
|
Write note for test that triggers get request | import unittest
import django.test
from django.core.exceptions import ValidationError
from core.tests.setups import RobrechtSocialUserFactory
from ..validators import RepoExistanceValidator
###############################################################################
# Forms #
###############################################################################
'''
from ..forms import InvestmentModelForm
class InvestmentModelFormTestCase(TestCase):
"""
Tests for InvestmentModelForm
"""
def test_initial_value_of_investor_type(self):
"""
Verify initial value of investor_type field of InvestmentModelForm.
"""
investor_type_initial = InvestmentModelForm().fields["investor_type"].initial
self.assertEqual(investor_type_initial, "PERSON")
'''
###############################################################################
# Validators #
###############################################################################
# Test takes about ~0.7 secs because of requests call
@unittest.skip("")
class RepoExistanceValidatorTestCase(django.test.TestCase):
def test_repo_existance_validator(self):
user_rob = RobrechtSocialUserFactory()
self.assertRaises(ValidationError, RepoExistanceValidator(user_rob), "asiakas/non_existing_branch")
| import unittest
import django.test
from django.core.exceptions import ValidationError
from core.tests.setups import RobrechtSocialUserFactory
from ..validators import RepoExistanceValidator
###############################################################################
# Forms #
###############################################################################
'''
from ..forms import InvestmentModelForm
class InvestmentModelFormTestCase(TestCase):
"""
Tests for InvestmentModelForm
"""
def test_initial_value_of_investor_type(self):
"""
Verify initial value of investor_type field of InvestmentModelForm.
"""
investor_type_initial = InvestmentModelForm().fields["investor_type"].initial
self.assertEqual(investor_type_initial, "PERSON")
'''
###############################################################################
# Validators #
###############################################################################
# Test takes longer than average test because of requests call
#@unittest.skip("")
class RepoExistanceValidatorTestCase(django.test.TestCase):
def test_repo_existance_validator(self):
user_rob = RobrechtSocialUserFactory()
self.assertRaises(ValidationError, RepoExistanceValidator(user_rob), "asiakas/non_existing_branch")
|
Fix syntax according to jshint | import AppConfig from 'scripts/config';
export default class User extends Backbone.Model {
constructor(...args) {
this.urlRoot = `${AppConfig.apiPath}/users`;
this.validation = {
username: {
required: () => { return this.isSignup; }
},
password: {
required: true
},
password_confirmation: {
equalTo: 'password',
required: () => { return this.isSignup; }
},
email: {
pattern: 'email',
required: true
}
};
super(...args);
}
signIn() {
this.isSignup = false;
return this.send(`${this.url()}/sign_in`);
}
signUp() {
this.isSignup = true;
return this.send(`${this.url()}/sign_up`);
}
send(url) {
let deferred = $.Deferred();
if (this.isValid(true)) {
this.save(null, {
url,
success(data) {
deferred.resolve(data);
},
error(data) {
deferred.reject(data);
}
});
}
else {
deferred.reject();
}
return deferred.promise();
}
}
| import AppConfig from 'scripts/config';
export default class User extends Backbone.Model {
constructor(...args) {
this.urlRoot = `${AppConfig.apiPath}/users`;
this.validation = {
username: {
required: () => { return this.isSignup },
},
password: {
required: true
},
password_confirmation: {
equalTo: 'password',
required: () => { return this.isSignup },
},
email: {
pattern: 'email',
required: true
}
};
super(...args);
}
signIn() {
this.isSignup = false;
return this.send(`${this.url()}/sign_in`);
}
signUp() {
this.isSignup = true;
return this.send(`${this.url()}/sign_up`);
}
send(url) {
let deferred = $.Deferred();
if (this.isValid(true)) {
this.save(null, {
url,
success(data) {
deferred.resolve(data);
},
error(data) {
deferred.reject(data);
}
});
}
else {
deferred.reject();
}
return deferred.promise();
}
}
|
Add uglify to prod build. | var webpack = require('webpack');
module.exports = {
entry: [
'./src/index'
],
module: {
loaders: [{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel'
}, {
test: /\.css$/,
loader: 'style!css'
}]
},
resolve: {
extensions: ['', '.js', '.jsx']
},
output: {
path: __dirname + '/dist',
publicPath: '/',
filename: 'bundle.js'
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': '"production"',
'process.env.API_URL': '"https://api.expensetracker.rjbernaldo.com"',
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
})
]
}
| var webpack = require('webpack');
module.exports = {
entry: [
'./src/index'
],
module: {
loaders: [{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel'
}, {
test: /\.css$/,
loader: 'style!css'
}]
},
resolve: {
extensions: ['', '.js', '.jsx']
},
output: {
path: __dirname + '/dist',
publicPath: '/',
filename: 'bundle.js'
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': '"production"',
'process.env.API_URL': '"https://api.expensetracker.rjbernaldo.com"',
})
]
}
|
Remove fact from list once used | var AWS = require("aws-sdk");
AWS.config.update({region: 'us-east-1'});
exports.handler = function(event, context) {
var s3 = new AWS.S3();
var params = {Bucket: 'cat-assets', Key: 'catfacts.txt'};
var file = s3.getObject(params, function(err, data){
if(err){
context.fail(err);
}
var lines = data.Body.toString().split('\r\n');
var i = Math.floor(Math.random()*lines.length);
var fact = lines.splice(i, 1) + "! :3";
console.log(fact);
s3.putObject({
Bucket: 'cat-assets',
Key: 'catfacts.txt',
Body: lines.join('\r\n')
}, function(err){
if (err){
context.fail(err);
}
var sns = new AWS.SNS();
params = {
Message: fact,
Subject: "Cat Facts",
TopicArn: "arn:aws:sns:us-east-1:110820207274:CatFacts"
};
sns.publish(params, context.done);
});
});
}; | var AWS = require("aws-sdk");
AWS.config.update({region: 'us-east-1'});
exports.handler = function(event, context) {
var s3 = new AWS.S3();
var params = {Bucket: 'cat-assets', Key: 'catfacts.txt'};
var file = s3.getObject(params, function(err, data){
if(err){
context.fail(err);
}
var lines = data.Body.toString().split('\r\n');
var fact = lines[Math.floor(Math.random()*lines.length)] + "! :3";
console.log(fact);
var sns = new AWS.SNS();
params = {
Message: fact,
Subject: "Cat Facts",
TopicArn: "arn:aws:sns:us-east-1:110820207274:CatFacts"
};
sns.publish(params, context.done);
});
}; |
Add check for PDF files | import ckan.model as model
import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit
import os
def get_number_of_files():
return model.Session.execute("select count(*) from resource where state = 'active'").first()[0]
def get_number_of_external_links():
return model.Session.execute("select count(*) from resource where state = 'active' and url not LIKE '%data.gov.ro%'").first()[0]
class Romania_ThemePlugin(plugins.SingletonPlugin):
plugins.implements(plugins.IConfigurer)
plugins.implements(plugins.ITemplateHelpers)
plugins.implements(plugins.IResourceController)
# IConfigurer
def update_config(self, config):
toolkit.add_template_directory(config, 'templates')
toolkit.add_public_directory(config, 'public')
toolkit.add_resource('fanstatic', 'romania_theme')
def get_helpers(self):
return {'get_number_of_files': get_number_of_files,
'get_number_of_external_links': get_number_of_external_links}
+ # IResourceController
def before_create(self, context, resource):
if resource['upload'].type == 'application/pdf':
raise ValidationError(['Resource type not allowed as resource.'])
| import ckan.model as model
import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit
import os
def get_number_of_files():
return model.Session.execute("select count(*) from resource where state = 'active'").first()[0]
def get_number_of_external_links():
return model.Session.execute("select count(*) from resource where state = 'active' and url not LIKE '%data.gov.ro%'").first()[0]
class Romania_ThemePlugin(plugins.SingletonPlugin):
plugins.implements(plugins.IConfigurer)
plugins.implements(plugins.ITemplateHelpers)
def update_config(self, config):
toolkit.add_template_directory(config, 'templates')
toolkit.add_public_directory(config, 'public')
toolkit.add_resource('fanstatic', 'romania_theme')
def get_helpers(self):
return {'get_number_of_files': get_number_of_files,
'get_number_of_external_links': get_number_of_external_links}
|
Update columns of Images migration
- Add new original_filename to store original file name as local run of
Rika's custom locale results the image store into garbled names
- Rename few column names for better readability and self-explanatory | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateImagesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('images',function(Blueprint $table) {
$table->increments('id');
$table->integer('vn_id')->unsigned();
$table->string('original_filename');
$table->string('local_filename');
$table->string('alternative_image_url')->nullable();
$table->smallInteger('screen_category')->nullable()->comment('1:title, 2:gameplay, 3:config, 4:save/load, 5:omake');
$table->string('description', 600)->nullable();
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->useCurrent();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('images');
}
}
| <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateImagesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('images',function(Blueprint $table) {
$table->increments('id');
$table->integer('vn_id')->unsigned();
$table->string('local_name');
$table->string('image_url')->nullable();
$table->smallInteger('screen')->nullable()->comment('1:title, 2:gameplay, 3:config, 4:save/load, 5:omake');
$table->string('description', 600)->nullable();
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->useCurrent();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('images');
}
}
|
Add some image mime types. | const removeLeadingSlash = path => (path[0] === '/' ? path.substring(1) : path);
const generateFileNameSuffix = fileName => `${Date.now()}-${fileName}`;
const returnFileType = fileName => ({
docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
ppt: 'application/vnd.ms-powerpoint',
xls: 'application/vnd.ms-excel',
doc: 'application/vnd.ms-word',
odt: 'application/vnd.oasis.opendocument.text',
txt: 'text/plain',
pdf: 'application/pdf',
png: 'image/png',
jpg: 'image/jpeg',
jpeg: 'image/jpeg',
jpe: 'image/jpeg',
gif: 'image/gif',
tiff: 'image/tiff',
tif: 'image/tiff',
}[fileName.split('.').pop()]);
module.exports = {
removeLeadingSlash,
generateFileNameSuffix,
returnFileType,
};
| const removeLeadingSlash = path => (path[0] === '/' ? path.substring(1) : path);
const generateFileNameSuffix = fileName => `${Date.now()}-${fileName}`;
const returnFileType = fileName => ({
docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
ppt: 'application/vnd.ms-powerpoint',
xls: 'application/vnd.ms-excel',
doc: 'application/vnd.ms-word',
odt: 'application/vnd.oasis.opendocument.text',
txt: 'text/plain',
pdf: 'application/pdf',
png: 'image/png',
}[fileName.split('.').pop()]);
module.exports = {
removeLeadingSlash,
generateFileNameSuffix,
returnFileType,
};
|
Make sure InetUtils.executorService shuts down.
See https://github.com/spring-cloud/spring-cloud-netflix/issues/491 | package org.springframework.cloud.util;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author Spencer Gibb
*/
@Configuration
@ConditionalOnProperty(value = "spring.cloud.util.enabled", matchIfMissing = true)
@AutoConfigureOrder(0)
@EnableConfigurationProperties
public class UtilAutoConfiguration {
@Bean
public InetUtilsProperties inetUtilsProperties() {
return new InetUtilsProperties();
}
@Bean(destroyMethod = "close")
@ConditionalOnMissingBean
public InetUtils inetUtils(InetUtilsProperties properties) {
return new InetUtils(properties);
}
}
| package org.springframework.cloud.util;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author Spencer Gibb
*/
@Configuration
@ConditionalOnProperty(value = "spring.cloud.util.enabled", matchIfMissing = true)
@AutoConfigureOrder(0)
@EnableConfigurationProperties
public class UtilAutoConfiguration {
@Bean
public InetUtilsProperties inetUtilsProperties() {
return new InetUtilsProperties();
}
@Bean
@ConditionalOnMissingBean
public InetUtils inetUtils(InetUtilsProperties properties) {
return new InetUtils(properties);
}
}
|
Change back Bridge scheduler to 12 pm daily | package org.sagebionetworks.dashboard;
import javax.annotation.Resource;
import org.sagebionetworks.dashboard.service.BridgeDynamoImporter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* Schedules the work of importing Bridge data into data warehouse.
*/
@Component("bridgeScheduler")
public final class BridgeScheduler {
private final Logger logger = LoggerFactory.getLogger(BridgeScheduler.class);
@Resource
private BridgeDynamoImporter bridgeDynamoImporter;
/**
* 12 pm UTC or 5 am PDT. Make sure this happens after daily backup is done.
*/
@Scheduled(cron="00 00 12 * * *", zone="UTC")
public void run() {
logger.info("Begin importing Bridge DynamoDB tables to Redshift.");
bridgeDynamoImporter.run();
logger.info("Finished importing Bridge DynamoDB tables to Redshift.");
}
}
| package org.sagebionetworks.dashboard;
import javax.annotation.Resource;
import org.sagebionetworks.dashboard.service.BridgeDynamoImporter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* Schedules the work of importing Bridge data into data warehouse.
*/
@Component("bridgeScheduler")
public final class BridgeScheduler {
private final Logger logger = LoggerFactory.getLogger(BridgeScheduler.class);
@Resource
private BridgeDynamoImporter bridgeDynamoImporter;
/**
* 12 pm UTC or 5 am PDT. Make sure this happens after daily backup is done.
*/
@Scheduled(cron="00 55 * * * *", zone="UTC")
public void run() {
logger.info("Begin importing Bridge DynamoDB tables to Redshift.");
bridgeDynamoImporter.run();
logger.info("Finished importing Bridge DynamoDB tables to Redshift.");
}
}
|
Update Text Component to allow React components to render as child | import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import styles from './text_component.module.scss';
function setWeight( { semibold, light } ) {
if ( semibold ) return styles.semibold;
if ( light ) return styles.light;
return styles.regular;
}
function TextComponent( props ) {
const {
tag,
children,
type,
className,
} = props;
const kids = typeof(children.type) === "function" ? children.type( children.props ) : [ ...children ];
return React.createElement(
tag,
{ className: classnames(
styles[`typography-${type}`],
setWeight( props ),
className
) },
kids
);
}
TextComponent.propTypes = {
/**
* You can use any html element text tag
*/
tag: PropTypes.string,
/**
* determines typography class
*/
type: PropTypes.number,
/**
* Font weight: 300
*/
light: PropTypes.bool,
/**
* Font weight: 400
*/
regular: PropTypes.bool,
/**
* Font weight: 600
*/
semibold: PropTypes.bool,
/**
* adds class name to class set
*/
className: PropTypes.string
};
TextComponent.defaultProps = {
tag: 'p',
type: 6
};
export default TextComponent;
| import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import styles from './text_component.module.scss';
function setWeight( { semibold, light } ) {
if ( semibold ) return styles.semibold;
if ( light ) return styles.light;
return styles.regular;
}
function TextComponent( props ) {
const {
tag,
children,
type,
className,
} = props;
return React.createElement(
tag,
{ className: classnames(
styles[`typography-${type}`],
setWeight( props ),
className
) },
[ ...children ]
);
}
TextComponent.propTypes = {
/**
* You can use any html element text tag
*/
tag: PropTypes.string,
/**
* determines typography class
*/
type: PropTypes.number,
/**
* Font weight: 300
*/
light: PropTypes.bool,
/**
* Font weight: 400
*/
regular: PropTypes.bool,
/**
* Font weight: 600
*/
semibold: PropTypes.bool,
/**
* adds class name to class set
*/
className: PropTypes.string
};
TextComponent.defaultProps = {
tag: 'p',
type: 6
};
export default TextComponent;
|
Fix test - s/time/updated_at/ named param | import unittest
import StringIO
from ztag.stream import Updater, UpdateRow
class UpdaterTestCase(unittest.TestCase):
FREQUENCY = 1.0
def setUp(self):
pass
def test_updater(self):
"""
Check that the updater runs as expected.
"""
output = StringIO.StringIO()
updater = Updater(output=output, frequency=self.FREQUENCY)
skipped = 0
handled = 0
expected = [UpdateRow.get_csv_labels()]
for i in range(0, 100000):
skipped += 1
handled += 2
row = UpdateRow(
skipped=skipped,
handled=handled,
updated_at=float(i) / 100.0,
prev=updater.prev)
if not updater.prev or (row.time - updater.prev.time) >= updater.frequency:
expected.append(row.get_csv())
updater.put_update(row)
self.assertEquals("\n".join(expected) + "\n", output.getvalue())
updater.close()
| import unittest
import StringIO
from ztag.stream import Updater, UpdateRow
class UpdaterTestCase(unittest.TestCase):
FREQUENCY = 1.0
def setUp(self):
pass
def test_updater(self):
"""
Check that the updater runs as expected.
"""
output = StringIO.StringIO()
updater = Updater(output=output, frequency=self.FREQUENCY)
skipped = 0
handled = 0
expected = [UpdateRow.get_csv_labels()]
for i in range(0, 100000):
skipped += 1
handled += 2
row = UpdateRow(
skipped=skipped,
handled=handled,
time=float(i) / 100.0,
prev=updater.prev)
if not updater.prev or (row.time - updater.prev.time) >= updater.frequency:
expected.append(row.get_csv())
updater.put_update(row)
self.assertEquals("\n".join(expected) + "\n", output.getvalue())
updater.close()
|
Add retry strategy for RPC server | package com.yuzhouwan.site.service.rpc.core;
import com.yuzhouwan.site.api.rpc.service.IRPCService;
import com.yuzhouwan.site.api.rpc.service.Server;
import com.yuzhouwan.site.service.rpc.service.RPCServiceImpl;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Copyright @ 2017 yuzhouwan.com
* All right reserved.
* Function: RPC Tester
*
* @author Benedict Jin
* @since 2016/9/1
*/
public class RPCTest {
@Test
public void rpc() throws Exception {
Server server = new RPC.RPCServer();
server.register(IRPCService.class, RPCServiceImpl.class);
server.start();
int count = 0, max = 5;
while (!server.isRunning() && count < max) {
Thread.sleep(10);
count++;
}
IRPCService testServiceImpl = RPC.getProxy(IRPCService.class, "localhost", server.getPort());
assertEquals("Hello, Benedict!", testServiceImpl.printHello("Benedict"));
server.stop(); // System.exit(0);
}
}
| package com.yuzhouwan.site.service.rpc.core;
import com.yuzhouwan.site.api.rpc.service.IRPCService;
import com.yuzhouwan.site.api.rpc.service.Server;
import com.yuzhouwan.site.service.rpc.service.RPCServiceImpl;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Copyright @ 2017 yuzhouwan.com
* All right reserved.
* Function: RPC Tester
*
* @author Benedict Jin
* @since 2016/9/1
*/
public class RPCTest {
@Test
public void rpc() throws Exception {
Server server = new RPC.RPCServer();
server.register(IRPCService.class, RPCServiceImpl.class);
server.start();
Thread.sleep(100);
IRPCService testServiceImpl = RPC.getProxy(IRPCService.class, "localhost", server.getPort());
assertEquals("Hello, Benedict!", testServiceImpl.printHello("Benedict"));
server.stop(); // System.exit(0);
}
}
|
Change the default route of Album to not show / when no action | <?php
return array(
'controllers' => array(
'invokables' => array(
'Album\Controller\Album' => 'Album\Controller\AlbumController',
),
),
'router' => array(
'routes' => array(
'album' => array(
'type' => 'segment',
'options' => array(
'route' => '/album[/:action][/:id]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
),
'defaults' => array(
'controller' => 'Album\Controller\Album',
'action' => 'index',
),
),
),
),
),
'view_manager' => array(
'template_path_stack' => array(
'album' => __DIR__ . '/../view',
),
),
); | <?php
return array(
'controllers' => array(
'invokables' => array(
'Album\Controller\Album' => 'Album\Controller\AlbumController',
),
),
'router' => array(
'routes' => array(
'album' => array(
'type' => 'segment',
'options' => array(
'route' => '/album[/][:action][/:id]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
),
'defaults' => array(
'controller' => 'Album\Controller\Album',
'action' => 'index',
),
),
),
),
),
'view_manager' => array(
'template_path_stack' => array(
'album' => __DIR__ . '/../view',
),
),
); |
Make autoFocus work again in dialogs | import cx from 'clsx';
import React from 'react';
import PropTypes from 'prop-types';
const {
useEffect,
useImperativeHandle,
useRef,
} = React;
const TextField = React.forwardRef(({
className,
type = 'text',
icon,
autoFocus,
...props
}, ref) => {
const refInput = useRef(null);
useImperativeHandle(ref, () => ({
get value() { return refInput.current.value; },
}));
useEffect(() => {
if (autoFocus) {
refInput.current?.focus();
}
}, []); // eslint-disable-line react-hooks/exhaustive-deps
return (
<div className={cx('TextField', className)}>
<input
ref={refInput}
className="TextField-input"
type={type}
{...props}
/>
{icon ? (
<div className="TextField-icon">{icon}</div>
) : null}
</div>
);
});
TextField.propTypes = {
className: PropTypes.string,
type: PropTypes.string,
icon: PropTypes.node,
autoFocus: PropTypes.bool,
};
export default TextField;
| import cx from 'clsx';
import React from 'react';
import PropTypes from 'prop-types';
const {
useImperativeHandle,
useRef,
} = React;
const TextField = React.forwardRef(({
className,
type = 'text',
icon,
...props
}, ref) => {
const refInput = useRef(null);
useImperativeHandle(ref, () => ({
get value() { return refInput.current.value; },
}));
return (
<div className={cx('TextField', className)}>
<input
ref={refInput}
className="TextField-input"
type={type}
{...props}
/>
{icon ? (
<div className="TextField-icon">{icon}</div>
) : null}
</div>
);
});
TextField.propTypes = {
className: PropTypes.string,
type: PropTypes.string,
icon: PropTypes.node,
};
export default TextField;
|
Revert "Add default value to variant enabled column migration"
This reverts commit 540031efb23dae1207254b9beb5989e5c0810dcb. | <?php
declare(strict_types=1);
namespace Sylius\Migrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20200309172908 extends AbstractMigration
{
public function getDescription() : string
{
return '';
}
public function up(Schema $schema) : void
{
// this up() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE sylius_product_variant ADD enabled TINYINT(1) NOT NULL');
}
public function down(Schema $schema) : void
{
// this down() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE sylius_product_variant DROP enabled');
}
}
| <?php
declare(strict_types=1);
namespace Sylius\Migrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20200309172908 extends AbstractMigration
{
public function getDescription() : string
{
return '';
}
public function up(Schema $schema) : void
{
// this up() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE sylius_product_variant ADD enabled TINYINT(1) DEFAULT 1 NOT NULL');
}
public function down(Schema $schema) : void
{
// this down() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE sylius_product_variant DROP enabled');
}
}
|
Add a missing Form::close() method | @extends('layouts.admin')
@section('title'){{ $title }}@endsection
@section('content')
{{ Form::model($page, ['url' => $url, 'method' => $method]) }}
<label class="checkbox pull-right">
{{ Form::checkbox('is_visible') }} Visible (Published)
</label>
{{ Form::label('title', 'Page Title') }}
{{ Form::text('title', null, ['class'=>'input-xxlarge', 'style'=>'font-size:150%']) }}
{{ Form::label('slug', 'URL (slug)') }}
{{ Form::text('slug', null, ['class'=>'input-xxlarge']) }}
{{ Form::label('body', 'Body (Markdown)') }}
{{ Form::textarea('body', null, ['class'=>'input-block-level', 'rows'=>20]) }}
{{ Form::label('head', 'Extra HTML for <head>') }}
{{ Form::textarea('head', null, ['class'=>'input-block-level']) }}
<p>
{{ Form::submit('Submit', ['class'=>'btn']) }}
{{ Html::linkRoute('sysop.pages.index', 'Cancel', null, ['class'=>'btn btn-danger'])}}
</p>
{{ Form::close() }}
@endsection
| @extends('layouts.admin')
@section('title'){{ $title }}@endsection
@section('content')
{{ Form::model($page, ['url' => $url, 'method' => $method]) }}
<label class="checkbox pull-right">
{{ Form::checkbox('is_visible') }} Visible (Published)
</label>
{{ Form::label('title', 'Page Title') }}
{{ Form::text('title', null, ['class'=>'input-xxlarge', 'style'=>'font-size:150%']) }}
{{ Form::label('slug', 'URL (slug)') }}
{{ Form::text('slug', null, ['class'=>'input-xxlarge']) }}
{{ Form::label('body', 'Body (Markdown)') }}
{{ Form::textarea('body', null, ['class'=>'input-block-level', 'rows'=>20]) }}
{{ Form::label('head', 'Extra HTML for <head>') }}
{{ Form::textarea('head', null, ['class'=>'input-block-level']) }}
<p>
{{ Form::submit('Submit', ['class'=>'btn']) }}
{{ Html::linkRoute('sysop.pages.index', 'Cancel', null, ['class'=>'btn btn-danger'])}}
</p>
@endsection
|
Return http status 500 instead of 400 on errors
400 implies that there is a problem with the request. 500 is an internal error. | var express = require('express')
var Crudivore = require('./crudivore')
var _ = require('lodash')
var app = express()
function start(config, onSuccess) {
var render = Crudivore(config)
app.set('port', (process.env.PORT || 5000))
var server = app.listen(app.get('port'), function() {
console.log('Running on port ' + app.get('port'))
if (onSuccess) onSuccess()
})
app.get('/render/*', function(req, res) {
var pageUrl = decodeURIComponent(req.params[0])
console.log('Requesting page ', pageUrl)
var renderingResult = render.renderPage(pageUrl)
renderingResult.onError(function(e) {
console.log(e)
res.status(500).end()
})
renderingResult.onValue(function(result) {
_(result.headers).each(function(value, name) {
res.setHeader(name, value)
})
res.status(result.status).send(result.content)
})
})
app.get('/info/', function(req, res) {
res.send(render.threadInfo())
})
return server
}
module.exports = start
| var express = require('express')
var Crudivore = require('./crudivore')
var _ = require('lodash')
var app = express()
function start(config, onSuccess) {
var render = Crudivore(config)
app.set('port', (process.env.PORT || 5000))
var server = app.listen(app.get('port'), function() {
console.log('Running on port ' + app.get('port'))
if (onSuccess) onSuccess()
})
app.get('/render/*', function(req, res) {
var pageUrl = decodeURIComponent(req.params[0])
console.log('Requesting page ', pageUrl)
var renderingResult = render.renderPage(pageUrl)
renderingResult.onError(function(e) {
console.log(e)
res.status(400).end()
})
renderingResult.onValue(function(result) {
_(result.headers).each(function(value, name) {
res.setHeader(name, value)
})
res.status(result.status).send(result.content)
})
})
app.get('/info/', function(req, res) {
res.send(render.threadInfo())
})
return server
}
module.exports = start
|
Refactor output format to be same as input format, standardizing the API | package com.google.sps.data;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.commons.collections4.keyvalue.MultiKey;
/*
* Class representing one row/entry in the aggregation response. A NULL field value
* means the field was not being aggregated by, and will be omitted from the JSON response
*/
public final class AggregationResponseEntry {
private String annotatedAssetId;
private String annotatedLocation;
private String annotatedUser;
private final int count;
public AggregationResponseEntry(MultiKey key, int count, Set<AnnotatedField> fields) {
String keys[] = (String[]) key.getKeys();
int currKey = 0;
Iterator<AnnotatedField> it = fields.iterator();
while (it.hasNext()) {
switch(it.next()) {
case ASSET_ID:
this.annotatedAssetId = keys[currKey++];
break;
case LOCATION:
this.annotatedLocation = keys[currKey++];
break;
case USER:
this.annotatedUser = keys[currKey++];
break;
}
}
this.count = count;
}
}
| package com.google.sps.data;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.commons.collections4.keyvalue.MultiKey;
/*
* Class representing one row/entry in the aggregation response. A NULL field value
* means the field was not being aggregated by, and will be omitted from the JSON response
*/
public final class AggregationResponseEntry {
private String assetId;
private String location;
private String user;
private final int count;
public AggregationResponseEntry(MultiKey key, int count, Set<AnnotatedField> fields) {
String keys[] = (String[]) key.getKeys();
int currKey = 0;
Iterator<AnnotatedField> it = fields.iterator();
while (it.hasNext()) {
switch(it.next()) {
case ASSET_ID:
this.assetId = keys[currKey++];
break;
case LOCATION:
this.location = keys[currKey++];
break;
case USER:
this.user = keys[currKey++];
break;
}
}
this.count = count;
}
}
|
Send a signal on each message that is sent to allow for external customization. | from django.db.models import Manager
from user_messages.signals import message_sent
class ThreadManager(Manager):
def inbox(self, user):
return self.filter(userthread__user=user, userthread__deleted=False)
def unread(self, user):
return self.filter(userthread__user=user, userthread__deleted=False, userthread__unread=True)
class MessageManager(Manager):
def new_reply(self, thread, user, content):
msg = self.create(thread=thread, sender=user, content=content)
thread.userthread_set.exclude(user=user).update(deleted=False, unread=True)
message_sent.send(sender=self.model, message=msg, thread=thread)
return msg
def new_message(self, from_user, to_users, subject, content):
from user_messages.models import Thread
thread = Thread.objects.create(subject=subject)
for user in to_users:
thread.userthread_set.create(user=user, deleted=False, unread=True)
thread.userthread_set.create(user=from_user, deleted=True, unread=False)
msg = self.create(thread=thread, sender=from_user, content=content)
message_sent.send(sender=self.model, message=msg, thread=thread)
return msg
| from django.db.models import Manager
class ThreadManager(Manager):
def inbox(self, user):
return self.filter(userthread__user=user, userthread__deleted=False)
def unread(self, user):
return self.filter(userthread__user=user, userthread__deleted=False, userthread__unread=True)
class MessageManager(Manager):
def new_reply(self, thread, user, content):
msg = self.create(thread=thread, sender=user, content=content)
thread.userthread_set.exclude(user=user).update(deleted=False, unread=True)
return msg
def new_message(self, from_user, to_users, subject, content):
from user_messages.models import Thread
thread = Thread.objects.create(subject=subject)
for user in to_users:
thread.userthread_set.create(user=user, deleted=False, unread=True)
thread.userthread_set.create(user=from_user, deleted=True, unread=False)
return self.create(thread=thread, sender=from_user, content=content)
|
Add type constant for data one of. | package de.uni_stuttgart.vis.vowl.owl2vowl.constants;
public class Node_Types {
public static final String TYPE_CLASS = "owl:Class";
public static final String TYPE_RDFSCLASS = "rdfs:Class";
public static final String TYPE_EQUIVALENT = "owl:equivalentClass";
public static final String TYPE_EXTERNALCLASS = "externalclass";
public static final String TYPE_DEPRECTAEDCLASS = "owl:DeprecatedClass";
public static final String TYPE_THING = "owl:Thing";
public static final String TYPE_NOTHING = "owl:Nothing";
public static final String TYPE_RDFSRESOURCE = "rdfs:Resource";
public static final String TYPE_UNION = "owl:unionOf";
public static final String TYPE_INTERSECTION = "owl:intersectionOf";
public static final String TYPE_COMPLEMENT = "owl:complementOf";
public static final String TYPE_DATATYPE = "rdfs:Datatype";
public static final String TYPE_LITERAL = "rdfs:Literal";
public static final String KEY_TYPE_DATA_ONE_OF = "DATA_ONE_OF";
}
| package de.uni_stuttgart.vis.vowl.owl2vowl.constants;
public class Node_Types {
public static final String TYPE_CLASS = "owl:Class";
public static final String TYPE_RDFSCLASS = "rdfs:Class";
public static final String TYPE_EQUIVALENT = "owl:equivalentClass";
public static final String TYPE_EXTERNALCLASS = "externalclass";
public static final String TYPE_DEPRECTAEDCLASS = "owl:DeprecatedClass";
public static final String TYPE_THING = "owl:Thing";
public static final String TYPE_NOTHING = "owl:Nothing";
public static final String TYPE_RDFSRESOURCE = "rdfs:Resource";
public static final String TYPE_UNION = "owl:unionOf";
public static final String TYPE_INTERSECTION = "owl:intersectionOf";
public static final String TYPE_COMPLEMENT = "owl:complementOf";
public static final String TYPE_DATATYPE = "rdfs:Datatype";
public static final String TYPE_LITERAL = "rdfs:Literal";
}
|
Add Metafield property and method to docblock
SmartCollection has Metafield support, but static analysis will complain unless it is described in the docblock. | <?php
/**
* Created by PhpStorm.
* @author Tareq Mahmood <tareqtms@yahoo.com>
* Created at 8/19/16 7:40 PM UTC+06:00
*
* @see https://help.shopify.com/api/reference/smartcollection Shopify API Reference for SmartCollection
*/
namespace PHPShopify;
/**
* --------------------------------------------------------------------------
* SmartCollection -> Child Resources
* --------------------------------------------------------------------------
* @property-read Event $Event
* @property-read Metafield $Metafield
*
* @method Event Event(integer $id = null)
* @method Metafield Metafield(integer $id = null)
*
* --------------------------------------------------------------------------
* SmartCollection -> Custom actions
* --------------------------------------------------------------------------
*
*/
class SmartCollection extends ShopifyResource
{
/**
* @inheritDoc
*/
protected $resourceKey = 'smart_collection';
/**
* @inheritDoc
*/
protected $childResource = array(
'Event',
'Metafield',
);
/**
* Set the ordering type and/or the manual order of products in a smart collection
*
* @param array $params
*
* @return array
*/
public function sortOrder($params)
{
$url = $this->generateUrl($params, 'order');
return $this->put(array(), $url);
}
}
| <?php
/**
* Created by PhpStorm.
* @author Tareq Mahmood <tareqtms@yahoo.com>
* Created at 8/19/16 7:40 PM UTC+06:00
*
* @see https://help.shopify.com/api/reference/smartcollection Shopify API Reference for SmartCollection
*/
namespace PHPShopify;
/**
* --------------------------------------------------------------------------
* SmartCollection -> Child Resources
* --------------------------------------------------------------------------
* @property-read Event $Event
*
* @method Event Event(integer $id = null)
*
* --------------------------------------------------------------------------
* SmartCollection -> Custom actions
* --------------------------------------------------------------------------
*
*/
class SmartCollection extends ShopifyResource
{
/**
* @inheritDoc
*/
protected $resourceKey = 'smart_collection';
/**
* @inheritDoc
*/
protected $childResource = array(
'Event',
'Metafield',
);
/**
* Set the ordering type and/or the manual order of products in a smart collection
*
* @param array $params
*
* @return array
*/
public function sortOrder($params)
{
$url = $this->generateUrl($params, 'order');
return $this->put(array(), $url);
}
}
|
Remove Calendar obligation on construction and add unique id. | <?php
namespace Plummer\Calendar;
class Event
{
protected $uniqueId;
protected $name;
protected $dateStart;
protected $dateEnd;
protected $occurrenceDateStart;
protected $calendar;
protected $recurrenceType;
protected function __construct($uniqueId, $name, $dateStart, $dateEnd, $occurrenceDateStart = null)
{
$this->uniqueId = $uniqueId;
$this->name = $name;
$this->dateStart = $dateStart;
$this->dateEnd = $dateEnd;
$this->occurrenceDateStart = $occurrenceDateStart;
}
public static function make($name, $dateStart, $dateEnd, $occurrenceDateStart = null)
{
return new static($name, $dateStart, $dateEnd, $occurrenceDateStart);
}
public function setRecurrenceType(RecurrenceInterface $recurrenceType)
{
$this->recurrenceType = $recurrenceType;
}
public function setCalendar(Calendar &$calendar)
{
$this->calendar = $calendar;
}
} | <?php
namespace Plummer\Calendar;
class Event
{
protected $name;
protected $dateStart;
protected $dateEnd;
protected $occurrenceDateStart;
protected $calendar;
protected $recurrenceType;
protected function __construct($name, $dateStart, $dateEnd, &$calendar, $occurrenceDateStart = null)
{
$this->name = $name;
$this->dateStart = $dateStart;
$this->dateEnd = $dateEnd;
$this->calendar = $calendar;
$this->occurrenceDateStart = $occurrenceDateStart;
}
public static function make($name, $dateStart, $dateEnd, Calendar $calendar = null, $occurrenceDateStart = null)
{
return new static($name, $dateStart, $dateEnd, $calendar, $occurrenceDateStart);
}
public function setRecurrenceType(RecurrenceInterface $recurrenceType)
{
$this->recurrenceType = $recurrenceType;
}
public function setCalendar(Calendar $calendar)
{
$this->calendar = $calendar;
}
} |
Fix a mistake made while merging | from pip._vendor.six.moves.urllib import parse as urllib_parse
class PackageIndex(object):
"""Represents a Package Index and provides easier access to endpoints
"""
def __init__(self, url, file_storage_domain):
super(PackageIndex, self).__init__()
self.url = url
self.netloc = urllib_parse.urlsplit(url).netloc
self.simple_url = self._url_for_path('simple')
self.pypi_url = self._url_for_path('pypi')
# This is part of a temporary hack used to block installs of PyPI
# packages which depend on external urls only necessary until PyPI can
# block such packages themselves
self.file_storage_domain = file_storage_domain
def _url_to_path(self, path):
return urllib_parse.urljoin(self.url, path)
PyPI = PackageIndex('https://pypi.org/', 'files.pythonhosted.org')
TestPyPI = PackageIndex('https://test.pypi.org/', 'test-files.pythonhosted.org')
| from pip._vendor.six.moves.urllib import parse as urllib_parse
class PackageIndex(object):
"""Represents a Package Index and provides easier access to endpoints
"""
def __init__(self, url, file_storage_domain):
super(PackageIndex, self).__init__()
self.url = url
self.netloc = urllib_parse.urlsplit(url).netloc
self.simple_url = self._url_for_path('simple')
self.pypi_url = self._url_for_path('pypi')
# This is part of a temporary hack used to block installs of PyPI
# packages which depend on external urls only necessary until PyPI can
# block such packages themselves
self.file_storage_domain = file_storage_domain
def url_to_path(self, path):
return urllib_parse.urljoin(self.url, path)
PyPI = PackageIndex('https://pypi.org/', 'files.pythonhosted.org')
TestPyPI = PackageIndex('https://test.pypi.org/', 'test-files.pythonhosted.org')
|
Add requests module to installation requirements | from setuptools import setup, find_packages
setup(
name = 'ckanext-archiver',
version = '0.1',
packages = find_packages(),
install_requires = [
'celery>=2.3.3',
'kombu-sqlalchemy>=1.1.0',
'SQLAlchemy>=0.6.6',
'requests==0.6.1'
],
# metadata for upload to PyPI
author = 'Open Knowledge Foundation',
author_email = 'info@okfn.org',
description = 'Archive ckan resources',
long_description = 'Archive ckan resources',
license = 'MIT',
url='http://ckan.org/wiki/Extensions',
download_url = '',
include_package_data = True,
classifiers = [
'Development Status :: 3 - Alpha',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules'
],
entry_points = '''
[paste.paster_command]
archiver = ckanext.archiver.commands:Archiver
'''
)
| from setuptools import setup, find_packages
setup(
name = 'ckanext-archiver',
version = '0.1',
packages = find_packages(),
install_requires = [
'celery>=2.3.3',
'kombu-sqlalchemy>=1.1.0',
'SQLAlchemy>=0.6.6'
],
# metadata for upload to PyPI
author = 'Open Knowledge Foundation',
author_email = 'info@okfn.org',
description = 'Archive ckan resources',
long_description = 'Archive ckan resources',
license = 'MIT',
url='http://ckan.org/wiki/Extensions',
download_url = '',
include_package_data = True,
classifiers = [
'Development Status :: 3 - Alpha',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules'
],
entry_points = '''
[paste.paster_command]
archiver = ckanext.archiver.commands:Archiver
'''
)
|
Refactor python if statement into dictionary | """
Elixir-related Ultisnips snippet helper functions.
NOTE: Changes to this file require restarting Vim!
"""
import re
_DASHES_AND_UNDERSCORES = re.compile("[-_]")
_MODULE_FILEPATH = re.compile(r"lib\/([^\/]+)\/([\w+\/]+)*\/([^\/]+).ex")
_CLOSING_CHARACTERS = {
"(": ")",
"{": "}",
"[": "]",
"\"": "\""
}
def closing_character(tabstop):
"""
Return closing character for a tabstop containing an opening character.
"""
if tabstop:
return _CLOSING_CHARACTERS.get(tabstop[0], "")
return ""
def module_path_match(path, regex=_MODULE_FILEPATH):
"""
Return match data for an Elixir module from a file path.
"""
return re.search(regex, path)
def outer_module_name(path):
"""
Return name for an outer Elixir module from a file path.
"""
outer_module_path = module_path_match(path).group(1)
return to_module_name(outer_module_path)
def to_module_name(string):
"""
Convert string into an Elixir module name
"""
return (
re.sub(_DASHES_AND_UNDERSCORES, " ", string)
.title()
.replace(" ", "")
.replace(".ex", "")
)
| """
Elixir-related Ultisnips snippet helper functions.
NOTE: Changes to this file require restarting Vim!
"""
import re
_DASHES_AND_UNDERSCORES = re.compile("[-_]")
_MODULE_FILEPATH = re.compile(r"lib\/([^\/]+)\/([\w+\/]+)*\/([^\/]+).ex")
def closing_character(tabstop):
"""
Return closing character for a tabstop containing an opening character.
"""
if tabstop.startswith("("):
return ")"
if tabstop.startswith("{"):
return "}"
if tabstop.startswith("["):
return "]"
if tabstop.startswith("\""):
return "\""
return ""
def module_path_match(path, regex=_MODULE_FILEPATH):
"""
Return match data for an Elixir module from a file path.
"""
return re.search(regex, path)
def outer_module_name(path):
"""
Return name for an outer Elixir module from a file path.
"""
outer_module_path = module_path_match(path).group(1)
return to_module_name(outer_module_path)
def to_module_name(string):
"""
Convert string into an Elixir module name
"""
return (
re.sub(_DASHES_AND_UNDERSCORES, " ", string)
.title()
.replace(" ", "")
.replace(".ex", "")
)
|
Fix and update the rfft tests |
import pytest
from ..statistics.rfft_to_fft import rfft_to_fft
from ._testing_data import dataset1
import numpy as np
import numpy.testing as npt
def test_rfft_to_rfft():
comp_rfft = rfft_to_fft(dataset1['moment0'][0])
test_rfft = np.abs(np.fft.rfftn(dataset1['moment0'][0]))
shape2 = test_rfft.shape[-1]
npt.assert_allclose(test_rfft, comp_rfft[:, :shape2])
def test_fft_to_rfft():
comp_rfft = rfft_to_fft(dataset1['moment0'][0])
test_fft = np.abs(np.fft.fftn(dataset1['moment0'][0]))
npt.assert_allclose(test_fft, comp_rfft)
|
from turbustat.statistics.rfft_to_fft import rfft_to_fft
from ._testing_data import dataset1
import numpy as np
import numpy.testing as npt
from unittest import TestCase
class testRFFT(TestCase):
"""docstring for testRFFT"""
def __init__(self):
self.dataset1 = dataset1
self.comp_rfft = rfft_to_fft(self.dataset1)
def rfft_to_rfft(self):
test_rfft = np.abs(np.fft.rfftn(self.dataset1))
shape2 = test_rfft.shape[-1]
npt.assert_allclose(test_rfft, self.comp_rfft[:, :, :shape2+1])
def fft_to_rfft(self):
test_fft = np.abs(np.fft.fftn(self.dataset1))
npt.assert_allclose(test_fft, self.comp_rfft)
|
Add error message for failed data send | /*
* Copyright 2015 Ryan Gilera.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.daytron.revworks.data;
/**
* Collection of error messages.
*
* @author Ryan Gilera
*/
public enum ErrorMsg {
CONSULT_YOUR_ADMIN("Please consult your administrator for help."),
INVALID_INPUT_CAPTION("Invalid input!"),
SIGNIN_FAILED_CAPTION("Sign-In failed!"),
NO_USER_SIGNIN("No login user found. The session has been reset. "),
DATA_FETCH_ERROR("Could not retrieve user data."),
DATA_SEND_ERROR("Could not send data.");
private final String text;
private ErrorMsg(String text) {
this.text = text;
}
public String getText() {
return text;
}
}
| /*
* Copyright 2015 Ryan Gilera.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.daytron.revworks.data;
/**
* Collection of error messages.
*
* @author Ryan Gilera
*/
public enum ErrorMsg {
CONSULT_YOUR_ADMIN("Please consult your administrator for help."),
INVALID_INPUT_CAPTION("Invalid input!"),
SIGNIN_FAILED_CAPTION("Sign-In failed!"),
NO_USER_SIGNIN("No login user found. The session has been reset. "),
DATA_FETCH_ERROR("Could not retrieve user data.");
private final String text;
private ErrorMsg(String text) {
this.text = text;
}
public String getText() {
return text;
}
}
|
Add test getattr for FUSE |
import os
import pytest
from fuse import FUSE, FuseOSError
from diss.fs import id_from_path, DissFilesystem
from .testdata import ID
@pytest.fixture
def fs():
return DissFilesystem()
def test_id_from_path():
assert id_from_path('/blobs/SOMEID') == 'SOMEID'
assert id_from_path('/files/hello.txt') == ID
with pytest.raises(FuseOSError):
id_from_path('/DOES NOT EXIST')
with pytest.raises(FuseOSError):
id_from_path('/files/DOES NOT EXIST')
def test_readdir(fs):
assert fs.readdir('/', None) == ['blobs', 'files']
assert set(fs.readdir('/blobs', None)).issuperset([ID])
assert set(fs.readdir('/files', None)).issuperset(['hello.txt'])
def test_read(fs):
data = fs.read('/files/hello.txt', 100, 0, None)
assert data == b"Hello world !\n\n"
def test_getattr(fs):
assert fs.getattr('/').get('st_size')
assert fs.getattr('/files/hello.txt').get('st_size')
|
import os
import pytest
from fuse import FUSE, FuseOSError
from diss.fs import id_from_path, DissFilesystem
from .testdata import ID
@pytest.fixture
def fs():
return DissFilesystem()
def test_id_from_path():
assert id_from_path('/blobs/SOMEID') == 'SOMEID'
assert id_from_path('/files/hello.txt') == ID
with pytest.raises(FuseOSError):
id_from_path('/DOES NOT EXIST')
with pytest.raises(FuseOSError):
id_from_path('/files/DOES NOT EXIST')
def test_readdir(fs):
assert fs.readdir('/', None) == ['blobs', 'files']
assert set(fs.readdir('/blobs', None)).issuperset([ID])
assert set(fs.readdir('/files', None)).issuperset(['hello.txt'])
def test_read(fs):
data = fs.read('/files/hello.txt', 100, 0, None)
assert data == b"Hello world !\n\n"
|
Prepare release candidate for version 5.0 | <?php
/**
* This file is part of CaptainHook
*
* (c) Sebastian Feldmann <sf@sebastian.feldmann.info>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace CaptainHook\App;
/**
* Class CH
*
* @package CaptainHook
* @author Sebastian Feldmann <sf@sebastian-feldmann.info>
* @link https://github.com/captainhookphp/captainhook
* @since Class available since Release 0.9.0
*/
final class CH
{
public const VERSION = '5.0.0-RC1';
public const RELEASE_DATE = '2019-12-27';
public const CONFIG = 'captainhook.json';
public const COMPOSER_CONFIG = 'captainhook-config';
}
| <?php
/**
* This file is part of CaptainHook
*
* (c) Sebastian Feldmann <sf@sebastian.feldmann.info>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace CaptainHook\App;
/**
* Class CH
*
* @package CaptainHook
* @author Sebastian Feldmann <sf@sebastian-feldmann.info>
* @link https://github.com/captainhookphp/captainhook
* @since Class available since Release 0.9.0
*/
final class CH
{
public const VERSION = '5.0.0';
public const RELEASE_DATE = '2019-12-02';
public const CONFIG = 'captainhook.json';
public const COMPOSER_CONFIG = 'captainhook-config';
}
|
Test auto update to packagist
Signed-off-by: ShaneStevenLei <d08720d67a6f151c69423335bab4d91bf169ca89@outlook.com> | <?php
/*
* This file is part of the php-file-uploader package.
*
* (c) ShaneStevenLei <shanestevenlei@outlook.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace ShaneStevenLei\FileUploader;
use Illuminate\Support\ServiceProvider;
class FileUploaderServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
// Publish config files
$this->publishes([
__DIR__ . '/../config/fileuploader.php' => config_path('fileuploader.php')
]);
$this->publishes([
__DIR__ . '/config/resumable' => base_path('public/resumable'),
]);
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->app->singleton('FileUploader', function ($app) {
return new \ShaneStevenLei\FileUploader\FileUploader();
});
}
}
| <?php
/*
* This file is part of the php-file-uploader package.
*
* (c) ShaneStevenLei <shanestevenlei@outlook.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace ShaneStevenLei\FileUploader;
use Illuminate\Support\ServiceProvider;
class FileUploaderServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
// Publish config files
$this->publishes([
__DIR__ . '/../config/fileuploader.php' => config_path('fileuploader.php')
]);
$this->publishes([
__DIR__ . '/config/resumable' => base_path('public/resumable'),
]);
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->app->singleton('FileUploader', function ($app) {
return new \ShaneStevenLei\FileUploader\FileUploader();
});
}
}
|
Reduce calendar range to 1 day | import request from 'request';
import config from '../config/config';
export default {
getFromConfig(callback) {
let now = new Date();
let later = new Date();
later.setDate(now.getDate() + 1);
let url = 'https://www.googleapis.com/calendar/v3/calendars' +
`/${config.google.calendarId}/events?key=${config.google.apiKey}` +
`&timeMin=${now.toISOString()}&timeMax=${later.toISOString()}` +
`&singleEvents=true&orderBy=startTime`;
request(url, (error, response, body) => {
if (!error && response.statusCode === 200) {
if (body === null) {
console.error(`Error: ${response}`);
} else {
callback(JSON.parse(body).items);
}
} else {
console.error(`Error: ${error}`);
}
});
}
};
| import request from 'request';
import config from '../config/config';
export default {
getFromConfig(callback) {
let now = new Date();
let later = new Date();
later.setDate(now.getDate() + 2);
let url = 'https://www.googleapis.com/calendar/v3/calendars' +
`/${config.google.calendarId}/events?key=${config.google.apiKey}` +
`&timeMin=${now.toISOString()}&timeMax=${later.toISOString()}` +
`&singleEvents=true&orderBy=startTime`;
request(url, (error, response, body) => {
if (!error && response.statusCode === 200) {
if (body === null) {
console.error(`Error: ${response}`);
} else {
callback(JSON.parse(body).items);
}
} else {
console.error(`Error: ${error}`);
}
});
}
};
|
Add completed field to review | from django.db import models
from django.contrib.auth.models import User
class Review(models.Model):
user = models.ForeignKey(User, default=None)
title = models.CharField(max_length=128)
description = models.TextField()
date_created = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True)
completed = models.BooleanField(default=False)
query = models.TextField()
abstract_pool_size = models.IntegerField()
document_pool_size = models.IntegerField()
final_pool_size = models.IntegerField()
class Paper(models.Model):
review = models.ForeignKey(Review)
title = models.CharField(max_length=128)
authors = models.CharField(max_length=128)
abstract = models.TextField()
publish_date = models.DateField()
url = models.URLField()
notes = models.TextField()
ABSTRACT_POOL = 'A'
DOCUMENT_POOL = 'D'
FINAL_POOL = 'F'
REJECTED = 'R'
POOLS = ((ABSTRACT_POOL, 'Abstract pool'),
(DOCUMENT_POOL, 'Document pool'),
(FINAL_POOL, 'Final pool'),
(REJECTED, 'Rejected'))
pool = models.CharField(max_length=1, choices=POOLS, default=ABSTRACT_POOL)
| from django.db import models
from django.contrib.auth.models import User
class Review(models.Model):
user = models.ForeignKey(User, default=None)
title = models.CharField(max_length=128)
description = models.TextField()
date_created = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True)
query = models.TextField()
abstract_pool_size = models.IntegerField()
document_pool_size = models.IntegerField()
final_pool_size = models.IntegerField()
class Paper(models.Model):
review = models.ForeignKey(Review)
title = models.CharField(max_length=128)
authors = models.CharField(max_length=128)
abstract = models.TextField()
publish_date = models.DateField()
url = models.URLField()
notes = models.TextField()
ABSTRACT_POOL = 'A'
DOCUMENT_POOL = 'D'
FINAL_POOL = 'F'
REJECTED = 'R'
POOLS = ((ABSTRACT_POOL, 'Abstract pool'),
(DOCUMENT_POOL, 'Document pool'),
(FINAL_POOL, 'Final pool'),
(REJECTED, 'Rejected'))
pool = models.CharField(max_length=1, choices=POOLS, default=ABSTRACT_POOL)
|
Add log in user receive. | package com.raillearn;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
public class TripController {
@Autowired
TripRepository tripRepository;
@RequestMapping(value = "/trips", method = RequestMethod.GET)
public List<Trip> getTrips() {
return tripRepository.findAll();
}
@RequestMapping(value = "/trips", method = RequestMethod.POST)
public Trip postTrip(@RequestBody Trip trip) {
return tripRepository.save(trip);
}
@RequestMapping(value = "/trips/{id}/join", method = RequestMethod.POST)
public Trip postTrip(@PathVariable long id) {
return tripRepository.findOne(id);
}
@RequestMapping(value = "/user/login", method = RequestMethod.POST)
public String logInUser(@RequestParam String token) {
return token;
}
}
| package com.raillearn;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
public class TripController {
@Autowired
TripRepository tripRepository;
@RequestMapping(value = "/trips", method = RequestMethod.GET)
public List<Trip> getTrips() {
return tripRepository.findAll();
}
@RequestMapping(value = "/trips", method = RequestMethod.POST)
public Trip postTrip(@RequestBody Trip trip) {
return tripRepository.save(trip);
}
@RequestMapping(value = "/trips/{id}/join", method = RequestMethod.POST)
public Trip postTrip(@PathVariable long id) {
return tripRepository.findOne(id);
}
}
|
Add updated description for Racing | <?php
$page_title = 'Home';
$site_title = 'Racing';
$site_index = '/racing';
include '../header.php';
?>
<!-- Content Row -->
<div class="well card-1">
<div class="row">
<!-- Content Column -->
<div class="col-md-8 text-dark col-md-offset-2 text-dark">
<h2>Racing Team</h2>
<p> IEEE Racing builds an electric go-kart that competes in the Purdue evGrandPrix that takes place annually at the Indianapolis Motor Speedway. We are looking for members to redesign electrical systems, get sponsors and build industry contacts, improve safety features, and most importantly, have a great time learning about electric vehicle technology. <br>
Team meetings are once a week in the off-season and twice a week during race season. Meetings are broken into planning time where we discuss our project and budget and build sessions where members get hands-on with the go-kart. <br>
All majors are welcome!!
</p>
<p>Contact <a href="mailto:efiguer@purdue.edu">Erick Figueroa</a> for more details.</p>
</div>
</div>
</div>
<!-- /.well -->
<?php include '../footer.php'; ?>
| <?php
$page_title = 'Home';
$site_title = 'Racing';
$site_index = '/racing';
include '../header.php';
?>
<!-- Content Row -->
<div class="well card-1">
<div class="row">
<!-- Content Column -->
<div class="col-md-8 text-dark col-md-offset-2 text-dark">
<h2>Racing Team</h2>
<p> The IEEE Racing Team builds an electric go-kart to compete in evGrandPrix. In addition to go-karts, the team undertakes small projects such as building an off-road buggy to explore the field of electric motorsports even further.</p>
<p>Contact <a href="mailto:efiguer@purdue.edu">Erick Figueroa</a> for more details.</p>
</div>
</div>
</div>
<!-- /.well -->
<?php include '../footer.php'; ?>
|
Update Filtered to Selected object key | export function load(files) {
return {
type: 'FILES_DATA_LOAD',
payload: files.map(file => {
return {
id: file.Id,
newName: file.NewName,
originalName: file.OriginalName,
size: file.Size,
type: file.Type,
isSelected: file.Selected,
};
}),
};
}
export function sort(type, direction, field) {
return {
type: 'FILES_DATA_SORT',
payload: {
type,
direction,
field,
},
};
}
export function setPath(path) {
return {
type: 'FILES_SET_PATH',
payload: path,
};
}
export function setCount(count) {
return {
type: 'FILES_COUNT_UPDATE',
payload: count,
};
}
export function toggleIsSelected(id) {
return {
type: 'FILE_IS_SELECTED_TOGGLE',
payload: id,
};
}
export function deleteFile(id) {
return {
type: 'FILE_DATA_DELETE',
payload: id,
};
}
export function updateLoader(isLoading, message) {
return {
type: 'FILES_LOADER_UPDATE',
payload: {
isLoading,
message,
},
};
}
export function clearData() {
return {
type: 'FILES_CLEAR_DATA',
};
}
| export function load(files) {
return {
type: 'FILES_DATA_LOAD',
payload: files.map(file => {
return {
id: file.Id,
newName: file.NewName,
originalName: file.OriginalName,
size: file.Size,
type: file.Type,
isSelected: file.Filtered,
};
}),
};
}
export function sort(type, direction, field) {
return {
type: 'FILES_DATA_SORT',
payload: {
type,
direction,
field,
},
};
}
export function setPath(path) {
return {
type: 'FILES_SET_PATH',
payload: path,
};
}
export function setCount(count) {
return {
type: 'FILES_COUNT_UPDATE',
payload: count,
};
}
export function toggleIsSelected(id) {
return {
type: 'FILE_IS_SELECTED_TOGGLE',
payload: id,
};
}
export function deleteFile(id) {
return {
type: 'FILE_DATA_DELETE',
payload: id,
};
}
export function updateLoader(isLoading, message) {
return {
type: 'FILES_LOADER_UPDATE',
payload: {
isLoading,
message,
},
};
}
export function clearData() {
return {
type: 'FILES_CLEAR_DATA',
};
}
|
Use collect_libs for finding libs | from conans import ConanFile, CMake
class SocketwConan(ConanFile):
name = "SocketW"
version = "3.10.36"
license = "GNU Lesser General Public License v2.1"
url = "https://github.com/RigsOfRods/socketw/issues"
description = "SocketW is a library which provides cross-platform socket abstraction"
settings = "os", "compiler", "build_type", "arch"
#options = {"shared": [True, False]}
#default_options = "shared=False"
generators = "cmake"
exports_sources = "src/*", "CMakeLists.txt", "LICENSE", "README"
def requirements(self):
self.requires.add('OpenSSL/1.0.2@conan/stable')
def build(self):
cmake = CMake(self)
cmake.configure()
cmake.build()
def package(self):
cmake = CMake(self)
cmake.install()
def package_info(self):
self.cpp_info.libs = tools.collect_libs(self)
| from conans import ConanFile, CMake
class SocketwConan(ConanFile):
name = "SocketW"
version = "3.10.36"
license = "GNU Lesser General Public License v2.1"
url = "https://github.com/RigsOfRods/socketw/issues"
description = "SocketW is a library which provides cross-platform socket abstraction"
settings = "os", "compiler", "build_type", "arch"
#options = {"shared": [True, False]}
#default_options = "shared=False"
generators = "cmake"
exports_sources = "src/*", "CMakeLists.txt", "LICENSE", "README"
def requirements(self):
self.requires.add('OpenSSL/1.0.2@conan/stable')
def build(self):
cmake = CMake(self)
cmake.configure()
cmake.build()
def package(self):
cmake = CMake(self)
cmake.install()
def package_info(self):
self.cpp_info.libs = ["SocketW"]
|
Make /dashboard the home route | <?php
/*
|--------------------------------------------------------------------------
| Application Routers
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/
Route::group(['before' => 'Sentinel\auth'], function()
{
Route::resource('projects', 'ProjectsController');
Route::resource('tickets', 'TicketsController');
Route::resource('invoices', 'InvoicesController');
Route::post('tickets/{id}/reply', 'TicketsController@reply');
Route::get('/', ['as' => 'index', 'uses' => 'HomeController@index']);
# Override Sentinel's Default user routes with our own filter requirement
Route::get('/users/{id}', ['as' => 'sl_user.show', 'uses' => 'SimpleLance\UserController@show'])->where('id', '[0-9]+');
Route::get('dashboard', ['as' => 'home', 'uses' => 'DashboardController@index']);
});
Route::group(['before' => 'Sentinel\inGroup:Admins'], function()
{
Route::resource('priorities', 'PrioritiesController', ['except' => ['show']]);
Route::resource('statuses', 'StatusesController', ['except' => ['show']]);
});
| <?php
/*
|--------------------------------------------------------------------------
| Application Routers
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/
Route::group(['before' => 'Sentinel\auth'], function()
{
Route::resource('projects', 'ProjectsController');
Route::resource('tickets', 'TicketsController');
Route::resource('invoices', 'InvoicesController');
Route::post('tickets/{id}/reply', 'TicketsController@reply');
Route::get('/', ['as' => 'home', 'uses' => 'HomeController@index']);
# Override Sentinel's Default user routes with our own filter requirement
Route::get('/users/{id}', ['as' => 'sl_user.show', 'uses' => 'SimpleLance\UserController@show'])->where('id', '[0-9]+');
Route::get('dashboard', ['as' => 'dashboard', 'uses' => 'DashboardController@index']);
});
Route::group(['before' => 'Sentinel\inGroup:Admins'], function()
{
Route::resource('priorities', 'PrioritiesController', ['except' => ['show']]);
Route::resource('statuses', 'StatusesController', ['except' => ['show']]);
});
|
Fix category reloadAll and removeAll | const Collection = require('discord.js').Collection;
class Category {
/**
* Creates a new command category.
* @param {string} id - ID of the category.
*/
constructor(id){
/**
* ID of the category.
* @type {string}
*/
this.id = id;
/**
* Collection of commands, mapped by ID to Command.
* @type {Collection.<string, Command>}
*/
this.commands = new Collection();
}
/**
* Reloads all commands in this category.
*/
reloadAll(){
Array.from(this.commands.values()).forEach(command => command.reload());
}
/**
* Removes all commands in this category.
*/
removeAll(){
Array.from(this.commands.values()).forEach(command => command.remove());
}
/**
* Gets the first alias of each command.
* @return {string[]}
*/
list(){
return this.commands.map(command => command.aliases[0]);
}
/**
* Returns the ID.
* @returns {string}
*/
toString(){
return this.id;
}
}
module.exports = Category; | const Collection = require('discord.js').Collection;
class Category {
/**
* Creates a new command category.
* @param {string} id - ID of the category.
*/
constructor(id){
/**
* ID of the category.
* @type {string}
*/
this.id = id;
/**
* Collection of commands, mapped by ID to Command.
* @type {Collection.<string, Command>}
*/
this.commands = new Collection();
}
/**
* Reloads all commands in this category.
*/
reloadAll(){
this.commands.forEach(command => command.reload());
}
/**
* Removes all commands in this category.
*/
removeAll(){
this.commands.forEach(command => command.remove());
}
/**
* Gets the first alias of each command.
* @return {string[]}
*/
list(){
return this.commands.map(command => command.aliases[0]);
}
/**
* Returns the ID.
* @returns {string}
*/
toString(){
return this.id;
}
}
module.exports = Category; |
Add badge state to approval list | <?php
namespace AppBundle\Services\Approvals\Providers;
use AppBundle\Entity\BadgeHolder;
use AppBundle\Services\Approvals\ApprovalQueueItem;
use AppBundle\Services\Approvals\ApprovalQueueProviderInterface;
use AppBundle\Services\Enum\BadgeState;
use Doctrine\Bundle\DoctrineBundle\Registry;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class BadgeApprovalProvider implements ApprovalQueueProviderInterface
{
/**
* @param Registry $doctrine
* @param UrlGeneratorInterface $url
*
* @return ApprovalQueueItem[]
*/
function getItems(Registry $doctrine, UrlGeneratorInterface $url)
{
$repository = $doctrine->getRepository('AppBundle:BadgeHolder');
$badges = $repository->findByIncomplete()->getQuery()->getResult();
return array_map(function (BadgeHolder $badge) use ($url) {
$name = (string)$badge . ' - ' . BadgeState::$choices[$badge->getState()];
return new ApprovalQueueItem('badge', $name, $url->generate('badge_detail', ['id' => $badge->getBadge()->getId()]), $badge);
}, $badges);
}
} | <?php
namespace AppBundle\Services\Approvals\Providers;
use AppBundle\Entity\BadgeHolder;
use AppBundle\Services\Approvals\ApprovalQueueItem;
use AppBundle\Services\Approvals\ApprovalQueueProviderInterface;
use Doctrine\Bundle\DoctrineBundle\Registry;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class BadgeApprovalProvider implements ApprovalQueueProviderInterface
{
/**
* @param Registry $doctrine
* @param UrlGeneratorInterface $url
*
* @return ApprovalQueueItem[]
*/
function getItems(Registry $doctrine, UrlGeneratorInterface $url)
{
$repository = $doctrine->getRepository('AppBundle:BadgeHolder');
$badges = $repository->findByIncomplete()->getQuery()->getResult();
return array_map(function (BadgeHolder $badge) use ($url) {
return new ApprovalQueueItem('badge', (string)$badge, $url->generate('badge_detail', ['id' => $badge->getBadge()->getId()]), $badge);
}, $badges);
}
} |
:fire: Remove check for `null` in duplicate storage decorator | <?php
/**
* Vainyl
*
* PHP Version 7
*
* @package Core
* @license https://opensource.org/licenses/MIT MIT License
* @link https://vainyl.com
*/
declare(strict_types=1);
namespace Vainyl\Core\Storage\Decorator;
use Vainyl\Core\Exception\DuplicateOffsetException;
/**
* Class DuplicateStorageDecorator
*
* @author Taras P. Girnyk <taras.p.gyrnik@gmail.com>
*/
class DuplicateStorageDecorator extends AbstractStorageDecorator
{
/**
* @inheritDoc
*/
public function offsetSet($offset, $value)
{
if ($this->offsetExists($offset)) {
throw new DuplicateOffsetException($this, $offset, $value, $this->offsetGet($offset));
}
parent::offsetSet($offset, $value);
}
}
| <?php
/**
* Vainyl
*
* PHP Version 7
*
* @package Core
* @license https://opensource.org/licenses/MIT MIT License
* @link https://vainyl.com
*/
declare(strict_types=1);
namespace Vainyl\Core\Storage\Decorator;
use Vainyl\Core\Exception\DuplicateOffsetException;
/**
* Class DuplicateStorageDecorator
*
* @author Taras P. Girnyk <taras.p.gyrnik@gmail.com>
*/
class DuplicateStorageDecorator extends AbstractStorageDecorator
{
/**
* @inheritDoc
*/
public function offsetSet($offset, $value)
{
if (null !== $offset && $this->offsetExists($offset)) {
throw new DuplicateOffsetException($this, $offset, $value, $this->offsetGet($offset));
}
parent::offsetSet($offset, $value);
}
}
|
Fix typo in author FactorLibre | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Hugo Santos
# Copyright 2015 FactorLibre
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'Sale Order Add Variants',
'summary': 'Add variants from template into sale order',
'version': '0.1',
'author': 'FactorLibre,Odoo Community Association (OCA)',
'category': 'Sale',
'license': 'AGPL-3',
'website': 'http://factorlibre.com',
'depends': [
'sale'
],
'demo': [],
'data': [
'security/sale_order_add_variants_security.xml',
'view/sale_add_variants_view.xml',
'view/sale_view.xml',
'view/res_config_view.xml'
],
'installable': True
}
| # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Hugo Santos
# Copyright 2015 FactorLibre
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'Sale Order Add Variants',
'summary': 'Add variants from template into sale order',
'version': '0.1',
'author': 'Factorlibre,Odoo Community Association (OCA)',
'category': 'Sale',
'license': 'AGPL-3',
'website': 'http://factorlibre.com',
'depends': [
'sale'
],
'demo': [],
'data': [
'security/sale_order_add_variants_security.xml',
'view/sale_add_variants_view.xml',
'view/sale_view.xml',
'view/res_config_view.xml'
],
'installable': True
}
|
Rename Page's title to name in the Form entity | <?php
namespace Kunstmaan\NodeBundle\Form;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\AbstractType;
/**
* PageAdminType
*/
class PageAdminType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('id', 'hidden');
$builder->add('title', null, array('label' => 'Name'));
$builder->add('pageTitle');
}
/**
* @param array $options
*
* @return array
*/
public function getDefaultOptions(array $options)
{
return array(
'data_class' => 'Kunstmaan\NodeBundle\Entity\AbstractPage',
);
}
/**
* @return string
*/
public function getName()
{
return 'page';
}
}
| <?php
namespace Kunstmaan\NodeBundle\Form;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\AbstractType;
/**
* PageAdminType
*/
class PageAdminType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('id', 'hidden');
$builder->add('title');
$builder->add('pageTitle');
}
/**
* @param array $options
*
* @return array
*/
public function getDefaultOptions(array $options)
{
return array(
'data_class' => 'Kunstmaan\NodeBundle\Entity\AbstractPage',
);
}
/**
* @return string
*/
public function getName()
{
return 'page';
}
}
|
Add login and forgot links in the user register view
Make is easy for users to get to the login and forgot view
if they already registered.
Signed-off-by: Marc Jones <bb1304e98184a66f7e15848bfbd0ff1c09583089@gmail.com> | @extends('app')
@section('content')
<h1>Register an Account</h1>
<hr>
{!! Form::open() !!}
@include('partials/form/text', ['name' => 'name', 'label' => 'Username', 'placeholder' => 'Your login name'])
@include('partials/form/text', ['name' => 'email', 'label' => 'Email address', 'placeholder' => 'Your email'])
@include('partials/form/password', ['name' => 'password', 'label' => 'Password', 'placeholder' => 'A strong password'])
@include('partials/form/password', ['name' => 'password_confirmation', 'label' => 'Confirm Password', 'placeholder' => 'Type your password again'])
<button type="submit" class="btn btn-primary">Submit</button>
{!! Form::close() !!}
<hr>
<p>
Already registered? <a href="/login/">Login Here!</a><br>
Forgot your password? <a href="/forgot/">Reset it!</a>
<p>
@endsection
| @extends('app')
@section('content')
<h1>Register an Account</h1>
<hr>
{!! Form::open() !!}
@include('partials/form/text', ['name' => 'name', 'label' => 'Username', 'placeholder' => 'Your login name'])
@include('partials/form/text', ['name' => 'email', 'label' => 'Email address', 'placeholder' => 'Your email'])
@include('partials/form/password', ['name' => 'password', 'label' => 'Password', 'placeholder' => 'A strong password'])
@include('partials/form/password', ['name' => 'password_confirmation', 'label' => 'Confirm Password', 'placeholder' => 'Type your password again'])
<button type="submit" class="btn btn-primary">Submit</button>
{!! Form::close() !!}
@endsection
|
Allow characters/length to be overriden in the generator. | <?php
namespace Nubs\PwMan;
use RandomLib\Factory as RandomFactory;
/**
* Generate random passwords.
*/
class PasswordGenerator
{
/** @type string The characters to use in the password. */
private $_characters;
/** @type int The length of the password. */
private $_length;
/**
* Construct the password generator with the desired settings.
*
* @api
* @param string $characters The characters to use in the password.
* @param int $length The length of the password to generate.
*/
public function __construct($characters = null, $length = 32)
{
$this->_characters = $characters ?: join(range(chr(32), chr(126)));
$this->_length = $length;
}
/**
* Generate a password.
*
* @api
* @return string The random password.
*/
public function __invoke()
{
$generator = (new RandomFactory())->getMediumStrengthGenerator();
return $generator->generateString($this->_length, $this->_characters);
}
}
| <?php
namespace Nubs\PwMan;
use RandomLib\Factory as RandomFactory;
/**
* Generate random passwords.
*/
class PasswordGenerator
{
/** @type string The characters to use in the password. */
private $_characters;
/** @type int The length of the password. */
private $_length;
/**
* Construct the password generator with the desired settings.
*
* @api
*/
public function __construct()
{
$this->_characters = join(range(chr(32), chr(126)));
$this->_length = 32;
}
/**
* Generate a password.
*
* @api
* @return string The random password.
*/
public function __invoke()
{
$generator = (new RandomFactory())->getMediumStrengthGenerator();
return $generator->generateString($this->_length, $this->_characters);
}
}
|
Use correct props on ShufflingCardGrid | import React, { Component } from 'react';
import uuid from 'uuid';
import './store/reducers';
import CARD_TEXTS from './store/values.json';
import ShufflingCardGrid from './components/ShufflingCardGrid';
const CARDS = CARD_TEXTS.map(text => ({
key: uuid.v4(),
text,
accepted: false,
rejected: false
}));
class App extends Component {
constructor(props, context) {
super(props, context);
this.state = {
windowWidth: window.innerWidth
};
}
handleResize = () => {
this.setState({ windowWidth: window.innerWidth });
}
componentDidMount() {
window.addEventListener('resize', this.handleResize);
}
render() {
const totalWidth = Math.min(this.state.windowWidth, 900);
const cardWidth = 200;
return (
<div className="App">
<ShufflingCardGrid
width={totalWidth}
itemWidth={cardWidth}
itemHeight={160}
cards={CARDS}
/>
</div>
);
}
}
export default App;
| import React, { Component } from 'react';
import uuid from 'uuid';
import './store/reducers';
import CARD_TEXTS from './store/values.json';
import ShufflingCardGrid from './components/ShufflingCardGrid';
const CARDS = CARD_TEXTS.map(text => ({
key: uuid.v4(),
text,
accepted: false,
rejected: false
}));
class App extends Component {
constructor(props, context) {
super(props, context);
this.state = {
windowWidth: window.innerWidth
};
}
handleResize = () => {
this.setState({ windowWidth: window.innerWidth });
}
componentDidMount() {
window.addEventListener('resize', this.handleResize);
}
render() {
const totalWidth = Math.min(this.state.windowWidth, 900);
const cardWidth = 200;
return (
<div className="App">
<ShufflingCardGrid
width={totalWidth}
cardWidth={cardWidth}
cards={CARDS}
/>
</div>
);
}
}
export default App;
|
Remove @Override annotation to prevent compilation issue on old Java compiler
Change-Id: I9ed0e8423f5ae028294d773799979865e0dd4e8f | package vtk.rendering;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
/**
* This class implement vtkEventInterceptor with no event interception at all.
*
* @see {@link MouseMotionListener} {@link MouseListener} {@link MouseWheelListener}
* {@link KeyListener}
*
* @author Sebastien Jourdain - sebastien.jourdain@kitware.com, Kitware Inc 2013
*/
public class vtkAbstractEventInterceptor implements vtkEventInterceptor {
public boolean keyPressed(KeyEvent e) {
return false;
}
public boolean keyReleased(KeyEvent e) {
return false;
}
public boolean keyTyped(KeyEvent e) {
return false;
}
public boolean mouseDragged(MouseEvent e) {
return false;
}
public boolean mouseMoved(MouseEvent e) {
return false;
}
public boolean mouseClicked(MouseEvent e) {
return false;
}
public boolean mouseEntered(MouseEvent e) {
return false;
}
public boolean mouseExited(MouseEvent e) {
return false;
}
public boolean mousePressed(MouseEvent e) {
return false;
}
public boolean mouseReleased(MouseEvent e) {
return false;
}
public boolean mouseWheelMoved(MouseWheelEvent e) {
return false;
}
}
| package vtk.rendering;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
/**
* This class implement vtkEventInterceptor with no event interception at all.
*
* @see {@link MouseMotionListener} {@link MouseListener} {@link MouseWheelListener}
* {@link KeyListener}
*
* @author Sebastien Jourdain - sebastien.jourdain@kitware.com, Kitware Inc 2013
*/
public class vtkAbstractEventInterceptor implements vtkEventInterceptor {
@Override
public boolean keyPressed(KeyEvent e) {
return false;
}
@Override
public boolean keyReleased(KeyEvent e) {
return false;
}
@Override
public boolean keyTyped(KeyEvent e) {
return false;
}
@Override
public boolean mouseDragged(MouseEvent e) {
return false;
}
@Override
public boolean mouseMoved(MouseEvent e) {
return false;
}
@Override
public boolean mouseClicked(MouseEvent e) {
return false;
}
@Override
public boolean mouseEntered(MouseEvent e) {
return false;
}
@Override
public boolean mouseExited(MouseEvent e) {
return false;
}
@Override
public boolean mousePressed(MouseEvent e) {
return false;
}
@Override
public boolean mouseReleased(MouseEvent e) {
return false;
}
@Override
public boolean mouseWheelMoved(MouseWheelEvent e) {
return false;
}
}
|
Fix logging bug: mkdir -> makedirs. | import errno
import os
import logging
def _mkdir_p(path):
ab_path = path
if not os.path.isabs(ab_path):
curr_dir = os.getcwd()
ab_path = os.path.join(curr_dir, path)
try:
os.makedirs(ab_path)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(ab_path):
pass
else:
raise
def log_file_handler(app_name, log_level, log_dir):
app_log_dir = os.path.join(log_dir, app_name.lower())
_mkdir_p(app_log_dir)
log_name = "{}.log".format(log_level)
log_path = os.path.join(app_log_dir, log_name)
file_handler = logging.FileHandler(log_path)
file_handler.setLevel(logging.ERROR)
formatter = logging.Formatter(
fmt="%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]",
datefmt="%Y-%m-%d %H:%M:%S")
file_handler.setFormatter(formatter)
return file_handler
| import errno
import os
import logging
def _mkdir_p(path):
try:
os.mkdir(path)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def log_file_handler(app_name, log_level, log_dir):
app_log_dir = os.path.join(log_dir, app_name.lower())
_mkdir_p(app_log_dir)
log_name = "{}.log".format(log_level)
log_path = os.path.join(app_log_dir, log_name)
file_handler = logging.FileHandler(log_path)
file_handler.setLevel(logging.ERROR)
formatter = logging.Formatter(
fmt="%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]",
datefmt="%Y-%m-%d %H:%M:%S")
file_handler.setFormatter(formatter)
return file_handler
|
Move wp-i18n and wp-dom-ready into src directory | /* global require, module, __dirname */
const path = require( 'path' );
module.exports = {
entry: {
'./assets/js/amp-blocks-compiled': './blocks/index.js',
'./assets/js/wp-i18n-compiled': './assets/src/wp-i18n',
'./assets/js/wp-dom-ready-compiled': './assets/src/wp-dom-ready',
'./assets/js/amp-block-editor-toggle-compiled': './assets/src/amp-block-editor-toggle',
'./assets/js/amp-validation-detail-toggle-compiled': './assets/src/amp-validation-detail-toggle',
'./assets/js/amp-validation-single-error-url-details-compiled': './assets/src/amp-validation-single-error-url-details'
},
output: {
path: path.resolve( __dirname ),
filename: '[name].js'
},
externals: {
// Make localized data importable.
'amp-validation-i18n': 'ampValidationI18n'
},
devtool: 'cheap-eval-source-map',
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader'
}
}
]
}
};
| /* global require, module, __dirname */
const path = require( 'path' );
module.exports = {
entry: {
'./assets/js/amp-blocks-compiled': './blocks/index.js',
'./assets/js/wp-i18n-compiled': './assets/js/wp-i18n',
'./assets/js/wp-dom-ready-compiled': './assets/js/wp-dom-ready',
'./assets/js/amp-block-editor-toggle-compiled': './assets/src/amp-block-editor-toggle',
'./assets/js/amp-validation-detail-toggle-compiled': './assets/src/amp-validation-detail-toggle',
'./assets/js/amp-validation-single-error-url-details-compiled': './assets/src/amp-validation-single-error-url-details'
},
output: {
path: path.resolve( __dirname ),
filename: '[name].js'
},
externals: {
// Make localized data importable.
'amp-validation-i18n': 'ampValidationI18n'
},
devtool: 'cheap-eval-source-map',
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader'
}
}
]
}
};
|
Fix error message when svgexport is not installed | var _ = require("lodash");
var Q = require("q");
var fs = require("./fs");
var exec = require('child_process').exec;
var request = require("request");
var links = require("./links");
// Convert a svg file
var convertSVGFile = function(source, dest, options) {
var d = Q.defer();
options = _.defaults(options || {}, {
});
var command = "svgexport "+source+" "+dest;
var child = exec(command, function (error, stdout, stderr) {
if (error) {
if (error.code == 127) error = new Error("Need to install 'svgexport' using 'npm install svgexport -g'");
return d.reject(error);
}
d.resolve();
});
return d.promise;
};
// Convert a svg file or url
var convertSVG = function(source, dest, options) {
if (!links.isExternal(source)) return convertSVGFile(source, dest, options);
return fs.tmp.file({ postfix: '.svg' })
// Download file
.then(function(tmpfile) {
return fs.writeStream(tmpfile, request(source))
.thenResolve(tmpfile);
})
.then(function(tmpfile) {
return convertSVGFile(tmpfile, dest, options);
});
};
module.exports = {
convertSVG: convertSVG,
INVALID: [".svg"]
};
| var _ = require("lodash");
var Q = require("q");
var fs = require("./fs");
var exec = require('child_process').exec;
var request = require("request");
var links = require("./links");
// Convert a svg file
var convertSVGFile = function(source, dest, options) {
var d = Q.defer();
options = _.defaults(options || {}, {
});
var command = "svgexport "+source+" "+dest;
var child = exec(command, function (error, stdout, stderr) {
if (error) {
if (error.code == "ENOENT") error = new Error("Need to install 'svgexport' using 'npm install svgexport -g'");
return d.reject(error);
}
d.resolve();
});
return d.promise;
};
// Convert a svg file or url
var convertSVG = function(source, dest, options) {
if (!links.isExternal(source)) return convertSVGFile(source, dest, options);
return fs.tmp.file({ postfix: '.svg' })
// Download file
.then(function(tmpfile) {
return fs.writeStream(tmpfile, request(source))
.thenResolve(tmpfile);
})
.then(function(tmpfile) {
return convertSVGFile(tmpfile, dest, options);
});
};
module.exports = {
convertSVG: convertSVG,
INVALID: [".svg"]
};
|
Make the paths not relative, so tests can be run from anywhere. | # -*- coding: utf-8 -*-
import os, os.path
import sys
import unittest
from macrotest import JSONSpecMacroTestCaseFactory
def JSONTestCaseLoader(tests_path, recursive=False):
"""
Load JSON specifications for Jinja2 macro test cases from the given
path and returns the resulting test classes.
This function will create a MacroTestCase subclass (using
JSONSpecMacrosTestCaseFactory) for each JSON file in the given path.
If `recursive` is True, it will also look in subdirectories. This is
not yet supported.
"""
path = os.path.abspath(os.path.join(os.path.dirname( __file__ ), tests_path))
json_files = [f for f in os.listdir(path) if f.endswith('.json')]
for json_file in json_files:
# Create a camelcased name for the test. This is a minor thing, but I
# think it's nice.
name, extension = os.path.splitext(json_file)
class_name = ''.join(x for x in name.title() if x not in ' _-') + 'TestCase'
# Get the full path to the file and create a test class
json_file_path = os.path.join(path, json_file)
test_class = JSONSpecMacroTestCaseFactory(class_name, json_file_path)
# Add the test class to globals() so that unittest.main() picks it up
globals()[class_name] = test_class
if __name__ == '__main__':
JSONTestCaseLoader('./tests/')
unittest.main()
| # -*- coding: utf-8 -*-
import os, os.path
import sys
import unittest
from macrotest import JSONSpecMacroTestCaseFactory
def JSONTestCaseLoader(tests_path, recursive=False):
"""
Load JSON specifications for Jinja2 macro test cases from the given
path and returns the resulting test classes.
This function will create a MacroTestCase subclass (using
JSONSpecMacrosTestCaseFactory) for each JSON file in the given path.
If `recursive` is True, it will also look in subdirectories. This is
not yet supported.
"""
json_files = [f for f in os.listdir(tests_path) if f.endswith('.json')]
for json_file in json_files:
# Create a camelcased name for the test. This is a minor thing, but I
# think it's nice.
name, extension = os.path.splitext(json_file)
class_name = ''.join(x for x in name.title() if x not in ' _-') + 'TestCase'
# Get the full path to the file and create a test class
json_file_path = os.path.join(tests_path, json_file)
test_class = JSONSpecMacroTestCaseFactory(class_name, json_file_path)
# Add the test class to globals() so that unittest.main() picks it up
globals()[class_name] = test_class
if __name__ == '__main__':
JSONTestCaseLoader('./tests/')
unittest.main()
|
Change contract detail data type from string to number | import { runAndGetResult, expectResultTypes, parts } from '../tools';
describe('After Purchase Blocks', () => {
let result;
beforeAll(done => {
runAndGetResult(
undefined,
`
${parts.waitToPurchase}
${parts.waitToSell}
result.isWin = Bot.isResult('win');
result.detail = Bot.readDetails(1);
`
).then(v => {
result = v;
done();
});
});
it('After purchase api', () => {
expectResultTypes(result, [
'boolean', // is result win
'number', // statement
]);
});
});
| import { runAndGetResult, expectResultTypes, parts } from '../tools';
describe('After Purchase Blocks', () => {
let result;
beforeAll(done => {
runAndGetResult(
undefined,
`
${parts.waitToPurchase}
${parts.waitToSell}
result.isWin = Bot.isResult('win');
result.detail = Bot.readDetails(1);
`
).then(v => {
result = v;
done();
});
});
it('After purchase api', () => {
expectResultTypes(result, [
'boolean', // is result win
'string', // statement
]);
});
});
|
Update to new dataseed URL | define(['module', 'jquery', 'underscore', 'lib/sync', 'dataseed/views/dataset'], function(module, $, _, sync, DatasetEmbedView) {
'use strict';
// Override Backbone sync
Backbone.sync = sync;
// Get base URL
var config = module.config(),
base_url = (_.isUndefined(config['BASE_URL'])) ? 'https://getdataseed.com' : config['BASE_URL'];
// Setup external API access
var _ajax = $.ajax;
$.extend({
ajax: function(options) {
options['url'] = base_url + options['url'];
return _ajax.call(this, options);
}
});
});
| define(['module', 'jquery', 'underscore', 'lib/sync', 'dataseed/views/dataset'], function(module, $, _, sync, DatasetEmbedView) {
'use strict';
// Override Backbone sync
Backbone.sync = sync;
// Get base URL
var config = module.config(),
base_url = (_.isUndefined(config['BASE_URL'])) ? 'http://dataseedapp.com' : config['BASE_URL'];
// Setup external API access
var _ajax = $.ajax;
$.extend({
ajax: function(options) {
options['url'] = base_url + options['url'];
return _ajax.call(this, options);
}
});
});
|
Tidy up info a little for the PluginModule popup edit form
git-svn-id: a7fabbc6a7c54ea5c67cbd16bd322330fd10cc35@40402 b456876b-0849-0410-b77d-98878d47e9d5 | <?php
// (c) Copyright 2002-2012 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$
//this script may only be included - so its better to die if called directly.
if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) {
header("location: index.php");
exit;
}
function module_top_files_info()
{
return array(
'name' => tra('Top Files'),
'description' => tra('Displays the specified number of files with links to them, starting with the one with most hits.'),
'prefs' => array('feature_file_galleries'),
'params' => array(),
'common_params' => array('nonums', 'rows')
);
}
function module_top_files($mod_reference, $module_params)
{
global $smarty;
$filegallib = TikiLib::lib('filegal');
$ranking = $filegallib->list_files(0, $mod_reference["rows"], 'hits_desc', '');
$smarty->assign('modTopFiles', $ranking["data"]);
}
| <?php
// (c) Copyright 2002-2012 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$
//this script may only be included - so its better to die if called directly.
if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) {
header("location: index.php");
exit;
}
function module_top_files_info()
{
return array(
'name' => tra('Top files'),
'description' => tra('Displays the specified number of files with links to them, starting with the one with most hits.'),
'prefs' => array('feature_file_galleries'),
'params' => array(),
'common_params' => array('nonums', 'rows')
);
}
function module_top_files($mod_reference, $module_params)
{
global $smarty;
$filegallib = TikiLib::lib('filegal');
$ranking = $filegallib->list_files(0, $mod_reference["rows"], 'hits_desc', '');
$smarty->assign('modTopFiles', $ranking["data"]);
}
|
Fix exception message if app path is invalid | from importlib import import_module
from django.apps import apps
from django.core.exceptions import ImproperlyConfigured
def get_callable(func_or_path):
"""
Receives a dotted path or a callable, Returns a callable or None
"""
if callable(func_or_path):
return func_or_path
module_name = '.'.join(func_or_path.split('.')[:-1])
function_name = func_or_path.split('.')[-1]
_module = import_module(module_name)
func = getattr(_module, function_name)
return func
def clean_app_config(app_path):
"""
Removes the AppConfig path for this app and returns the new string
"""
apps_names = [app.name for app in apps.get_app_configs()]
if app_path in apps_names:
return app_path
else:
app_split = app_path.split('.')
new_app = '.'.join(app_split[:-2])
if new_app in apps_names:
return new_app
else: # pragma: no cover
raise ImproperlyConfigured(
"The application {0} is not in the configured apps or does".format(app_path) +
"not have the pattern app.apps.AppConfig"
)
| from importlib import import_module
from django.apps import apps
from django.core.exceptions import ImproperlyConfigured
def get_callable(func_or_path):
"""
Receives a dotted path or a callable, Returns a callable or None
"""
if callable(func_or_path):
return func_or_path
module_name = '.'.join(func_or_path.split('.')[:-1])
function_name = func_or_path.split('.')[-1]
_module = import_module(module_name)
func = getattr(_module, function_name)
return func
def clean_app_config(app_path):
"""
Removes the AppConfig path for this app and returns the new string
"""
apps_names = [app.name for app in apps.get_app_configs()]
if app_path in apps_names:
return app_path
else:
app_split = app_path.split('.')
new_app = '.'.join(app_split[:-2])
if new_app in apps_names:
return new_app
else: # pragma: no cover
raise ImproperlyConfigured(
"The application {0} is not in the configured apps or does" +
"not have the pattern app.apps.AppConfig".format(app_path)
)
|
Use sum function to construct objective function. | #!/usr/bin/python3
"""
Maximize
1 x1 + 2 x2
Subject To
C1: x1 + x2 <= 40
Nickel: 2 x1 + 1 x2 <= 60
Bounds
x1 >= 0
x2 >= 0
End
"""
from gurobipy import *
m = Model("simple")
x1 = m.addVar(name="x1")
x2 = m.addVar(name="x2")
m.update()
print("x1:%s x2:%s" % (x1,x2))
#m.setObjective(x1 + 2*x2, GRB.MAXIMIZE)
coef=[1,2]
var=[x1,x2]
s=[]
for c,v in zip(coef,var):
print(c,v)
s.append(c*v)
m.setObjective(sum(s),GRB.MAXIMIZE)
m.addConstr(x1 + x2 <= 40, "C1")
m.addConstr(2*x1 + x2 <= 60, "C2")
m.optimize()
print("Solution: %f" % (m.objVal,))
for v in m.getVars():
print("%s:%f" % (v.varName, v.x))
| #!/usr/bin/python3
"""
Maximize
1 x1 + 2 x2
Subject To
C1: x1 + x2 <= 40
Nickel: 2 x1 + 1 x2 <= 60
Bounds
x1 >= 0
x2 >= 0
End
"""
from gurobipy import *
m = Model("simple")
x1 = m.addVar(name="x1")
x2 = m.addVar(name="x2")
m.update()
print("x1:%s x2:%s" % (x1,x2))
m.setObjective(x1 + 2*x2, GRB.MAXIMIZE)
m.addConstr(x1 + x2 <= 40, "C1")
m.addConstr(2*x1 + x2 <= 60, "C2")
m.optimize()
print("Solution: %f" % (m.objVal,))
for v in m.getVars():
print("%s:%f" % (v.varName, v.x))
|
Fix order of headers in response | /**
* @package admiral
* @author Andrew Munsell <andrew@wizardapps.net>
* @copyright 2015 WizardApps
*/
exports = module.exports = function(app, config, fleet) {
/**
* Get the machines in the cluster
*/
app.get('/v1/machines', function(req, res) {
fleet.list_machinesAsync()
.then(function(machines) {
res
.header('Cache-Control', 'private, max-age=60')
.json(machines);
})
.catch(function(err) {
res
.status(500)
.json({
error: 500,
message: 'There was a problem fetching the machines.'
});
})
.finally(function() {
res.end();
});
});
};
exports['@singleton'] = true;
exports['@require'] = ['app', 'config', 'fleet']; | /**
* @package admiral
* @author Andrew Munsell <andrew@wizardapps.net>
* @copyright 2015 WizardApps
*/
exports = module.exports = function(app, config, fleet) {
/**
* Get the machines in the cluster
*/
app.get('/v1/machines', function(req, res) {
fleet.list_machinesAsync()
.then(function(machines) {
res
.json(machines)
.header('Cache-Control', 'private, max-age=60');
})
.catch(function(err) {
res
.status(500)
.json({
error: 500,
message: 'There was a problem fetching the machines.'
});
})
.finally(function() {
res.end();
});
});
};
exports['@singleton'] = true;
exports['@require'] = ['app', 'config', 'fleet']; |
Fix test for posts reducer requesting posts | import { expect } from 'chai';
import posts from '../../src/js/store/reducers/posts';
import {
addPost,
requestPosts,
receivePosts,
} from '../../src/js/store/actions/posts';
describe('posts reducer', () => {
const post = { title: 'A first post' };
it('returns initial state', () => {
const result = posts(undefined, {});
expect(result).to.eql({
isFetching: false,
lastUpdated: 0,
items: [],
});
});
it('adds post', () => {
const result = posts({ items: [] }, addPost(post));
expect(result.items).to.include(post);
});
it('receives posts', () => {
const result = posts(
undefined,
receivePosts({ posts: [post] }),
);
expect(result.items).not.to.be.empty;
expect(result.isFetching).to.eq(false);
expect(result.lastUpdated).not.to.eq(0);
});
it('requests posts', () => {
const result = posts({ items: [] }, requestPosts());
expect(result.isFetching).to.eq(true);
});
});
| import { expect } from 'chai';
import posts from '../../src/js/store/reducers/posts';
import {
addPost,
requestPosts,
receivePosts,
} from '../../src/js/store/actions/posts';
describe('posts reducer', () => {
const post = { title: 'A first post' };
it('returns initial state', () => {
const result = posts(undefined, {});
expect(result).to.eql({
isFetching: false,
lastUpdated: 0,
items: [],
});
});
it('adds post', () => {
const result = posts({ items: [] }, addPost(post));
expect(result.items).to.include(post);
});
it('receives posts', () => {
const result = posts(
undefined,
receivePosts({ posts: [post] }),
);
expect(result.items).not.to.be.empty;
expect(result.isFetching).to.eq(false);
expect(result.lastUpdated).not.to.eq(0);
});
it('requests posts', () => {
const result = posts({ items: [] }, requestPosts());
expect(result.lastUpdated).not.to.eq(0);
});
});
|
feat: Add contentType as a parameter for OnRedirect callback function | const mediaType = 'application/vnd.cignium.resource+json'
export async function request(method, href, data, config) {
const request = {
body: data && JSON.stringify(data),
credentials: 'include',
headers: new Headers({ Accept: 'application/json' }),
method,
}
const response = await fetch(href, request)
const contentType = response.headers.get('Content-Type')
if (response.status == 401) {
if (config && config.onRedirect) {
return getResponse(response, config, contentType)
}
location.href = method.toLowerCase() == 'get' ? response.url : location.href
return
}
if (response.status >= 400 && response.status < 600) {
throw Error(`${response.status}: ${response.statusText}`)
}
if (contentType.startsWith(mediaType)) {
return await response.json()
}
if (config && config.onRedirect) {
return getResponse(response, config, contentType)
}
location.href = response.url
return null
}
async function getResponse(response, config, contentType) {
let content = await response.text()
content = config.onRedirect(response.url, content, response.status, contentType)
if (content) {
content.type = content.type || 'html'
content.links = content.links || [{ rel: 'self', href: response.url }]
}
return content
}
| const mediaType = 'application/vnd.cignium.resource+json'
export async function request(method, href, data, config) {
const request = {
body: data && JSON.stringify(data),
credentials: 'include',
headers: new Headers({ Accept: 'application/json' }),
method,
}
const response = await fetch(href, request)
const contentType = response.headers.get('Content-Type')
if (response.status == 401) {
if (config && config.onRedirect) {
return getResponse(response, config)
}
location.href = method.toLowerCase() == 'get' ? response.url : location.href
return
}
if (response.status >= 400 && response.status < 600) {
throw Error(`${response.status}: ${response.statusText}`)
}
if (contentType.startsWith(mediaType)) {
return await response.json()
}
if (config && config.onRedirect) {
return getResponse(response, config)
}
location.href = response.url
return null
}
async function getResponse(response, config) {
let content = await response.text()
content = config.onRedirect(response.url, content, response.status)
if (content) {
content.type = content.type || 'html'
content.links = content.links || [{ rel: 'self', href: response.url }]
}
return content
}
|
Set a default realm config | package com.bkp.minerva;
import android.app.Application;
import android.content.Context;
import com.karumi.dexter.Dexter;
import io.realm.Realm;
import io.realm.RealmConfiguration;
/**
* Custom Application class.
*/
public class Minerva extends Application {
/**
* Static instance to (CAREFULLY) allow getting Application Context anywhere.
*/
private static Minerva instance;
@Override
public void onCreate() {
super.onCreate();
// Stash application context.
instance = this;
// Init Dexter.
Dexter.initialize(this);
// Set up Realm.
setupRealm();
}
/**
* Set up Realm's default configuration.
*/
private void setupRealm() {
RealmConfiguration config = new RealmConfiguration.Builder(this)
.name("minerva.realm")
.schemaVersion(0)
.build();
Realm.setDefaultConfiguration(config);
}
/**
* Get the application context. DO NOT use the context returned by this method in methods which affect the UI (such
* as when inflating a layout, for example).
* @return Application context.
*/
public static Context getAppCtx() {
return instance.getApplicationContext();
}
}
| package com.bkp.minerva;
import android.app.Application;
import android.content.Context;
import com.karumi.dexter.Dexter;
/**
* Custom Application class.
*/
public class Minerva extends Application {
/**
* Static instance to (CAREFULLY) allow getting Application Context anywhere.
*/
private static Minerva instance;
@Override
public void onCreate() {
super.onCreate();
// Stash application context.
instance = this;
// Init Dexter.
Dexter.initialize(this);
}
/**
* Get the application context. DO NOT use the context returned by this method in methods which affect the UI (such
* as when inflating a layout, for example).
* @return Application context.
*/
public static Context getAppCtx() {
return instance.getApplicationContext();
}
}
|
Add cache in opps menu list via context processors | # -*- coding: utf-8 -*-
from django.utils import timezone
from django.conf import settings
from django.contrib.sites.models import get_current_site
from django.core.cache import cache
from .models import Channel
def channel_context(request):
""" Channel context processors
"""
site = get_current_site(request)
opps_menu = cache.get('opps_menu')
if not opps_menu:
opps_menu = [channel for channel in Channel.objects.filter(
site=site,
date_available__lte=timezone.now(),
published=True,
show_in_menu=True).distinct().order_by('order')]
cache.set('opps_menu', opps_menu, settings.OPPS_CACHE_EXPIRE)
return {'opps_menu': opps_menu,
'opps_channel_conf_all': settings.OPPS_CHANNEL_CONF,
'site': site}
| # -*- coding: utf-8 -*-
from django.utils import timezone
from django.conf import settings
from django.contrib.sites.models import get_current_site
from .models import Channel
def channel_context(request):
""" Channel context processors
"""
site = get_current_site(request)
opps_menu = Channel.objects.filter(site=site,
date_available__lte=timezone.now(),
published=True,
show_in_menu=True).order_by('order')
return {'opps_menu': opps_menu,
'opps_channel_conf_all': settings.OPPS_CHANNEL_CONF,
'site': site}
|
Add data for ranking route | var subscriptions = new SubsManager();
Router.configure({
layoutTemplate: 'layout',
loadingTemplate: 'loading',
notFoundTemplate: 'notFound'
});
Router.route('/', {
name: 'home',
waitOn: function() {
return [subscriptions.subscribe('lastGames'), subscriptions.subscribe('allUsers')];
},
fastRender: true
});
Router.route('/ranking', {
name: 'rankingWrapper',
waitOn: function() {
return subscriptions.subscribe('allUsers');
},
data: function() {
return Meteor.users.find({}, {
fields: {
'profile.firstName': 1,
'profile.lastName': 1,
'profile.points': 1
}
});
},
fastRender: true
});
Router.route('/championship', {
name: 'ChampionshipWrapper',
/*waitOn: function() {
return subscriptions.subscribe('');
},*/
fastRender: true
});
Router.route('/search', {
name: 'search',
/*waitOn: function() {
return subscriptions.subscribe('');
},*/
fastRender: true
});
Router.route('/account', {
name: 'accountWrapper',
fastRender: true
});
| var subscriptions = new SubsManager();
Router.configure({
layoutTemplate: 'layout',
loadingTemplate: 'loading',
notFoundTemplate: 'notFound'
});
Router.route('/', {
name: 'home',
waitOn: function() {
return [subscriptions.subscribe('lastGames'), subscriptions.subscribe('allUsers')];
},
fastRender: true
});
Router.route('/ranking', {
name: 'rankingWrapper',
/*waitOn: function() {
return subscriptions.subscribe('');
},*/
fastRender: true
});
Router.route('/championship', {
name: 'ChampionshipWrapper',
/*waitOn: function() {
return subscriptions.subscribe('');
},*/
fastRender: true
});
Router.route('/search', {
name: 'search',
/*waitOn: function() {
return subscriptions.subscribe('');
},*/
fastRender: true
});
Router.route('/account', {
name: 'accountWrapper',
fastRender: true
});
|
Fix check for presence of elements | protractor.expect = {
challengeSolved: function (context) {
describe('(shared)', () => {
beforeEach(() => {
browser.get('/#/score-board')
})
it("challenge '" + context.challenge + "' should be solved on score board", () => {
expect(element(by.id(context.challenge + '.solved')).isPresent()).toBeTruthy()
expect(element(by.id(context.challenge + '.notSolved')).isPresent()).toBeFalsy()
})
})
}
}
protractor.beforeEach = {
login: function (context) {
describe('(shared)', () => {
beforeEach(() => {
browser.get('/#/login')
element(by.id('email')).sendKeys(context.email)
element(by.id('password')).sendKeys(context.password)
element(by.id('loginButton')).click()
})
it('should have logged in user "' + context.email + '" with password "' + context.password + '"', () => {
expect(browser.getCurrentUrl()).toMatch(/\/search/) // TODO Instead check for uib-tooltip of <i> with fa-user-circle
})
})
}
}
| protractor.expect = {
challengeSolved: function (context) {
describe('(shared)', () => {
beforeEach(() => {
browser.get('/#/score-board')
})
it("challenge '" + context.challenge + "' should be solved on score board", () => {
expect(element(by.id(context.challenge + '.solved'))).toBeTruthy()
expect(element(by.id(context.challenge + '.notSolved'))).not.toBeTruthy()
})
})
}
}
protractor.beforeEach = {
login: function (context) {
describe('(shared)', () => {
beforeEach(() => {
browser.get('/#/login')
element(by.id('email')).sendKeys(context.email)
element(by.id('password')).sendKeys(context.password)
element(by.id('loginButton')).click()
})
it('should have logged in user "' + context.email + '" with password "' + context.password + '"', () => {
expect(browser.getCurrentUrl()).toMatch(/\/search/) // TODO Instead check for uib-tooltip of <i> with fa-user-circle
})
})
}
}
|
Use correct Buffer in tests
`new B` instead of `new Buffer`, otherwise browserify will inline the old version in the tests and we won't be testing anything. :) | var B = require('../').Buffer
var test = require('tape')
test('modifying buffer created by .slice() modifies original memory', function (t) {
if (!B._useTypedArrays) return t.end()
var buf1 = new B(26)
for (var i = 0 ; i < 26 ; i++) {
buf1[i] = i + 97 // 97 is ASCII a
}
var buf2 = buf1.slice(0, 3)
t.equal(buf2.toString('ascii', 0, buf2.length), 'abc')
buf2[0] = '!'.charCodeAt(0)
t.equal(buf1.toString('ascii', 0, buf2.length), '!bc')
t.end()
})
test('modifying parent buffer modifies .slice() buffer\'s memory', function (t) {
if (!B._useTypedArrays) return t.end()
var buf1 = new B(26)
for (var i = 0 ; i < 26 ; i++) {
buf1[i] = i + 97 // 97 is ASCII a
}
var buf2 = buf1.slice(0, 3)
t.equal(buf2.toString('ascii', 0, buf2.length), 'abc')
buf1[0] = '!'.charCodeAt(0)
t.equal(buf2.toString('ascii', 0, buf2.length), '!bc')
t.end()
})
| var B = require('../').Buffer
var test = require('tape')
test('modifying buffer created by .slice() modifies original memory', function (t) {
if (!B._useTypedArrays) return t.end()
var buf1 = new Buffer(26)
for (var i = 0 ; i < 26 ; i++) {
buf1[i] = i + 97 // 97 is ASCII a
}
var buf2 = buf1.slice(0, 3)
t.equal(buf2.toString('ascii', 0, buf2.length), 'abc')
buf2[0] = '!'.charCodeAt(0)
t.equal(buf1.toString('ascii', 0, buf2.length), '!bc')
t.end()
})
test('modifying parent buffer modifies .slice() buffer\'s memory', function (t) {
if (!B._useTypedArrays) return t.end()
var buf1 = new Buffer(26)
for (var i = 0 ; i < 26 ; i++) {
buf1[i] = i + 97 // 97 is ASCII a
}
var buf2 = buf1.slice(0, 3)
t.equal(buf2.toString('ascii', 0, buf2.length), 'abc')
buf1[0] = '!'.charCodeAt(0)
t.equal(buf2.toString('ascii', 0, buf2.length), '!bc')
t.end()
})
|
Fix encoding of source image to work on Python3 | import base64
import json
import os
import random
from dallinger.nodes import Source
class DrawingSource(Source):
"""A Source that reads in a random image from a file and transmits it."""
__mapper_args__ = {"polymorphic_identity": "drawing_source"}
def _contents(self):
"""Define the contents of new Infos.
transmit() -> _what() -> create_information() -> _contents().
"""
images = ["owl.png"]
# We're selecting from a list of only one item here, but it's a useful
# technique to demonstrate:
image = random.choice(images)
image_path = os.path.join("static", "stimuli", image)
uri_encoded_image = u"data:image/png;base64," + base64.b64encode(
open(image_path, "rb").read()
).decode("ascii")
return json.dumps({"image": uri_encoded_image, "sketch": ""})
| import base64
import json
import os
import random
from dallinger.nodes import Source
class DrawingSource(Source):
"""A Source that reads in a random image from a file and transmits it."""
__mapper_args__ = {"polymorphic_identity": "drawing_source"}
def _contents(self):
"""Define the contents of new Infos.
transmit() -> _what() -> create_information() -> _contents().
"""
images = ["owl.png"]
# We're selecting from a list of only one item here, but it's a useful
# technique to demonstrate:
image = random.choice(images)
image_path = os.path.join("static", "stimuli", image)
uri_encoded_image = "data:image/png;base64," + base64.b64encode(
open(image_path, "rb").read()
)
return json.dumps({"image": uri_encoded_image, "sketch": ""})
|
Fix package name on class title | <?php
namespace Juy\ActiveMenu;
/**
* Class Active
*
* @package Juy\ActiveMenu
*/
class Active
{
/**
* Current matched route
*
* @var Route
*/
protected $currentRouteName;
/**
* Active constructor
*
* @param $currentRouteName
*/
public function __construct($currentRouteName)
{
$this->currentRouteName = $currentRouteName;
}
/**
* Active route name
* If route matches given route (or array of routes) return active class
*
* @param $routePattern
*
* @return string
*/
public function route($routePattern = null)
{
// Convert to array
if (!is_array($routePattern) && $routePattern != null)
{
$routePattern = explode(' ', $routePattern);
}
// Check the current route name
// https://laravel.com/docs/5.3/helpers#method-str-is
foreach ((array) $routePattern as $i)
{
if (str_is($i, $this->currentRouteName))
{
return config('activemenu.class');
}
}
}
}
| <?php
namespace Juy\ActiveMenu;
/**
* Class Active
*
* @package Juy\Providers
*/
class Active
{
/**
* Current matched route
*
* @var Route
*/
protected $currentRouteName;
/**
* Active constructor
*
* @param $currentRouteName
*/
public function __construct($currentRouteName)
{
$this->currentRouteName = $currentRouteName;
}
/**
* Active route name
* If route matches given route (or array of routes) return active class
*
* @param $routePattern
*
* @return string
*/
public function route($routePattern = null)
{
// Convert to array
if (!is_array($routePattern) && $routePattern != null)
{
$routePattern = explode(' ', $routePattern);
}
// Check the current route name
// https://laravel.com/docs/5.3/helpers#method-str-is
foreach ((array) $routePattern as $i)
{
if (str_is($i, $this->currentRouteName))
{
return config('activemenu.class');
}
}
}
}
|
Fix startup error in Meteor 0.8.3 | Package.describe({
summary: "Adds basic support for Cordova/Phonegap\n"+
"\u001b[32mv0.0.8\n"+
"\u001b[33m-----------------------------------------\n"+
"\u001b[0m Adds basic support for Cordova/Phonegap \n"+
"\u001b[0m shell communication in iframe \n"+
"\u001b[33m-------------------------------------RaiX\n"
});
Package.on_use(function (api) {
api.use('deps','client');
api.use('ejson', 'client');
api.add_files('cordova.client.js', 'client');
api.add_files('cordova.client.notification.js', 'client');
api.export && api.export('Cordova', 'client');
});
Package.on_test(function(api) {
api.use('cordova', ['client']);
api.use('test-helpers', 'client');
api.use(['tinytest', 'underscore', 'ejson', 'ordered-dict',
'random', 'deps']);
api.add_files([
'plugin/meteor.cordova.js',
'meteor.cordova.tests.js',
], 'client');
});
| Package.describe({
summary: "Adds basic support for Cordova/Phonegap\n"+
"\u001b[32mv0.0.8\n"+
"\u001b[33m-----------------------------------------\n"+
"\u001b[0m Adds basic support for Cordova/Phonegap \n"+
"\u001b[0m shell communication in iframe \n"+
"\u001b[33m-------------------------------------RaiX\n"
});
Package.on_use(function (api) {
api.use('ejson', 'client');
api.add_files('cordova.client.js', 'client');
api.add_files('cordova.client.notification.js', 'client');
api.export && api.export('Cordova', 'client');
});
Package.on_test(function(api) {
api.use('cordova', ['client']);
api.use('test-helpers', 'client');
api.use(['tinytest', 'underscore', 'ejson', 'ordered-dict',
'random', 'deps']);
api.add_files([
'plugin/meteor.cordova.js',
'meteor.cordova.tests.js',
], 'client');
});
|
Refresh occur only if token is not expired | package net.etalia.crepuscolo.auth;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
public class RefreshAuthTokenFilter implements Filter {
private long maxTokenTime = -1;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
if (filterConfig.getInitParameter("maxTokenTime") != null) {
maxTokenTime = Long.parseLong(filterConfig.getInitParameter("maxTokenTime"));
}
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
chain.doFilter(request, response);
AuthData auth = AuthFilter.getAuthData();
if (auth.getCurrentToken() != null) {
if (response instanceof HttpServletResponse) {
if (maxTokenTime != -1 && System.currentTimeMillis() < auth.getTimeStamp() + maxTokenTime) {
String newToken = AuthData.produce(auth.getUserId(), auth.getUserPassword(), auth.getSystemId());
((HttpServletResponse) response).setHeader("X-Authorization", newToken);
}
}
}
}
@Override
public void destroy() {
}
}
| package net.etalia.crepuscolo.auth;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
public class RefreshAuthTokenFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
chain.doFilter(request, response);
AuthData auth = AuthFilter.getAuthData();
if (auth.getCurrentToken() != null) {
if (response instanceof HttpServletResponse) {
String newToken = AuthData.produce(auth.getUserId(), auth.getUserPassword(), auth.getSystemId());
((HttpServletResponse) response).setHeader("X-Authorization", newToken);
}
}
}
@Override
public void destroy() {
}
}
|
Use README.rst as long_description for package info. | """
scratchdir
~~~~~~~~~~
Context manager used to maintain your temporary directories/files.
:copyright: (c) 2017 Andrew Hawker.
:license: Apache 2.0, see LICENSE for more details.
"""
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def get_long_description():
with open('README.rst') as f:
return f.read()
setup(
name='scratchdir',
version='0.0.3',
author='Andrew Hawker',
author_email='andrew.r.hawker@gmail.com',
url='https://github.com/ahawker/scratchdir',
license='Apache 2.0',
description='Context manager used to maintain your temporary directories/files.',
long_description=get_long_description(),
py_modules=['scratchdir'],
classifiers=(
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Software Development :: Libraries :: Python Modules'
)
)
| """
scratchdir
~~~~~~~~~~
Context manager used to maintain your temporary directories/files.
:copyright: (c) 2017 Andrew Hawker.
:license: Apache 2.0, see LICENSE for more details.
"""
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name='scratchdir',
version='0.0.3',
author='Andrew Hawker',
author_email='andrew.r.hawker@gmail.com',
url='https://github.com/ahawker/scratchdir',
license='Apache 2.0',
description='Context manager used to maintain your temporary directories/files.',
long_description=__doc__,
py_modules=['scratchdir'],
classifiers=(
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Software Development :: Libraries :: Python Modules'
)
)
|
Use require.resolve to locate main.scss | const sass = require('node-sass');
const path = require('path');
const config = require('../config');
const fs = require('fs');
const imdino = require('imdi-no');
const development = config.env === 'development';
module.exports = {
"/stylesheets/main.css": function (callback) {
const opts = {
file: require.resolve("../stylesheets/main.scss"),
outFile: '/stylesheets/main.css',
includePaths: imdino.includePaths,
sourceMap: development,
sourceMapEmbed: development,
sourceMapContents: development,
sourceComments: development,
outputStyle: development ? 'nested' : 'compressed'
};
sass.render(opts, (err, result)=> {
if (err) {
return callback(err)
}
callback(null, result.css);
});
}
};
fs.readdirSync(imdino.paths.gfx).forEach(file => {
const fullPath = path.join(imdino.paths.gfx, file);
const httpPaths = [
path.join('/imdi-no/_themes/blank/gfx', file),
path.join('/gfx', file)
];
httpPaths.forEach(httpPath => {
module.exports[httpPath] = function() {
return fs.createReadStream(fullPath);
}
});
});
| const sass = require('node-sass');
const path = require('path');
const config = require('../config');
const fs = require('fs');
const imdino = require('imdi-no');
const development = config.env === 'development';
module.exports = {
"/stylesheets/main.css": function (callback) {
const opts = {
file: path.join(__dirname, "/../stylesheets/main.scss"),
outFile: '/stylesheets/main.css',
includePaths: imdino.includePaths,
sourceMap: development,
sourceMapEmbed: development,
sourceMapContents: development,
sourceComments: development,
outputStyle: development ? 'nested' : 'compressed'
};
sass.render(opts, (err, result)=> {
if (err) {
return callback(err)
}
callback(null, result.css);
});
}
};
fs.readdirSync(imdino.paths.gfx).forEach(file => {
const fullPath = path.join(imdino.paths.gfx, file);
const httpPaths = [
path.join('/imdi-no/_themes/blank/gfx', file),
path.join('/gfx', file)
];
httpPaths.forEach(httpPath => {
module.exports[httpPath] = function() {
return fs.createReadStream(fullPath);
}
});
});
|
Fix delete fail when only single deletion needed
The deleteMessages method only supports deleting more that one message,
so deleteMessage is used when there is a single thing to delete. | const DEFAULT_CHECK_FREQUENCY = 10;
const DEFAULT_MIN_AGE = 5;
module.exports = (opts) => {
const init = (app) => {
app.addCronTrigger(`*/${opts.checkFrequency || DEFAULT_CHECK_FREQUENCY} * * * *`, (bot) => {
console.log('trying to clear messages.');
bot.getMessages({ channelID: opts.channel, limit: 100 }, (err, messages) => {
if (err) {
console.error(err);
} else {
const toDelete = messages
.filter(m => Date.now() - new Date(m.timestamp).valueOf() > (opts.minAge || DEFAULT_MIN_AGE) * 60 * 1000)
.map(m => m.id);
if (toDelete.length > 1) {
bot.deleteMessages({
channelID: opts.channel,
messageIDs: toDelete,
});
} else if (toDelete.length === 1) {
bot.deleteMessage({
channelID: opts.channel,
messageID: toDelete[0],
});
}
}
});
});
};
return { init };
};
| const DEFAULT_CHECK_FREQUENCY = 10;
const DEFAULT_MIN_AGE = 5;
module.exports = (opts) => {
const init = (app) => {
app.addCronTrigger(`*/${opts.checkFrequency || DEFAULT_CHECK_FREQUENCY} * * * *`, (bot) => {
console.log('trying to clear messages.');
bot.getMessages({ channelID: opts.channel, limit: 100 }, (err, messages) => {
if (err) {
console.error(err);
} else {
bot.deleteMessages({
channelID: opts.channel,
messageIDs: messages.filter(m => Date.now() - new Date(m.timestamp).valueOf() > (opts.minAge || DEFAULT_MIN_AGE) * 60 * 1000).map(m => m.id),
});
}
});
});
};
return { init };
};
|
Add category mapping for "festmøte"
These were not given a category | module.exports = {
"Dagens bedrift": "PRESENTATIONS",
"Fest og moro": "NIGHTLIFE",
"Konsert": "MUSIC",
"Kurs og events": "PRESENTATIONS",
"Revy og teater": "PERFORMANCES",
"Foredrag": "PRESENTATIONS",
"Møte": "DEBATE",
"Happening": "NIGHTLIFE",
"Kurs": "OTHER",
"Show": "PERFORMANCES",
"Fotballkamp": "SPORT",
"Film": "PRESENTATIONS",
"Samfundsmøte": "DEBATE",
"Excenteraften": "DEBATE",
"Temafest": "NIGHTLIFE",
"Bokstavelig talt": "DEBATE",
"Quiz": "OTHER",
"DJ": "MUSIC",
"Teater": "PERFORMANCES",
"Annet": "OTHER",
"Kurs": "PRESENTATIONS",
"Omvising": "PRESENTATIONS",
"Samfunn": "DEBATE",
"Festival": "PERFORMANCES",
"Sport": "SPORT",
"Forestilling": "PERFORMANCES",
"Utstilling" : "EXHIBITIONS",
"Festmøte" : "DEBATE"
};
| module.exports = {
"Dagens bedrift": "PRESENTATIONS",
"Fest og moro": "NIGHTLIFE",
"Konsert": "MUSIC",
"Kurs og events": "PRESENTATIONS",
"Revy og teater": "PERFORMANCES",
"Foredrag": "PRESENTATIONS",
"Møte": "DEBATE",
"Happening": "NIGHTLIFE",
"Kurs": "OTHER",
"Show": "PERFORMANCES",
"Fotballkamp": "SPORT",
"Film": "PRESENTATIONS",
"Samfundsmøte": "DEBATE",
"Excenteraften": "DEBATE",
"Temafest": "NIGHTLIFE",
"Bokstavelig talt": "DEBATE",
"Quiz": "OTHER",
"DJ": "MUSIC",
"Teater": "PERFORMANCES",
"Annet": "OTHER",
"Kurs": "PRESENTATIONS",
"Omvising": "PRESENTATIONS",
"Samfunn": "DEBATE",
"Festival": "PERFORMANCES",
"Sport": "SPORT",
"Forestilling": "PERFORMANCES",
"Utstilling" : "EXHIBITIONS"
};
|
Modify ModelBuilder override to something that doesn't crash maven.
By extending the class we're overriding through plexus, we can avoid the problem of requiring a reference to it before it is loaded.
This commit should allow maven to continue normally, but with some extra messages output by our own class. | package org.jboss.maven.extension.dependency;
import org.apache.maven.model.building.DefaultModelBuilder;
import org.apache.maven.model.building.ModelBuilder;
import org.apache.maven.model.building.ModelBuildingException;
import org.apache.maven.model.building.ModelBuildingRequest;
import org.apache.maven.model.building.ModelBuildingResult;
import org.codehaus.plexus.component.annotations.Component;
@Component(role = DefaultModelBuilder.class)
public class ExtDepMgmtModelBuilder extends DefaultModelBuilder implements ModelBuilder {
@Override
public ModelBuildingResult build(ModelBuildingRequest request) throws ModelBuildingException {
System.out.println(">>>> build(ModelBuildingRequest) called: [" + request + "]");
return super.build(request);
}
@Override
public ModelBuildingResult build(ModelBuildingRequest request, ModelBuildingResult result) throws ModelBuildingException {
System.out.println(">>>> build(ModelBuildingRequest, ModelBuildingResult) called: [" + request + "] [" + result + "]");
return super.build(request, result);
}
}
| package org.jboss.maven.extension.dependency;
import org.apache.maven.model.building.DefaultModelBuilder;
import org.apache.maven.model.building.ModelBuilder;
import org.apache.maven.model.building.ModelBuildingException;
import org.apache.maven.model.building.ModelBuildingRequest;
import org.apache.maven.model.building.ModelBuildingResult;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
@Component(role = DefaultModelBuilder.class)
public class ExtDepMgmtModelBuilder implements ModelBuilder {
// Seems that having this requirement may cause issues, since jars in lib/ext/ are loaded before the main jars
// Need to see this works if we add this as a build extension in the pom (the other way of using an extension)
// See http://maven.apache.org/examples/maven-3-lifecycle-extensions.html
// It's also possible that we could insert this jar after the main jars are loaded? This isn't documented though.
// See /usr/share/maven/bin/m2.conf 's [plexus.core] section
//@Requirement(hint = "model-builder-internal")
//private DefaultModelBuilder modelBuilderDelegate;
public ModelBuildingResult build(ModelBuildingRequest request) throws ModelBuildingException {
System.out.println(">>>> build 1 called <<<<");
return null;
}
public ModelBuildingResult build(ModelBuildingRequest request, ModelBuildingResult result) throws ModelBuildingException {
System.out.println(">>>> build 2 called <<<<");
return null;
}
}
|
Add TODO for actual functionality. | package commands
import (
"fmt"
"github.com/spf13/cobra"
)
var minCommits, maxCommits int
var randomCmd = &cobra.Command{
Use: "random",
Short: "Random will add commits throughout the past 365 days.",
Long: `Random will create a git repo at the given location and create
random commits, random meaning the number of commits per day.
This will be done for the past 365 days and the commits are in the range of
--min and --max commits.`,
Run: randomRun,
}
func randomRun(cmd *cobra.Command, args []string) {
// TODO replace with actual function
fmt.Println(Location)
}
func init() {
randomCmd.Flags().IntVar(&minCommits, "min", 1,
"minimal #commits on a given day.")
randomCmd.Flags().IntVar(&maxCommits, "max", 10,
"maximal #commits on a given day.")
PunchCardCmd.AddCommand(randomCmd)
}
| package commands
import (
"fmt"
"github.com/spf13/cobra"
)
var minCommits, maxCommits int
var randomCmd = &cobra.Command{
Use: "random",
Short: "Random will add commits throughout the past 365 days.",
Long: `Random will create a git repo at the given location and create
random commits, random meaning the number of commits per day.
This will be done for the past 365 days and the commits are in the range of
--min and --max commits.`,
Run: randomRun,
}
func randomRun(cmd *cobra.Command, args []string) {
fmt.Println(Location)
}
func init() {
randomCmd.Flags().IntVar(&minCommits, "min", 1,
"minimal #commits on a given day.")
randomCmd.Flags().IntVar(&maxCommits, "max", 10,
"maximal #commits on a given day.")
PunchCardCmd.AddCommand(randomCmd)
}
|
Use rpy2 version available through conda (2.8.5) | from setuptools import setup, find_packages
from glob import glob
__author__ = 'shafferm'
__version__ = '0.1.1'
setup(
name="dada2_qiime1",
version=__version__,
install_requires=['rpy2 ==2.8.5', 'biom-format', 'numpy', 'qiime'],
scripts=glob("scripts/*.py"),
packages=find_packages(),
description="Using DADA2 with qiime 1",
author="Michael Shaffer",
author_email='michael.shaffer@ucdenver.edu',
package_data={'': ['*.r', '*.R']},
include_package_data=True,
url="https://github.com/shafferm/dada2_qiime1/",
download_url="https://github.com/shafferm/dada2_qiime1/tarball/%s" % __version__
)
| from setuptools import setup, find_packages
from glob import glob
__author__ = 'shafferm'
__version__ = '0.1.1'
setup(
name="dada2_qiime1",
version=__version__,
install_requires=['rpy2 ==2.8', 'biom-format', 'numpy', 'qiime'],
scripts=glob("scripts/*.py"),
packages=find_packages(),
description="Using DADA2 with qiime 1",
author="Michael Shaffer",
author_email='michael.shaffer@ucdenver.edu',
package_data={'': ['*.r', '*.R']},
include_package_data=True,
url="https://github.com/shafferm/dada2_qiime1/",
download_url="https://github.com/shafferm/dada2_qiime1/tarball/%s" % __version__
)
|
Use /start command as login and use proper webhook remover function | const Telegraf = require('telegraf');
const commandParts = require('telegraf-command-parts');
const cfg = require('../config');
const commander = require('./commander');
const middleware = require('./middleware');
const bot = new Telegraf(cfg.tgToken);
// Apply middleware
bot.use(commandParts());
bot.use(middleware.getSession);
bot.command('start', commander.login);
bot.command('kirjaudu', commander.login);
bot.command('saldo', middleware.loggedIn, commander.saldo);
bot.command('lisaa', middleware.loggedIn, commander.add);
bot.command('viiva', middleware.loggedIn, commander.subtract);
bot.on('message', commander.message);
// Get own username to handle commands such as /start@my_bot
bot.telegram.getMe()
.then((botInfo) => {
bot.options.username = botInfo.username;
});
// Setup webhook when in production
if (cfg.isProduction) {
bot.telegram.setWebhook(`${cfg.appUrl}/bot${cfg.tgToken}`);
bot.startWebhook(`/bot${cfg.tgToken}`, null, cfg.appPort);
// If env is development, get updates by polling
} else {
bot.telegram.deleteWebhook(); // Unsubscribe webhook if it exists
bot.startPolling();
}
| const Telegraf = require('telegraf');
const commandParts = require('telegraf-command-parts');
const cfg = require('../config');
const commander = require('./commander');
const middleware = require('./middleware');
const bot = new Telegraf(cfg.tgToken);
// Apply middleware
bot.use(commandParts());
bot.use(middleware.getSession);
bot.command('kirjaudu', commander.login);
bot.command('saldo', middleware.loggedIn, commander.saldo);
bot.command('lisaa', middleware.loggedIn, commander.add);
bot.command('viiva', middleware.loggedIn, commander.subtract);
bot.on('message', commander.message);
// Get own username to handle commands such as /start@my_bot
bot.telegram.getMe()
.then((botInfo) => {
bot.options.username = botInfo.username;
});
// Setup webhook when in production
if (cfg.isProduction) {
bot.telegram.setWebhook(`${cfg.appUrl}/bot${cfg.tgToken}`);
bot.startWebhook(`/bot${cfg.tgToken}`, null, cfg.appPort);
// If env is development, get updates by polling
} else {
bot.telegram.setWebhook(); // Unsubscribe webhook if it exists
bot.startPolling();
}
|
Add socket event to refresh sequence page | /**
* @module client/controllers/controllerSequence
*/
'use strict';
// TODO move to service
var find = require('101/find');
require('app')
.controller('controllerSequence', controllerSequence);
function controllerSequence (
$http,
$routeParams,
$scope,
socket
) {
var data = $scope.sequenceData = {};
data.sequenceName = $routeParams.sequenceName;
data.sequenceUUid = $routeParams.sequenceUuid;
socket.on('postSequence', function (data) {
if (data.uuid === $routeParams.sequenceUuid) {
fetchSequence();
}
});
/**
* Test if spec checkpoint is in list of reached checkpoints
* @return {Boolean}
*/
data.checkpointComplete = function (checkpointName) {
if (!data.sequence) { return false; }
return find(data.sequence.checkpoints, function (checkpoint) {
return checkpoint.name === checkpointName;
});
};
$http.get('/api/sequences')
.then(function success (res) {
data.sequencesSpecifications = res.data;
data.sequenceSpec = res.data[$routeParams.sequenceName];
},
function failure (res) {
});
function fetchSequence () {
$http.get('/api/sequences/'+$routeParams.sequenceName+'/'+$routeParams.sequenceUuid)
.then(function success (res) {
data.sequence = res.data;
},
function failure (res) {
});
}
fetchSequence();
}
| /**
* @module client/controllers/controllerSequence
*/
'use strict';
// TODO move to service
var find = require('101/find');
require('app')
.controller('controllerSequence', controllerSequence);
function controllerSequence (
$http,
$routeParams,
$scope
) {
var data = $scope.sequenceData = {};
data.sequenceName = $routeParams.sequenceName;
data.sequenceUUid = $routeParams.sequenceUuid;
/**
* Test if spec checkpoint is in list of reached checkpoints
* @return {Boolean}
*/
data.checkpointComplete = function (checkpointName) {
if (!data.sequence) { return false; }
return find(data.sequence.checkpoints, function (checkpoint) {
return checkpoint.name === checkpointName;
});
};
$http.get('/api/sequences')
.then(function success (res) {
data.sequencesSpecifications = res.data;
data.sequenceSpec = res.data[$routeParams.sequenceName];
},
function failure (res) {
});
$http.get('/api/sequences/'+$routeParams.sequenceName+'/'+$routeParams.sequenceUuid)
.then(function success (res) {
data.sequence = res.data;
},
function failure (res) {
});
}
|
Mark API as experimental, because of javax.swing.TransferHandler.DropHandler.autoscroll
GitOrigin-RevId: c8522f07307517203906b9c867fd4fca6713b708 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.dnd;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.util.Key;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
public abstract class DnDManager {
public static DnDManager getInstance() {
return ApplicationManager.getApplication().getService(DnDManager.class);
}
public abstract void registerSource(@NotNull DnDSource source, @NotNull JComponent component);
public abstract void registerSource(@NotNull AdvancedDnDSource source);
public abstract void unregisterSource(@NotNull DnDSource source, @NotNull JComponent component);
public abstract void unregisterSource(@NotNull AdvancedDnDSource source);
public abstract void registerTarget(DnDTarget target, JComponent component);
public abstract void unregisterTarget(DnDTarget target, JComponent component);
@Nullable
public abstract Component getLastDropHandler();
/**
* This key is intended to switch on a smooth scrolling during drag-n-drop operations.
* Note, that the target component must not use default auto-scrolling.
*
* @see java.awt.dnd.Autoscroll
* @see JComponent#setAutoscrolls
* @see JComponent#putClientProperty
*/
@ApiStatus.Experimental
public static final Key<Boolean> AUTO_SCROLL = Key.create("AUTO_SCROLL");
}
| // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.dnd;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.util.Key;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
public abstract class DnDManager {
public static DnDManager getInstance() {
return ApplicationManager.getApplication().getService(DnDManager.class);
}
public abstract void registerSource(@NotNull DnDSource source, @NotNull JComponent component);
public abstract void registerSource(@NotNull AdvancedDnDSource source);
public abstract void unregisterSource(@NotNull DnDSource source, @NotNull JComponent component);
public abstract void unregisterSource(@NotNull AdvancedDnDSource source);
public abstract void registerTarget(DnDTarget target, JComponent component);
public abstract void unregisterTarget(DnDTarget target, JComponent component);
@Nullable
public abstract Component getLastDropHandler();
/**
* This key is intended to switch on a smooth scrolling during drag-n-drop operations.
* Note, that the target component must not use default auto-scrolling.
*
* @see java.awt.dnd.Autoscroll
* @see JComponent#setAutoscrolls
* @see JComponent#putClientProperty
*/
public static final Key<Boolean> AUTO_SCROLL = Key.create("AUTO_SCROLL");
}
|
Clean up the _pool namespace as well as _pool[name] and _counts | jsio('from shared.javascript import Class')
exports = Class(function(){
this.init = function() {
this._pool = {}
this._counts = {}
this._uniqueId = 0
}
this.add = function(name, item) {
if (!this._pool[name]) {
this._pool[name] = {}
this._counts[name] = 0
}
this._counts[name]++
var id = 'p' + this._uniqueId++
this._pool[name][id] = item
return id
}
this.remove = function(name, id) {
var item = this._pool[name][id]
delete this._pool[name][id]
if (this._counts[name]-- == 0) {
delete this._counts[name]
delete this._pool[name]
}
return item
}
this.get = function(name) {
return this._pool[name]
}
this.count = function(name) {
return this._counts[name] || 0
}
}) | jsio('from shared.javascript import Class')
exports = Class(function(){
this.init = function() {
this._pool = {}
this._counts = {}
this._uniqueId = 0
}
this.add = function(name, item) {
if (!this._pool[name]) {
this._pool[name] = {}
this._counts[name] = 0
}
this._counts[name]++
var id = 'p' + this._uniqueId++
this._pool[name][id] = item
return id
}
this.remove = function(name, id) {
var item = this._pool[name][id]
delete this._pool[name][id]
if (this._counts[name]-- == 0) { delete this._counts[name] }
return item
}
this.get = function(name) {
return this._pool[name]
}
this.count = function(name) {
return this._counts[name] || 0
}
}) |
Add sets + a float value to the benchmark. | """
Performance tests for the agent/dogstatsd metrics aggregator.
"""
from aggregator import MetricsAggregator
class TestAggregatorPerf(object):
def test_aggregation_performance(self):
ma = MetricsAggregator('my.host')
flush_count = 10
loops_per_flush = 10000
metric_count = 5
for _ in xrange(flush_count):
for i in xrange(loops_per_flush):
# Counters
for j in xrange(metric_count):
ma.submit_packets('counter.%s:%s|c' % (j, i))
ma.submit_packets('gauge.%s:%s|g' % (j, i))
ma.submit_packets('histogram.%s:%s|h' % (j, i))
ma.submit_packets('set.%s:%s|s' % (j, 1.0))
ma.flush()
if __name__ == '__main__':
t = TestAggregatorPerf()
t.test_aggregation_performance()
| """
Performance tests for the agent/dogstatsd metrics aggregator.
"""
from aggregator import MetricsAggregator
class TestAggregatorPerf(object):
def test_aggregation_performance(self):
ma = MetricsAggregator('my.host')
flush_count = 10
loops_per_flush = 10000
metric_count = 5
for _ in xrange(flush_count):
for i in xrange(loops_per_flush):
# Counters
for j in xrange(metric_count):
ma.submit_packets('counter.%s:%s|c' % (j, i))
ma.submit_packets('gauge.%s:%s|g' % (j, i))
ma.submit_packets('histogram.%s:%s|h' % (j, i))
ma.flush()
if __name__ == '__main__':
t = TestAggregatorPerf()
t.test_aggregation_performance()
|
Fix for wrong parameter check in processPayment method. | if(Meteor.isClient){
processPayment = function(checkout, next){
Meteor.call("processPayment", checkout, next);
};
getReceipt = function(key, next){
return Meteor.call("getReceipt", key, next);
};
}
if(Meteor.isServer){
Meteor.methods({
getReceipt : function(key){
check(key, String);
return SalesRepo.getReceipt(key);
},
processPayment : function(checkout){
check(checkout, Match.ObjectIncluding({
cart_id: String
}));
//never trust the client, build the sale from the saved data
var cart = Carts.findOne({_id : checkout.cart_id});
//set the total
checkout.total = cart.total;
//set the items - have to use stringify to make sure it's saved as an array
checkout.items = JSON.stringify(cart.items);
//drop the response info onto the checkout object
checkout.payment_details = StripeService.runCharge(checkout);
//create a unique id
checkout.reference_key = Meteor.uuid();
//empty the cart
Meteor.call("emptyCart", cart.userKey);
//drop it in the DB
return SalesRepo.saveCheckout(checkout);
}
})
} | if(Meteor.isClient){
processPayment = function(checkout, next){
Meteor.call("processPayment", checkout, next);
};
getReceipt = function(key, next){
return Meteor.call("getReceipt", key, next);
};
}
if(Meteor.isServer){
Meteor.methods({
getReceipt : function(key){
check(key, String);
return SalesRepo.getReceipt(key);
},
processPayment : function(checkout){
check(checkout, Match.ObjectIncluding({
card_id: String
}));
//never trust the client, build the sale from the saved data
var cart = Carts.findOne({_id : checkout.cart_id});
//set the total
checkout.total = cart.total;
//set the items - have to use stringify to make sure it's saved as an array
checkout.items = JSON.stringify(cart.items);
//drop the response info onto the checkout object
checkout.payment_details = StripeService.runCharge(checkout);
//create a unique id
checkout.reference_key = Meteor.uuid();
//empty the cart
Meteor.call("emptyCart", cart.userKey);
//drop it in the DB
return SalesRepo.saveCheckout(checkout);
}
})
} |
[Telemetry] Set facebook_crendentials_backend_2's url to https
TBR=tonyg@chromium.org
BUG=428098
Review URL: https://codereview.chromium.org/688113003
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#301945} | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.core.backends import form_based_credentials_backend
class FacebookCredentialsBackend(
form_based_credentials_backend.FormBasedCredentialsBackend):
@property
def logged_in_javascript(self):
"""Evaluates to true iff already logged in."""
return ('document.getElementById("fbNotificationsList")!== null || '
'document.getElementById("m_home_notice")!== null')
@property
def credentials_type(self):
return 'facebook'
@property
def url(self):
return 'http://www.facebook.com/'
@property
def login_form_id(self):
return 'login_form'
@property
def login_input_id(self):
return 'email'
@property
def password_input_id(self):
return 'pass'
class FacebookCredentialsBackend2(FacebookCredentialsBackend):
""" Facebook credential backend for https client. """
@property
def credentials_type(self):
return 'facebook2'
@property
def url(self):
return 'https://www.facebook.com/'
| # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.core.backends import form_based_credentials_backend
class FacebookCredentialsBackend(
form_based_credentials_backend.FormBasedCredentialsBackend):
@property
def logged_in_javascript(self):
"""Evaluates to true iff already logged in."""
return ('document.getElementById("fbNotificationsList")!== null || '
'document.getElementById("m_home_notice")!== null')
@property
def credentials_type(self):
return 'facebook'
@property
def url(self):
return 'http://www.facebook.com/'
@property
def login_form_id(self):
return 'login_form'
@property
def login_input_id(self):
return 'email'
@property
def password_input_id(self):
return 'pass'
class FacebookCredentialsBackend2(FacebookCredentialsBackend):
@property
def credentials_type(self):
return 'facebook2'
|
Make sharedStateSink.Close return nil immediately | package core
import (
"fmt"
)
// writer points a shared state. sharedStateSink will point to the same shared state
// even after the state is removed from the context.
type sharedStateSink struct {
writer Writer
}
// NewSharedStateSink creates a sink that writes to SharedState.
func NewSharedStateSink(ctx *Context, name string) (Sink, error) {
// Get SharedState by name
state, err := ctx.SharedStates.Get(name)
if err != nil {
return nil, err
}
// It fails if the shared state cannot be written
writer, ok := state.(Writer)
if !ok {
return nil, fmt.Errorf("'%v' state cannot be written")
}
s := &sharedStateSink{
writer: writer,
}
return s, nil
}
func (s *sharedStateSink) Write(ctx *Context, t *Tuple) error {
return s.writer.Write(ctx, t)
}
func (s *sharedStateSink) Close(ctx *Context) error {
return nil
}
}
| package core
import (
"fmt"
)
// writer points a shared state. sharedStateSink will point to the same shared state
// even after the state is removed from the context.
type sharedStateSink struct {
writer Writer
}
// NewSharedStateSink creates a sink that writes to SharedState.
func NewSharedStateSink(ctx *Context, name string) (Sink, error) {
// Get SharedState by name
state, err := ctx.SharedStates.Get(name)
if err != nil {
return nil, err
}
// It fails if the shared state cannot be written
writer, ok := state.(Writer)
if !ok {
return nil, fmt.Errorf("'%v' state cannot be written")
}
s := &sharedStateSink{
writer: writer,
}
return s, nil
}
func (s *sharedStateSink) Write(ctx *Context, t *Tuple) error {
return s.writer.Write(ctx, t)
}
func (s *sharedStateSink) Close(ctx *Context) error {
closer, ok := s.writer.(WriteCloser)
if !ok {
return nil
}
return closer.Close(ctx)
}
|
Add comment before googleapis.discover call | var googleapis = require('googleapis');
/*
Example of using google apis module to discover the URL shortener module, and shorten
a url
@param params.url : the URL to shorten
*/
exports.googleapis = function(params, cb) {
// Note that, a folder named 'public' must be present in the same folder for the cache: { path: 'public' } option to work.
googleapis.withOpts({ cache: { path: 'public' }}).discover('urlshortener', 'v1').execute(function(err, client) {
console.log('executing');
console.log('dirname is ' + __dirname);
var req1 = client.urlshortener.url.insert({
longUrl: params.url || 'https://www.feedhenry.com'
});
console.log(req1);
req1.withApiKey( << place google API key here >> );
req1.execute(function(err, response) {
console.log(err);
console.log('Short URL is', response.id);
return cb(null, response);
});
});
};
| var googleapis = require('googleapis');
/*
Example of using google apis module to discover the URL shortener module, and shorten
a url
@param params.url : the URL to shorten
*/
exports.googleapis = function(params, cb) {
googleapis.withOpts({ cache: { path: 'public' }}).discover('urlshortener', 'v1').execute(function(err, client) {
console.log('executing');
console.log('dirname is ' + __dirname);
var req1 = client.urlshortener.url.insert({
longUrl: params.url || 'https://www.feedhenry.com'
});
console.log(req1);
req1.withApiKey( << place google API key here >> );
req1.execute(function(err, response) {
console.log(err);
console.log('Short URL is', response.id);
return cb(null, response);
});
});
};
|
Change indentation in js file | HTMLWidgets.widget({
name: 'trackWidget',
type: 'output',
factory: function(el, width, height) {
// Define shared variables for this instance
var tntins = null;
var initial_width = width;
return {
renderValue: function(x) {
// Code to render the widget ----------------
tntins = eval(x.tntdef);
// Set the initial width
tntins.width(initial_width);
tntins(el);
tntins.start();
// TODO: In the future, we may implement interface to add/update data to
// an existing tnt instance (with shiny), and with proper transition.
},
resize: function(width, height) {
// TODO: code to re-render the widget with a new size
tntins.width(width);
}
};
}
}); | HTMLWidgets.widget({
name: 'trackWidget',
type: 'output',
factory: function(el, width, height) {
// Define shared variables for this instance
var tntins = null;
var initial_width = width;
return {
renderValue: function(x) {
// Code to render the widget ----------------
tntins = eval(x.tntdef);
// Set the initial width
tntins.width(initial_width);
tntins(el);
tntins.start();
// TODO: In the future, we may implement interface to add/update data to
// an existing tnt instance (with shiny), and with proper transition.
},
resize: function(width, height) {
// TODO: code to re-render the widget with a new size
tntins.width(width);
}
};
}
}); |
Set layout explicitly for the overridden ilios-calendar-component | /* global moment */
import Ember from 'ember';
import layout from '../templates/components/ilios-calendar-event';
import { default as CalendarEvent } from 'el-calendar/components/calendar-event';
export default CalendarEvent.extend({
layout: layout,
viewType: 'day',
event: null,
classNameBindings: [':event', ':event-pos', ':ilios-calendar-event', 'event.eventClass', 'viewType'],
toolTipMessage: Ember.computed('event', function(){
let str = this.get('event.location') + '<br />' +
moment(this.get('event.startDate')).format('h:mma') + ' - ' +
moment(this.get('event.endDate')).format('h:mma') + '<br />' +
this.get('event.name');
return str;
}),
style: Ember.computed(function() {
if(this.get('viewType') === 'month-event'){
return '';
}
let escape = Ember.Handlebars.Utils.escapeExpression;
return Ember.String.htmlSafe(
`top: ${escape(this.calculateTop())}%;
height: ${escape(this.calculateHeight())}%;
left: ${escape(this.calculateLeft())}%;
width: ${escape(this.calculateWidth())}%;`
);
}),
click(){
this.sendAction('action', this.get('event'));
}
});
| /* global moment */
import Ember from 'ember';
import { default as CalendarEvent } from 'el-calendar/components/calendar-event';
export default CalendarEvent.extend({
viewType: 'day',
event: null,
classNameBindings: [':event', ':event-pos', ':ilios-calendar-event', 'event.eventClass', 'viewType'],
toolTipMessage: Ember.computed('event', function(){
let str = this.get('event.location') + '<br />' +
moment(this.get('event.startDate')).format('h:mma') + ' - ' +
moment(this.get('event.endDate')).format('h:mma') + '<br />' +
this.get('event.name');
return str;
}),
style: Ember.computed(function() {
if(this.get('viewType') === 'month-event'){
return '';
}
let escape = Ember.Handlebars.Utils.escapeExpression;
return Ember.String.htmlSafe(
`top: ${escape(this.calculateTop())}%;
height: ${escape(this.calculateHeight())}%;
left: ${escape(this.calculateLeft())}%;
width: ${escape(this.calculateWidth())}%;`
);
}),
click(){
this.sendAction('action', this.get('event'));
}
});
|
Add requests package as dependency
The package depends on the requests package, which is not explicitly mentioned in the setup file. Path adds this as requirement to the setup file. | '''
Python wrapper for the OpenAQ API
Written originally by David H Hagan
December 2015
'''
__version__ = '1.1.0'
try:
from setuptools import setup
except:
from distutils.core import setup
setup(
name = 'py-openaq',
version = __version__,
description = 'Python wrapper for the OpenAQ API',
keywords = ['OpenAQ', 'MIT', 'Air Quality'],
author = 'David H Hagan',
author_email = 'david@davidhhagan.com',
url = 'https://github.com/dhhagan/py-openaq',
license = 'MIT',
packages = ['openaq'],
install_requires = ['requests'],
test_suite = 'tests',
classifiers = [
'Development Status :: 3 - Alpha',
'Operating System :: OS Independent',
'Intended Audience :: Science/Research',
'Intended Audience :: Developers',
'Intended Audience :: Education',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Scientific/Engineering :: Atmospheric Science',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
| '''
Python wrapper for the OpenAQ API
Written originally by David H Hagan
December 2015
'''
__version__ = '1.1.0'
try:
from setuptools import setup
except:
from distutils.core import setup
setup(
name = 'py-openaq',
version = __version__,
description = 'Python wrapper for the OpenAQ API',
keywords = ['OpenAQ', 'MIT', 'Air Quality'],
author = 'David H Hagan',
author_email = 'david@davidhhagan.com',
url = 'https://github.com/dhhagan/py-openaq',
license = 'MIT',
packages = ['openaq'],
test_suite = 'tests',
classifiers = [
'Development Status :: 3 - Alpha',
'Operating System :: OS Independent',
'Intended Audience :: Science/Research',
'Intended Audience :: Developers',
'Intended Audience :: Education',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Scientific/Engineering :: Atmospheric Science',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
|
Correct return of Terminal instance when parameter is string | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from .RawGrammar import RawGrammar as Grammar
class StringGrammar(Grammar):
@staticmethod
def __to_string_arr(t):
if isinstance(t, str):
return [t]
return t
def remove_term(self, term=None):
return super().remove_term(StringGrammar.__to_string_arr(term))
def add_term(self, term):
return super().add_term(StringGrammar.__to_string_arr(term))
def term(self, term=None):
return super().term(StringGrammar.__to_string_arr(term))
def get_term(self, term=None):
res = super().get_term(StringGrammar.__to_string_arr(term))
if isinstance(term, str):
return res[0]
return res
def have_term(self, term):
return super().have_term(StringGrammar.__to_string_arr(term))
| #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from .RawGrammar import RawGrammar as Grammar
class StringGrammar(Grammar):
@staticmethod
def __to_string_arr(t):
if isinstance(t, str):
return [t]
return t
def remove_term(self, term=None):
return super().remove_term(StringGrammar.__to_string_arr(term))
def add_term(self, term):
return super().add_term(StringGrammar.__to_string_arr(term))
def term(self, term=None):
return super().term(StringGrammar.__to_string_arr(term))
def get_term(self, term=None):
return super().get_term(StringGrammar.__to_string_arr(term))
def have_term(self, term):
return super().have_term(StringGrammar.__to_string_arr(term))
|
Rename methods and instance variables to make intentions clearer. | package uk.ac.ebi.quickgo.index.annotation.coterms;
import java.util.Iterator;
import org.springframework.batch.item.ItemReader;
/**
* Provide a list of all GO Terms for which co-occurrence has been determined ( which is all of them that have been
* processed, since at worst a GO Term will have a statistic for co-occurring with itself).
*
* @author Tony Wardell
* Date: 07/09/2016
* Time: 15:38
* Created with IntelliJ IDEA.
*/
class Co_occurringTermItemReader implements ItemReader<String> {
private final AnnotationCoOccurringTermsAggregator aggregator;
private Iterator<String> termsIt;
public Co_occurringTermItemReader(AnnotationCoOccurringTermsAggregator annotationCoOccurringTermsAggregator) {
this.aggregator = annotationCoOccurringTermsAggregator;
}
@Override public String read() throws Exception {
//Delay providing full list until aggregator has fully processed all records.
if (termsIt == null) {
termsIt = aggregator.getCoTerms().keySet().iterator();
}
if (termsIt.hasNext()) {
return termsIt.next();
}
return null;
}
}
| package uk.ac.ebi.quickgo.index.annotation.coterms;
import java.util.Iterator;
import org.springframework.batch.item.ItemReader;
/**
* Provide a list of all GO Terms for which co-occurrence has been determined ( which is all of them that have been
* processed, since at worst a GO Term will have a statistic for co-occurring with itself).
*
* @author Tony Wardell
* Date: 07/09/2016
* Time: 15:38
* Created with IntelliJ IDEA.
*/
class Co_occurringTermItemReader implements ItemReader<String> {
private final AnnotationCoOccurringTermsAggregator aggregator;
private Iterator<String> termsIt;
public Co_occurringTermItemReader(AnnotationCoOccurringTermsAggregator annotationCoOccurringTermsAggregator) {
this.aggregator = annotationCoOccurringTermsAggregator;
}
@Override public String read() throws Exception {
//Delay providing full list until aggregator has fully processed all records.
if (termsIt == null) {
termsIt = aggregator.getTermToTermOverlapMatrix().keySet().iterator();
}
if (termsIt.hasNext()) {
return termsIt.next();
}
return null;
}
}
|
Fix CM upgrade issues, use request's clientId for message-client | <?php
class Denkmal_FormAction_Message_Create extends CM_FormAction_Abstract {
protected function _getRequiredFields() {
return array('venue', 'text');
}
protected function _process(CM_Params $params, CM_Http_Response_View_Form $response, CM_Form_Abstract $form) {
/** @var Denkmal_Params $params */
$venue = $params->getVenue('venue');
$text = $params->getString('text');
$clientId = (string) $response->getRequest()->getClientId();
$image = null;
if ($params->has('image')) {
/** @var CM_File_UserContent_Temp $file */
$file = $params->getArray('image')[0];
$image = Denkmal_Model_MessageImage::create(new CM_File_Image($file));
}
$action = new Denkmal_Action_Message(Denkmal_Action_Message::CREATE, $response->getRequest()->getIp());
$action->prepare();
$message = Denkmal_Model_Message::create($venue, $clientId, null, $text, $image);
$action->notify($message);
return $message;
}
}
| <?php
class Denkmal_FormAction_Message_Create extends CM_FormAction_Abstract {
protected function _getRequiredFields() {
return array('venue', 'text');
}
protected function _process(CM_Params $params, CM_Http_Response_View_Form $response, CM_Form_Abstract $form) {
/** @var Denkmal_Params $params */
$venue = $params->getVenue('venue');
$text = $params->getString('text');
$clientId = (string) $response->getRequest()->getClientId();
$image = null;
if ($params->has('image')) {
/** @var CM_File_UserContent_Temp $file */
$file = $params->getArray('image')[0];
$image = Denkmal_Model_MessageImage::create(new CM_File_Image($file));
}
$action = new Denkmal_Action_Message(Denkmal_Action_Message::CREATE, $response->getRequest()->getIp());
$action->prepare();
$message = Denkmal_Model_Message::create($venue, $clientId, $text, $image);
$action->notify($message);
return $message;
}
}
|
Read a CSV file and return a slice of slice | package main // import "eriol.xyz/piken"
import (
"encoding/csv"
"io"
"net/http"
"os"
"github.com/Sirupsen/logrus"
"github.com/mitchellh/go-homedir"
)
func download(url, output string) error {
r, err := http.Get(url)
if err != nil {
return err
}
defer r.Body.Close()
out, err := os.Create(output)
if err != nil {
return err
}
defer out.Close()
// io.copyBuffer, the actual implementation of io.Copy, reads maximum 32 KB
// from input, writes to output and then repeats. No need to worry about
// the size of file to download.
_, err = io.Copy(out, r.Body)
if err != nil {
return err
}
return nil
}
// Get user home directory or exit with a fatal error.
func getHome() string {
homeDir, err := homedir.Dir()
if err != nil {
logrus.Fatal(err)
}
return homeDir
}
// Read a CSV file and return a slice of slice.
func readCsvFile(filepath string) (records [][]string, err error) {
file, err := os.Open(filepath)
if err != nil {
return nil, err
}
defer file.Close()
reader := csv.NewReader(file)
reader.Comma = ';'
records, err = reader.ReadAll()
if err != nil {
return nil, err
}
return records, nil
}
| package main // import "eriol.xyz/piken"
import (
"io"
"net/http"
"os"
"github.com/Sirupsen/logrus"
"github.com/mitchellh/go-homedir"
)
func download(url, output string) error {
r, err := http.Get(url)
if err != nil {
return err
}
defer r.Body.Close()
out, err := os.Create(output)
if err != nil {
return err
}
defer out.Close()
// io.copyBuffer, the actual implementation of io.Copy, reads maximum 32 KB
// from input, writes to output and then repeats. No need to worry about
// the size of file to download.
_, err = io.Copy(out, r.Body)
if err != nil {
return err
}
return nil
}
// Get user home directory or exit with a fatal error.
func getHome() string {
homeDir, err := homedir.Dir()
if err != nil {
logrus.Fatal(err)
}
return homeDir
}
|
Change variable name to another more desriptive | <?php
namespace MartiAdrogue\SqlBuilder;
use MartiAdrogue\SqlBuilder\Exception\InvalidSqlSyntaxException;
/**
*
*/
class SelectBuilder
{
private $sql;
public function __construct()
{
$this->sql = 'SELECT ';
}
/**
* Make a select statement with rows passed.
*
* @param string $rows List of rows separated by comma
*
* @return FormBuilder Builder to make next part of a statement Select.
*/
public function select(array $rows)
{
$this->hasReservedWords($rows);
$this->sql .= $this->makeRowsChain($rows);
return new FromBuilder($this);
}
public function __toString()
{
return $this->sql;
}
private function makeRowsChain(array $rows)
{
return implode(', ', $rows);
}
private function hasReservedWords(array $rows)
{
$reservedWords = require('config/ReservedWords.php');
$candidatesViolation = array_map('strtoupper', $rows);
$violations = array_intersect($reservedWords, $candidatesViolation);
if (0 < count($violations)) {
throw new InvalidSqlSyntaxException();
}
}
}
| <?php
namespace MartiAdrogue\SqlBuilder;
use MartiAdrogue\SqlBuilder\Exception\InvalidSqlSyntaxException;
/**
*
*/
class SelectBuilder
{
private $sql;
public function __construct()
{
$this->sql = 'SELECT ';
}
/**
* Make a select statement with rows passed.
*
* @param string $rows List of rows separated by comma
*
* @return FormBuilder Builder to make next part of a statement Select.
*/
public function select(array $rows)
{
$this->hasReservedWords($rows);
$this->sql .= $this->makeRowsChain($rows);
return new FromBuilder($this);
}
public function __toString()
{
return $this->sql;
}
private function makeRowsChain(array $rows)
{
return implode(', ', $rows);
}
private function hasReservedWords(array $rows)
{
$reservedWords = require('config/ReservedWords.php');
$safeRows = array_map('strtoupper', $rows);
$violations = array_intersect($reservedWords, $safeRows);
if (0 < count($violations)) {
throw new InvalidSqlSyntaxException();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.