text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Use the new links for websites (with odoo) and for the prestashop
connector | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: David BEAL, Copyright Akretion, 2014
#
# 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': 'Connector Base Product',
'version': '1.0',
'author': 'Openerp Connector Core Editors',
'website': 'http://odoo-connector.com',
'license': 'AGPL-3',
'category': 'Connector',
'description': """
Connector Base Product
======================
Add 'Connector' tab to product view
""",
'depends': [
'connector',
'product',
],
'data': [
'product_view.xml'
],
'installable': True,
}
| # -*- coding: utf-8 -*-
##############################################################################
#
# Author: David BEAL, Copyright Akretion, 2014
#
# 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': 'Connector Base Product',
'version': '1.0',
'author': 'Openerp Connector Core Editors',
'website': 'http://openerp-connector.com',
'license': 'AGPL-3',
'category': 'Connector',
'description': """
Connector Base Product
======================
Add 'Connector' tab to product view
""",
'depends': [
'connector',
'product',
],
'data': [
'product_view.xml'
],
'installable': True,
}
|
Handle case of memory limit not set. | import os
import json
import psutil
from notebook.utils import url_path_join
from notebook.base.handlers import IPythonHandler
def get_metrics():
cur_process = psutil.Process()
all_processes = [cur_process] + cur_process.children(recursive=True)
rss = sum([p.memory_info().rss for p in all_processes])
mem_limit = os.environ.get('MEM_LIMIT', None)
if mem_limit is not None:
mem_limit = int(mem_limit)
return {
'rss': rss,
'limits': {
'memory': mem_limit
}
}
class MetricsHandler(IPythonHandler):
def get(self):
self.finish(json.dumps(get_metrics()))
def setup_handlers(web_app):
route_pattern = url_path_join(web_app.settings['base_url'], '/metrics')
web_app.add_handlers('.*', [(route_pattern, MetricsHandler)])
| import os
import json
import psutil
from notebook.utils import url_path_join
from notebook.base.handlers import IPythonHandler
def get_metrics():
cur_process = psutil.Process()
all_processes = [cur_process] + cur_process.children(recursive=True)
rss = sum([p.memory_info().rss for p in all_processes])
return {
'rss': rss,
'limits': {
'memory': int(os.environ.get('MEM_LIMIT', None))
}
}
class MetricsHandler(IPythonHandler):
def get(self):
self.finish(json.dumps(get_metrics()))
def setup_handlers(web_app):
route_pattern = url_path_join(web_app.settings['base_url'], '/metrics')
web_app.add_handlers('.*', [(route_pattern, MetricsHandler)])
|
Make compatible with Laravel 5.3 | <?php
namespace Spatie\FailedJobMonitor;
use Illuminate\Queue\Events\JobFailed;
use Illuminate\Queue\QueueManager;
use Spatie\FailedJobMonitor\Senders\Sender;
class FailedJobNotifier
{
public function notifyIfJobFailed(string $sender)
{
$sender = $this->getChannelInstance($sender);
app(QueueManager::class)->failing(function (JobFailed $event) use ($sender) {
$sender->send(json_encode($event->job->payload()));
});
}
protected function getChannelInstance(string $sender) : Sender
{
$className = '\Spatie\FailedJobMonitor\Senders\\'.ucfirst($sender).'Sender';
return app($className);
}
}
| <?php
namespace Spatie\FailedJobMonitor;
use Illuminate\Queue\Events\JobFailed;
use Illuminate\Queue\QueueManager;
use Spatie\FailedJobMonitor\Senders\Sender;
class FailedJobNotifier
{
public function notifyIfJobFailed(string $sender)
{
$sender = $this->getChannelInstance($sender);
app(QueueManager::class)->failing(function (JobFailed $event) use ($sender) {
$sender->send(json_encode($event->data));
});
}
protected function getChannelInstance(string $sender) : Sender
{
$className = '\Spatie\FailedJobMonitor\Senders\\'.ucfirst($sender).'Sender';
return app($className);
}
}
|
Use FileWrapper to send files to browser in chunks of 8KB
Maybe this will fix a problem on the test server when it tries to send a huge file. | import mimetypes
import os
from django.http import HttpResponse
from django.core.servers.basehttp import FileWrapper
mimetypes.init()
mimetypes.add_type('application/epub+zip','.epub')
mimetypes.add_type('text/x-brl','.brl')
mimetypes.add_type('text/x-sbsform-g0','.bv')
mimetypes.add_type('text/x-sbsform-g1','.bv')
mimetypes.add_type('text/x-sbsform-g2','.bk')
def render_to_mimetype_response(mimetype, filename, outputFile):
ext = mimetypes.guess_extension(mimetype)
assert ext != None
wrapper = FileWrapper(file(outputFile))
response = HttpResponse(wrapper, mimetype=mimetype)
response['Content-Disposition'] = "attachment; filename=\"%s%s\"" % (filename, ext)
response['Content-Length'] = os.path.getsize(outputFile)
# remove the tmp file
os.remove(outputFile)
return response
| import mimetypes
import os
from django.http import HttpResponse
mimetypes.init()
mimetypes.add_type('application/epub+zip','.epub')
mimetypes.add_type('text/x-brl','.brl')
mimetypes.add_type('text/x-sbsform-g0','.bv')
mimetypes.add_type('text/x-sbsform-g1','.bv')
mimetypes.add_type('text/x-sbsform-g2','.bk')
def render_to_mimetype_response(mimetype, filename, outputFile):
ext = mimetypes.guess_extension(mimetype)
assert ext != None
response = HttpResponse(mimetype=mimetype)
response['Content-Disposition'] = "attachment; filename=\"%s%s\"" % (filename, ext)
f = open(outputFile)
try:
content = f.read()
response.write(content)
finally:
f.close()
# remove the tmp file
os.remove(outputFile)
return response
|
Remove logging statement of geocoding results | $(function () {
$("#guess").click(function () {
getCurrent(function (pos) {
$.ajax({
type: 'GET',
url: '/bathrooms/nearby',
data: {search: 'true', lat: pos.coords.latitude, long: pos.coords.longitude},
success: function(data, textStatus) {
$('#nearby').html(data);
}
});
$('.currentLocationButton').removeClass('currentLocationButtonLocating');
guessPosition(pos.coords, function (results) {
if(results && results.length > 0){
var addressArray = results[0].address_components;
$("#bathroom_street").val(addressArray[0].long_name + " " + addressArray[1].long_name);
$("#bathroom_city").val(addressArray[3].long_name);
$("#bathroom_state").val(addressArray[5].long_name);
$("#bathroom_country").find("option[value='" + addressArray[6].long_name + "'']").prop('selected', true);
$("#bathroom_name").val(results[0].formatted_address);
}
});
})
});
});
| $(function () {
$("#guess").click(function () {
getCurrent(function (pos) {
$.ajax({
type: 'GET',
url: '/bathrooms/nearby',
data: {search: 'true', lat: pos.coords.latitude, long: pos.coords.longitude},
success: function(data, textStatus) {
$('#nearby').html(data);
}
});
$('.currentLocationButton').removeClass('currentLocationButtonLocating');
guessPosition(pos.coords, function (results) {
if(results && results.length > 0){
console.log(results);
var addressArray = results[0].address_components;
$("#bathroom_street").val(addressArray[0].long_name + " " + addressArray[1].long_name);
$("#bathroom_city").val(addressArray[3].long_name);
$("#bathroom_state").val(addressArray[5].long_name);
$("#bathroom_country").find("option[value='" + addressArray[6].long_name + "'']").prop('selected', true);
$("#bathroom_name").val(results[0].formatted_address);
}
});
})
});
});
|
Make all changes to app/ run on all trybot platforms, not just the big three.
Anyone who's changing a header here may break the chromeos build.
BUG=none
TEST=none
Review URL: http://codereview.chromium.org/2838027
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@51000 0039d316-1c4b-4281-b951-d872f2087c98 | #!/usr/bin/python
# Copyright (c) 2009 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.
"""Makes sure that the app/ code is cpplint clean."""
INCLUDE_CPP_FILES_ONLY = (
r'.*\.cc$', r'.*\.h$'
)
EXCLUDE = (
# Autogenerated window resources files are off limits
r'.*resource.h$',
)
def CheckChangeOnUpload(input_api, output_api):
results = []
black_list = input_api.DEFAULT_BLACK_LIST + EXCLUDE
sources = lambda x: input_api.FilterSourceFile(
x, white_list=INCLUDE_CPP_FILES_ONLY, black_list=black_list)
results.extend(input_api.canned_checks.CheckChangeLintsClean(
input_api, output_api, sources))
return results
def GetPreferredTrySlaves():
return ['win', 'linux', 'linux_view', 'linux_chromeos', 'mac']
| #!/usr/bin/python
# Copyright (c) 2009 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.
"""Makes sure that the app/ code is cpplint clean."""
INCLUDE_CPP_FILES_ONLY = (
r'.*\.cc$', r'.*\.h$'
)
EXCLUDE = (
# Autogenerated window resources files are off limits
r'.*resource.h$',
)
def CheckChangeOnUpload(input_api, output_api):
results = []
black_list = input_api.DEFAULT_BLACK_LIST + EXCLUDE
sources = lambda x: input_api.FilterSourceFile(
x, white_list=INCLUDE_CPP_FILES_ONLY, black_list=black_list)
results.extend(input_api.canned_checks.CheckChangeLintsClean(
input_api, output_api, sources))
return results
|
Add close handler to bootstrap alerts. | /* Serialize a form to a Javascript object. */
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$.fn.alert = function(type, message) {
this.hide();
this.removeClass("warning error success info").addClass(type);
this.html("<a class=\"close\" href=\"#\">×</a>" + message);
this.show();
window.scrollTo(0, this.offset());
}
$(".alert-message .close").live("click", function() {
$(this).parent().hide();
return false;
});
| /* Serialize a form to a Javascript object. */
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$.fn.alert = function(type, message) {
this.hide();
this.removeClass("warning error success info").addClass(type);
this.html(message);
this.show();
window.scrollTo(0, this.offset());
}
|
Add file as second param | /*jslint indent: 2, vars: true */
var es = require('event-stream');
var gutil = require('gulp-util');
var Buffer = require('buffer').Buffer;
var cheerio = require('cheerio');
function modify(file, elem, attr, modifier) {
"use strict";
var val = elem.attr(attr);
if (val) { elem.attr(attr, modifier(val, file)); }
}
module.exports = function (query, modifier) {
"use strict";
var queryHtml = function (file) {
if (file.isNull()) { return this.emit('data', file); } // pass along
if (file.isStream()) { return this.emit('error', new Error("gulp-coffee: Streaming not supported")); }
var str = file.contents.toString('utf8');
var $ = cheerio.load(str);
$(query).each(function () {
var elem = $(this);
modify(file, elem, 'href', modifier);
modify(file, elem, 'src', modifier);
});
file.contents = new Buffer($.root().html());
this.emit('data', file);
};
return es.through(queryHtml);
};
| /*jslint indent: 2, vars: true */
var es = require('event-stream');
var gutil = require('gulp-util');
var Buffer = require('buffer').Buffer;
var cheerio = require('cheerio');
function modify(elem, attr, modifier) {
"use strict";
var val = elem.attr(attr);
if (val) { elem.attr(attr, modifier(val)); }
}
module.exports = function (query, modifier) {
"use strict";
var queryHtml = function (file) {
if (file.isNull()) { return this.emit('data', file); } // pass along
if (file.isStream()) { return this.emit('error', new Error("gulp-coffee: Streaming not supported")); }
var str = file.contents.toString('utf8');
var $ = cheerio.load(str);
$(query).each(function () {
var elem = $(this);
modify(elem, 'href', modifier);
modify(elem, 'src', modifier);
});
file.contents = new Buffer($.root().html());
this.emit('data', file);
};
return es.through(queryHtml);
};
|
Correct BEM class in spec | import React from 'react';
import { shallow } from 'enzyme';
import Section from './section';
describe('Section', () => {
let wrapper, children;
beforeEach(() => {
wrapper = shallow(
<Section
className='my-custom-class'
title="My Section Title"
>
<p>This is some content</p>
</Section>
);
});
it('renders with main and custom classes', () => {
expect(wrapper.find('.carbon-section')).toBeTruthy()
expect(wrapper.find('.my-custom-class')).toBeTruthy()
});
it('renders a title', () => {
let title = wrapper.find('.carbon-section__title')
expect(title.text()).toEqual('My Section Title')
});
it('renders the children content', () => {
expect(wrapper.contains(<p>This is some content</p>)).toBeTruthy();
});
});
| import React from 'react';
import { shallow } from 'enzyme';
import Section from './section';
describe('Section', () => {
let wrapper, children;
beforeEach(() => {
wrapper = shallow(
<Section
className='my__custom-class'
title="My Section Title"
>
<p>This is some content</p>
</Section>
);
});
it('renders with main and custom classes', () => {
expect(wrapper.find('.carbon-section')).toBeTruthy()
expect(wrapper.find('.my__custom-class')).toBeTruthy()
});
it('renders a title', () => {
let title = wrapper.find('.carbon-section__title')
expect(title.text()).toEqual('My Section Title')
});
it('renders the children content', () => {
expect(wrapper.contains(<p>This is some content</p>)).toBeTruthy();
});
});
|
Change endpoint for SFTP credentials | package api
import (
"encoding/json"
"github.com/pkg/errors"
"github.com/pterodactyl/sftp-server"
)
func (r *PanelRequest) ValidateSftpCredentials(request sftp_server.AuthenticationRequest) (*sftp_server.AuthenticationResponse, error) {
b, err := json.Marshal(request)
if err != nil {
return nil, err
}
resp, err := r.Post("/sftp/auth", b)
if err != nil {
return nil, err
}
defer resp.Body.Close()
r.Response = resp
if r.HasError() {
if r.HttpResponseCode() == 403 {
return nil, sftp_server.InvalidCredentialsError{}
}
return nil, errors.WithStack(errors.New(r.Error()))
}
response := new(sftp_server.AuthenticationResponse)
body, _ := r.ReadBody()
if err := json.Unmarshal(body, response); err != nil {
return nil, err
}
return response, nil
} | package api
import (
"encoding/json"
"github.com/pkg/errors"
"github.com/pterodactyl/sftp-server"
)
func (r *PanelRequest) ValidateSftpCredentials(request sftp_server.AuthenticationRequest) (*sftp_server.AuthenticationResponse, error) {
b, err := json.Marshal(request)
if err != nil {
return nil, err
}
resp, err := r.Post("/sftp/auth/login", b)
if err != nil {
return nil, err
}
defer resp.Body.Close()
r.Response = resp
if r.HasError() {
if r.HttpResponseCode() == 403 {
return nil, sftp_server.InvalidCredentialsError{}
}
return nil, errors.WithStack(errors.New(r.Error()))
}
response := new(sftp_server.AuthenticationResponse)
body, _ := r.ReadBody()
if err := json.Unmarshal(body, response); err != nil {
return nil, err
}
return response, nil
} |
Use hideMargin to reuse component on pages without sidebar | import m from 'mithril';
import h from '../h';
const projectEditSaveBtn = {
view(ctrl, args) {
return m('.w-section.save-draft-btn-section', {
style: (args.hideMarginLeft ? { 'margin-left': 0 } : '')
}, [
m('.w-row', [
m('.w-col.w-col-4.w-col-push-4',
(args.loading() ? h.loader() : [
m('input[id="anchor"][name="anchor"][type="hidden"][value="about_me"]'),
m('input.btn.btn.btn-large[name="commit"][type="submit"][value="Salvar"]', {
onclick: args.onSubmit
})
])
),
m('.w-col.w-col-4')
])
]);
}
};
export default projectEditSaveBtn;
| import m from 'mithril';
import h from '../h';
const projectEditSaveBtn = {
view(ctrl, args) {
return m('.w-section.save-draft-btn-section', [
m('.w-row', [
m('.w-col.w-col-4.w-col-push-4',
(args.loading() ? h.loader() : [
m('input[id="anchor"][name="anchor"][type="hidden"][value="about_me"]'),
m('input.btn.btn.btn-large[name="commit"][type="submit"][value="Salvar"]', {
onclick: args.onSubmit
})
])
),
m('.w-col.w-col-4')
])
]);
}
};
export default projectEditSaveBtn;
|
Revert "add regex generator for object to delete (e.g. '_deprecated': {})"
This reverts commit 2774e638e9ffc9ccbfc8db911767d0929910f04b. | 'use strict';
/*
* Browserify transform that strips meta attributes out of the plotlyjs bundle
*
*/
var through = require('through2');
var attributeNamesToRemove = ['description', 'requiredOpts', 'otherOpts', 'hrName', 'role'],
regexStr = '';
// ref: http://www.regexr.com/3bj6p
attributeNamesToRemove.forEach(function(attr, i) {
// one line string with or without trailing comma
regexStr += attr + ': \'.*\'' + ',?' + '|';
// array of strings with or without trailing comma
regexStr += attr + ': \\[[\\s\\S]*?\\].*' + ',?';
if(i !== attributeNamesToRemove.length-1) regexStr += '|';
});
var regex = new RegExp(regexStr, 'g');
module.exports = function() {
return through(function(buf, enc, next) {
this.push(
buf.toString('utf-8')
.replace(regex, '')
);
next();
});
};
| 'use strict';
/*
* Browserify transform that strips meta attributes out of the plotlyjs bundle
*
*/
var through = require('through2');
var attributeNamesToRemove = [
'description', 'requiredOpts', 'otherOpts', 'hrName', 'role'
];
var objectNamesToRemove = ['_deprecated'];
// ref: http://www.regexr.com/3bj6p
var regexStr = '';
attributeNamesToRemove.forEach(function(attr, i) {
// one line string with or without trailing comma
regexStr += attr + ': \'.*\'' + ',?' + '|';
// array (of strings) with or without trailing comma
regexStr += attr + ': \\[[\\s\\S]*?\\].*' + ',?' + '|';
});
// ref: http://www.regexr.com/3bor2
objectNamesToRemove.forEach(function(obj) {
// object with '// to delete following trailling '}'
regexStr += obj + ': {[\\s\\S]*?}' + ',? ?\\/\\/ ?to delete' + '|';
});
// remove trailing '|'
regexStr = regexStr.substring(0, regexStr.length-1);
var regex = new RegExp(regexStr, 'g');
module.exports = function() {
return through(function(buf, enc, next) {
this.push(
buf.toString('utf-8')
.replace(regex, '')
);
next();
});
};
|
Update Help Intent with new Instruction | module.exports = HelpIntentFunction
// Purpose: To provide the user with more information on how to use the skill
// param (in): intent: given by Alexa, allows code to access parts of the intent request
// param (in): session: given by Alexa, allows code to access parts of the session in the Lambda request
// param (out): request: allows the user to change the response by Alexa
function HelpIntentFunction (intent, session, response) {
var begin = 'This is a skill that allows you to find jobs using themuse.com '
var useFindNewest = 'In order to find the newest job postings, please say Alexa, ask muse jobs to give me the newest job postings. '
var useLocation = 'In order to find the newest job postings by location, please say Alexa, ask muse jobs to tell me the jobs near New York City Metro Area. '
var useLevel = 'In order to find the newest job postings by location, please say Alexa, ask Muse Jobs to show jobs that are Entry Level. '
var useCategory = 'In order to find the newest job postings by category, please say Alexa, ask Muse Jobs to tell me jobs that are in the category engineering. '
var question = 'What would you like to do ?'
var output = begin + useFindNewest + useLocation + useLevel + useCategory + question
response.ask(output)
return
}
| module.exports = HelpIntentFunction
// Purpose: To provide the user with more information on how to use the skill
// param (in): intent: given by Alexa, allows code to access parts of the intent request
// param (in): session: given by Alexa, allows code to access parts of the session in the Lambda request
// param (out): request: allows the user to change the response by Alexa
function HelpIntentFunction (intent, session, response) {
var begin = 'This is a skill that allows you to find jobs using themuse.com '
var useFindNewest = 'In order to find the newest job postings, please say Alexa, ask muse jobs to give me the newest job postings. '
var useLocation = 'In order to find the newest job postings by location, please say Alexa, ask muse jobs to tell me the jobs near New York City Metro Area. '
var useLevel = 'In order to find the newest job postings by location, please say Alexa, ask Muse Jobs to show jobs that are Entry Level. '
var question = 'What would you like to do ?'
var output = begin + useFindNewest + useLocation + useLevel + question
response.ask(output)
return
}
|
Add more iterator methods to query results. | define([
'../../Promise'
], function (Promise) {
'use strict';
var resolve = Promise.resolve.bind(Promise),
arrayProto = Array.prototype,
slice = arrayProto.slice,
iteratorMethods = [ 'forEach', 'map', 'filter', 'every', 'some', 'reduce', 'reduceRight' ];
/**
* Decorates a promise with a method derived from the Array.prototype wrapped in a promise that resolves when the
* promise is resolved
* @param {Promise} promise The promise that is to be decorated
* @param {String} method The name of the function from the Array prototype that should be decorated
*/
function decorate(promise, method) {
promise[method] = function () {
var args = slice.call(arguments);
return promise.then(function (results) {
return arrayProto[method].apply(results, args);
});
};
}
/**
* Takes results from a store query, wraps them in a promise if none provided, decorates with promise iterators and
* a total.
* @param {Promise|Array} results The results that are to be wrapped and decorated
* @return {Promise} The resulting promise that has been decorated.
*/
return function queryResults(results) {
var resultsPromise = resolve(results);
iteratorMethods.forEach(function (method) {
decorate(resultsPromise, method);
});
resultsPromise.total = results.total || resultsPromise.then(function (results) {
return results.length;
});
return resultsPromise;
};
}); | define([
'../../Promise'
], function (Promise) {
'use strict';
var resolve = Promise.resolve.bind(Promise),
arrayProto = Array.prototype,
slice = arrayProto.slice,
iteratorMethods = [ 'forEach', 'map', 'filter' ];
/**
* Decorates a promise with a method derived from the Array.prototype wrapped in a promise that resolves when the
* promise is resolved
* @param {Promise} promise The promise that is to be decorated
* @param {String} method The name of the function from the Array prototype that should be decorated
*/
function decorate(promise, method) {
promise[method] = function () {
var args = slice.call(arguments);
return promise.then(function (results) {
return arrayProto[method].apply(results, args);
});
};
}
/**
* Takes results from a store query, wraps them in a promise if none provided, decorates with promise iterators and
* a total.
* @param {Promise|Array} results The results that are to be wrapped and decorated
* @return {Promise} The resulting promise that has been decorated.
*/
return function queryResults(results) {
var resultsPromise = resolve(results);
iteratorMethods.forEach(function (method) {
decorate(resultsPromise, method);
});
resultsPromise.total = results.total || resultsPromise.then(function (results) {
return results.length;
});
return resultsPromise;
};
}); |
Disable ReactTableFixedColumns til prefixed uniqid
Stuck with this until
https://github.com/GuillaumeJasmin/react-table-hoc-fixed-columns/pull/12
because sometimes uniqid will generate an invalid selector (leading digit). This ends up
being deterministic per machine because they're using the mac address of the system
as part of the hash. | import * as React from "react";
import ReactTable from "react-table";
import ReactTableStyles from "../css/react-table";
import withFixedColumns from "react-table-hoc-fixed-columns";
const ReactTableFixedColumns = withFixedColumns(ReactTable);
export const DataResourceTransformGrid = ({
data: { data, schema },
height
}) => {
const tableColumns = schema.fields.map((f, i) => ({
Header: f.name,
accessor: f.name,
fixed: i === 0 && "left"
}));
return (
<div style={{ width: "calc(100vw - 150px)" }}>
<ReactTable
data={data}
columns={tableColumns}
style={{
height: `${height}px`
}}
className="-striped -highlight"
/>
<style jsx>{ReactTableStyles}</style>
</div>
);
};
| import * as React from "react";
import ReactTable from "react-table";
import ReactTableStyles from "../css/react-table";
import withFixedColumns from "react-table-hoc-fixed-columns";
const ReactTableFixedColumns = withFixedColumns(ReactTable);
export const DataResourceTransformGrid = ({
data: { data, schema },
height
}) => {
const tableColumns = schema.fields.map((f, i) => ({
Header: f.name,
accessor: f.name,
fixed: i === 0 && "left"
}));
return (
<div style={{ width: "calc(100vw - 150px)" }}>
<ReactTableFixedColumns
data={data}
columns={tableColumns}
style={{
height: `${height}px`
}}
className="-striped -highlight"
/>
<style jsx>{ReactTableStyles}</style>
</div>
);
};
|
Make sure function runs even if one of the promise fails | $(document).ready(function () {
let zone;
let district;
let getZone = $.get('/inputs/geojson/zone', function (data) {
zone = data;
});
let getDistrict = $.get('/inputs/geojson/district', function (data) {
district = data;
});
$.when(getZone, getDistrict).always(function () {
let map = new MapClass('map-div');
map.init({
data:{
zone: zone,
district: district
},
extrude: true
});
});
});
| $(document).ready(function () {
let zone;
let district;
let getZone = $.get('/inputs/geojson/zone', function (data) {
zone = data;
});
let getDistrict = $.get('/inputs/geojson/district', function (data) {
district = data;
});
$.when(getZone, getDistrict).done(function () {
let map = new MapClass('map-div');
map.init({
data:{
zone: zone,
district: district
},
extrude: true
});
});
});
|
Add AppState annotation to slicer | // @flow
import type { ThunkOrActionType } from "./actionCreators";
import type { ActionType } from "./actionTypes";
import type { AppState } from "./reducers";
import type { Store as ReduxStore } from "redux";
import { browserHistory } from "react-router";
import { routerMiddleware } from "react-router-redux";
import { compose, createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import persistState from "redux-localstorage";
import reducer from "./reducers";
import { getAuthToken } from "./accessors";
import dropboxMiddleware from "./dropboxMiddleware";
export type Dispatch = (action: ThunkOrActionType) => void;
export type Store = ReduxStore<AppState, ActionType>;
export const getStore = (): Store => {
const slicer = paths => {
return (state: AppState) => {
return Object.assign(
{},
{
dropbox: {
authToken: getAuthToken(state)
}
}
);
};
};
return createStore(
reducer,
window.__REDUX_DEVTOOLS_EXTENSION__ &&
window.__REDUX_DEVTOOLS_EXTENSION__(),
compose(
persistState("dropbox", { slicer }),
applyMiddleware(
thunk,
routerMiddleware(browserHistory),
dropboxMiddleware
)
)
);
};
| // @flow
import type { ThunkOrActionType } from "./actionCreators";
import type { ActionType } from "./actionTypes";
import type { AppState } from "./reducers";
import type { Store as ReduxStore } from "redux";
import { browserHistory } from "react-router";
import { routerMiddleware } from "react-router-redux";
import { compose, createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import persistState from "redux-localstorage";
import reducer from "./reducers";
import { getAuthToken } from "./accessors";
import dropboxMiddleware from "./dropboxMiddleware";
export type Dispatch = (action: ThunkOrActionType) => void;
export type Store = ReduxStore<AppState, ActionType>;
export const getStore = (): Store => {
const slicer = paths => {
return state => {
return Object.assign(
{},
{
dropbox: {
authToken: getAuthToken(state)
}
}
);
};
};
return createStore(
reducer,
window.__REDUX_DEVTOOLS_EXTENSION__ &&
window.__REDUX_DEVTOOLS_EXTENSION__(),
compose(
persistState("dropbox", { slicer }),
applyMiddleware(
thunk,
routerMiddleware(browserHistory),
dropboxMiddleware
)
)
);
};
|
Fix deprecation warning for Symfony 4.2 | <?php declare(strict_types = 1);
namespace AtlassianConnectBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*/
class Configuration implements ConfigurationInterface
{
/**
* @return TreeBuilder
*/
public function getConfigTreeBuilder(): TreeBuilder
{
if (method_exists(TreeBuilder::class, 'getRootNode')) {
$treeBuilder = new TreeBuilder('atlassian_connect');
$rootNode = $treeBuilder->getRootNode();
} else {
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('atlassian_connect');
}
$rootNode
->children()
->variableNode('dev_tenant')->defaultValue(1)->end()
->variableNode('prod')->end()
->variableNode('dev')->end()
->end()
;
return $treeBuilder;
}
}
| <?php declare(strict_types = 1);
namespace AtlassianConnectBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*/
class Configuration implements ConfigurationInterface
{
/**
* @return TreeBuilder
*/
public function getConfigTreeBuilder(): TreeBuilder
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('atlassian_connect');
$rootNode
->children()
->variableNode('dev_tenant')->defaultValue(1)->end()
->variableNode('prod')->end()
->variableNode('dev')->end()
->end()
;
return $treeBuilder;
}
}
|
Make page param of the /app/:page route optional | var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('login', {error: req.flash('error')});
});
router.get('/app/:page?', function (req, res, next) {
res.render('index', {title: req.page});
});
router.get("/api/name", function(req,res){
res.json({
name: 'YEP'
});
});
router.get("/partials/view1", function(req,res){
res.render('partials/partial1',{
pretty: true
});
});
router.get("/partials/view2", function(req,res){
res.render('partials/partial2',{
pretty: true
});
});
router.get("/partials/cc", function(req,res){
res.render('partials/contentcontrol',{
pretty: true
});
});
router.get("/partials/admin", function(req,res){
res.render('partials/admincontrol',{
pretty: true
});
});
module.exports = router;
| var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('login', {error: req.flash('error')});
});
router.get('/app/:page', function (req, res, next) {
res.render('index', {title: req.page});
});
router.get("/api/name", function(req,res){
res.json({
name: 'YEP'
});
});
router.get("/partials/view1", function(req,res){
res.render('partials/partial1',{
pretty: true
});
});
router.get("/partials/view2", function(req,res){
res.render('partials/partial2',{
pretty: true
});
});
router.get("/partials/cc", function(req,res){
res.render('partials/contentcontrol',{
pretty: true
});
});
router.get("/partials/admin", function(req,res){
res.render('partials/admincontrol',{
pretty: true
});
});
module.exports = router;
|
Fix the log autoclean job | from django.conf import settings
import logging
from datetime import datetime, timedelta
from celery.decorators import task
from eve_proxy.models import CachedDocument, ApiAccessLog
@task(ignore_result=True)
def clear_stale_cache(cache_extension=0):
log = clear_stale_cache.get_logger()
time = datetime.utcnow() - timedelta(seconds=cache_extension)
objs = CachedDocument.objects.filter(cached_until__lt=time)
log.info('Removing %s stale cache documents' % objs.count())
objs.delete()
@task(ignore_result=True)
def clear_old_logs():
log = clear_old_logs.get_logger()
time = datetime.utcnow() - timedelta(days=settings.EVE_PROXY_KEEP_LOGS)
objs = ApiAccessLog.objects.filter(time_access__lt=time)
log.info('Removing %s old access logs' % objs.count())
objs.delete()
| from django.conf import settings
import logging
from datetime import datetime, timedelta
from celery.decorators import task
from eve_proxy.models import CachedDocument
@task(ignore_result=True)
def clear_stale_cache(cache_extension=0):
log = clear_stale_cache.get_logger()
time = datetime.utcnow() - timedelta(seconds=cache_extension)
objs = CachedDocument.objects.filter(cached_until__lt=time)
log.info('Removing %s stale cache documents' % objs.count())
objs.delete()
@task(ignore_result=True)
def clear_old_logs():
log = clear_old_logs.get_logger()
time = datetime.utcnow() - timedelta(days=settings.EVE_PROXY_KEEP_LOGS)
objs = ApiAccessLog.objects.filter(time_access__lt=time)
log.info('Removing %s old access logs' % objs.count())
objs.delete()
|
Change comparison from the window to itself.
Checks if the target element's scroll height is bigger than the client height. | ;(function(window, document){
document.addEventListener('touchmove', function(e) {
isScrollElement(e.target) || e.preventDefault();
}, false);
document.addEventListener('touchstart', function(e){
var elem = isScrollElement(e.target);
var startTopScroll = 0;
if(elem) {
startTopScroll = elem.scrollTop;
if(startTopScroll <= 0) { elem.scrollTop = 1; }
if(startTopScroll + elem.clientHeight >= elem.scrollHeight) {
elem.scrollTop = elem.scrollHeight - elem.clientHeight - 1;
}
}
}, false);
function isScrollElement(element) {
while(element) {
if (
(window.getComputedStyle(element).overflow === 'scroll' ||
window.getComputedStyle(element)["overflow-y"] === 'scroll' ||
window.getComputedStyle(element)["overflow-x"] === 'scroll') &&
element.scrollHeight > element.clientHeight
) {
return element;
}
element = element.parentElement;
}
return false;
}
})(window, document);
| ;(function(window, document){
document.addEventListener('touchmove', function(e) {
isScrollElement(e.target) || e.preventDefault();
}, false);
document.addEventListener('touchstart', function(e){
var elem = isScrollElement(e.target);
var startTopScroll = 0;
if(elem) {
startTopScroll = elem.scrollTop;
if(startTopScroll <= 0) { elem.scrollTop = 1; }
if(startTopScroll + elem.clientHeight >= elem.scrollHeight) {
elem.scrollTop = elem.scrollHeight - elem.clientHeight - 1;
}
}
}, false);
function isScrollElement(element) {
while(element) {
if (
(window.getComputedStyle(element).overflow === 'scroll' ||
window.getComputedStyle(element)["overflow-y"] === 'scroll' ||
window.getComputedStyle(element)["overflow-x"] === 'scroll') &&
element.scrollHeight > window.innerHeight
) {
return element;
}
element = element.parentElement;
}
return false;
}
})(window, document);
|
Allow port to be defined by env | /* ==================================
Express server - main server side file
===================================== */
var path = require('path');
var fs = require('fs');
var http = require('http');
var express = require('express');
var app = express();
// block access to src folder
app.get('/js/src/*', function(req, res) {
res.status(404);
res.end();
});
// Serve the ./static/ folder to the public
app.use(express.static('static'));
app.use('/stream', express.static('stream')); // need to optimize this
// Route all requests to static/index.html
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, 'static/index.html'));
});
// Start the server
var server = http.createServer(app);
server.listen(process.env.PORT || 8080);
// Socekt io
var io = require('socket.io')(server);
io.on('connection', function(socket) {
socket.on('control-start', function(data) {
io.emit('start', data);
});
socket.on('control-pause', function(data) {
io.emit('pause');
});
socket.on('report', function(data) {
io.emit('report', data);
});
});
| /* ==================================
Express server - main server side file
===================================== */
var path = require('path');
var fs = require('fs');
var http = require('http');
var express = require('express');
var app = express();
// block access to src folder
app.get('/js/src/*', function(req, res) {
res.status(404);
res.end();
});
// Serve the ./static/ folder to the public
app.use(express.static('static'));
app.use('/stream', express.static('stream')); // need to optimize this
// Route all requests to static/index.html
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, 'static/index.html'));
});
// Start the server
var server = http.createServer(app);
server.listen(8080);
// Socekt io
var io = require('socket.io')(server);
io.on('connection', function(socket) {
socket.on('control-start', function(data) {
io.emit('start', data);
});
socket.on('control-pause', function(data) {
io.emit('pause');
});
socket.on('report', function(data) {
io.emit('report', data);
});
});
|
Update comment, use FBTest.getSelectedNodeBox as soon as FBTest 1.10b5 is out | function runTest()
{
FBTest.sysout("issue5504.START");
FBTest.openNewTab(basePath + "html/5504/issue5504.html", function(win)
{
FBTest.openFirebug();
var panel = FBTest.selectPanel("html");
// Get the selected element and execute "New Attribute" action on it.
var nodeBox = getSelectedNodeBox();
FBTest.executeContextMenuCommand(nodeBox, "htmlNewAttribute", function()
{
var editor = panel.panelNode.getElementsByClassName("textEditorInner").item(0);
FBTest.compare("", editor.value, "The default value must be an empty string");
FBTest.testDone("issue5504.DONE");
});
});
}
// xxxHonza: use the one from FBTest (should be in FBTest 1.10b5)
function getSelectedNodeBox()
{
var panel = FBTest.getPanel("html");
return panel.panelNode.querySelector(".nodeBox.selected");
}
| function runTest()
{
FBTest.sysout("issue5504.START");
FBTest.openNewTab(basePath + "html/5504/issue5504.html", function(win)
{
FBTest.openFirebug();
var panel = FBTest.selectPanel("html");
// Get the selected elemetn and execute "New Attribute" action on it.
var nodeBox = getSelectedNodeBox();
FBTest.executeContextMenuCommand(nodeBox, "htmlNewAttribute", function()
{
var editor = panel.panelNode.getElementsByClassName("textEditorInner").item(0);
FBTest.compare("", editor.value, "The default value must be an empty string");
FBTest.testDone("issue5504.DONE");
});
});
}
// xxxHonza: use the one from FBTest
function getSelectedNodeBox()
{
var panel = FBTest.getPanel("html");
return panel.panelNode.querySelector(".nodeBox.selected");
}
|
HACK: Make sure JSON scheme is a string | /*
package proto defines a set of structures used to negotiate an update between an
an application (the client) and an equinox update service.
*/
package proto
import "time"
type PatchKind string
const (
PatchRaw PatchKind = "none"
PatchBSDIFF PatchKind = "bsdiff"
)
type Request struct {
AppID string `json:"app_id"`
Channel string `json:"channel"`
OS string `json:"os"`
Arch string `json:"arch"`
GoARM string `json:"goarm"`
TargetVersion string `json:"target_version"`
CurrentVersion string `json:"current_version"`
CurrentSHA256 string `json:"current_sha256"`
}
type Response struct {
Available bool `json:"available"`
DownloadURL string `json:"download_url"`
Checksum string `json:"checksum"`
Signature string `json:"signature"`
Patch PatchKind `json:"patch_type,string"`
Version string `json:"version"`
Release Release `json:"release"`
}
type Release struct {
Title string `json:"title"`
Version string `json:"version"`
Description string `json:"description"`
CreateDate time.Time `json:"create_date"`
}
| /*
package proto defines a set of structures used to negotiate an update between an
an application (the client) and an equinox update service.
*/
package proto
import "time"
type PatchKind string
const (
PatchRaw PatchKind = "none"
PatchBSDIFF PatchKind = "bsdiff"
)
type Request struct {
AppID string `json:"app_id"`
Channel string `json:"channel"`
OS string `json:"os"`
Arch string `json:"arch"`
GoARM string `json:"goarm"`
TargetVersion string `json:"target_version"`
CurrentVersion string `json:"current_version"`
CurrentSHA256 string `json:"current_sha256"`
}
type Response struct {
Available bool `json:"available"`
DownloadURL string `json:"download_url"`
Checksum string `json:"checksum"`
Signature string `json:"signature"`
Patch PatchKind `json:"patch_type"`
Version string `json:"version"`
Release Release `json:"release"`
}
type Release struct {
Title string `json:"title"`
Version string `json:"version"`
Description string `json:"description"`
CreateDate time.Time `json:"create_date"`
}
|
Fix project links broken by anchor | """Boxout module for Dribdat projects."""
import pystache
TEMPLATE_PROJECT = r"""
<div class="onebox honeycomb">
<a href="{{link}}"
class="hexagon
{{#is_challenge}}challenge{{/is_challenge}}
{{^is_challenge}}project stage-{{progress}}{{/is_challenge}}">
<div class="hexagontent">
{{#image_url}}
<div class="hexaicon" style="background-image:url('{{image_url}}')"></div>
{{/image_url}}
</div>
</a>
<a href="{{link}}" class="title">{{name}}</a>
<div class="event-detail">
<span>{{event_name}}</span>
<i class="phase">{{phase}}</i>
</div>
<p>{{summary}}</p>
</div>
"""
def box_project(url):
"""Create a OneBox for local projects."""
project_id = url.split('/')[-1].split('#')[0]
if not project_id or not project_id.isnumeric():
return None
from ..user.models import Project
project = Project.query.filter_by(id=int(project_id)).first()
if not project:
return None
pd = project.data
# project.url returns a relative path
pd['link'] = url
return pystache.render(TEMPLATE_PROJECT, pd)
| """Boxout module for Dribdat projects."""
import pystache
TEMPLATE_PROJECT = r"""
<div class="onebox honeycomb">
<a href="{{link}}"
class="hexagon
{{#is_challenge}}challenge{{/is_challenge}}
{{^is_challenge}}project stage-{{progress}}{{/is_challenge}}">
<div class="hexagontent">
{{#image_url}}
<div class="hexaicon" style="background-image:url('{{image_url}}')"></div>
{{/image_url}}
</div>
</a>
<a href="{{link}}" class="title">{{name}}</a>
<div class="event-detail">
<span>{{event_name}}</span>
<i class="phase">{{phase}}</i>
</div>
<p>{{summary}}</p>
</div>
"""
def box_project(url):
"""Create a OneBox for local projects."""
project_id = url.split('/')[-1]
if not project_id:
return None
from ..user.models import Project
project = Project.query.filter_by(id=int(project_id)).first()
if not project:
return None
pd = project.data
# project.url returns a relative path
pd['link'] = url
return pystache.render(TEMPLATE_PROJECT, pd)
|
Increase compatibility with Symfony 4.3 by using proper order of parameters | <?php
namespace Bernard;
use Bernard\Event\EnvelopeEvent;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
class Producer
{
protected $queues;
protected $dispatcher;
/**
* @param QueueFactory $queues
* @param EventDispatcherInterface $dispatcher
*/
public function __construct(QueueFactory $queues, EventDispatcherInterface $dispatcher)
{
$this->queues = $queues;
$this->dispatcher = $dispatcher;
}
/**
* @param Message $message
* @param string|null $queueName
*/
public function produce(Message $message, $queueName = null)
{
$queueName = $queueName ?: Util::guessQueue($message);
$queue = $this->queues->create($queueName);
$queue->enqueue($envelope = new Envelope($message));
$this->dispatch(BernardEvents::PRODUCE, new EnvelopeEvent($envelope, $queue));
}
private function dispatch($eventName, EnvelopeEvent $event)
{
$this->dispatcher instanceof \Symfony\Contracts\EventDispatcher\EventDispatcherInterface
? $this->dispatcher->dispatch($event, $eventName)
: $this->dispatcher->dispatch($eventName, $event);
}
}
| <?php
namespace Bernard;
use Bernard\Event\EnvelopeEvent;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
class Producer
{
protected $queues;
protected $dispatcher;
/**
* @param QueueFactory $queues
* @param EventDispatcherInterface $dispatcher
*/
public function __construct(QueueFactory $queues, EventDispatcherInterface $dispatcher)
{
$this->queues = $queues;
$this->dispatcher = $dispatcher;
}
/**
* @param Message $message
* @param string|null $queueName
*/
public function produce(Message $message, $queueName = null)
{
$queueName = $queueName ?: Util::guessQueue($message);
$queue = $this->queues->create($queueName);
$queue->enqueue($envelope = new Envelope($message));
$this->dispatcher->dispatch(BernardEvents::PRODUCE, new EnvelopeEvent($envelope, $queue));
}
}
|
Add decrypt helper to Entry | from django.db import models
from django.utils.translation import ugettext_lazy as _
from uuidfield import UUIDField
from keybar.utils.crypto import encrypt, decrypt, get_salt
class Entry(models.Model):
id = UUIDField(auto=True, primary_key=True)
created_by = models.ForeignKey('keybar.User')
title = models.TextField(_('Title'), blank=True, default='')
url = models.URLField(blank=True, default='')
identifier = models.TextField(_('Identifier for login'),
help_text=_('Usually a username or email address'))
value = models.TextField(_('The encrypted value for the entry.'),
help_text=_('Usually a password.'))
description = models.TextField(_('Description'), blank=True, default='')
salt = models.BinaryField(null=True, blank=True)
def set_value(self, password, value, salt=None):
if salt is None:
salt = get_salt()
self.value = encrypt(value, password, salt)
self.salt = salt
def decrypt(self, password):
return decrypt(self.value, password, bytes(self.salt))
| from django.db import models
from django.utils.translation import ugettext_lazy as _
from uuidfield import UUIDField
from keybar.utils.crypto import encrypt, get_salt
class Entry(models.Model):
id = UUIDField(auto=True, primary_key=True)
created_by = models.ForeignKey('keybar.User')
title = models.TextField(_('Title'), blank=True, default='')
url = models.URLField(blank=True, default='')
identifier = models.TextField(_('Identifier for login'),
help_text=_('Usually a username or email address'))
value = models.TextField(_('The encrypted value for the entry.'),
help_text=_('Usually a password.'))
description = models.TextField(_('Description'), blank=True, default='')
salt = models.BinaryField(null=True, blank=True)
def set_value(self, password, value, salt=None):
if salt is None:
salt = get_salt()
self.value = encrypt(value, password, salt)
self.salt = salt
|
Add patch_json method to our test Client | import json
import django.test
from .user import UserMixin
class Client(django.test.Client):
def patch_json(self, path, data=None, **kwargs):
return self.patch(path, **self._json_kwargs(data, kwargs))
def post_json(self, path, data=None, **kwargs):
return self.post(path, **self._json_kwargs(data, kwargs))
def put_json(self, path, data=None, **kwargs):
return self.put(path, **self._json_kwargs(data, kwargs))
def patch_json(self, path, data=None, **kwargs):
return self.patch(path, **self._json_kwargs(data, kwargs))
def _json_kwargs(self, data, kwargs):
if data is not None:
data = json.dumps(data)
kwargs['data'] = data
kwargs['content_type'] = 'application/json'
return kwargs
class FunctionalTestCase(django.test.TestCase, UserMixin):
"""Base class for view tests.
It adds the following to Django's `TestCase`:
- Convenient user creation & login
- Convenient POSTs, PUTs, and PATCHes with a JSON body
"""
client_class = Client
| import json
import django.test
from .user import UserMixin
class Client(django.test.Client):
def patch_json(self, path, data=None, **kwargs):
return self.patch(path, **self._json_kwargs(data, kwargs))
def post_json(self, path, data=None, **kwargs):
return self.post(path, **self._json_kwargs(data, kwargs))
def put_json(self, path, data=None, **kwargs):
return self.put(path, **self._json_kwargs(data, kwargs))
def _json_kwargs(self, data, kwargs):
if data is not None:
data = json.dumps(data)
kwargs['data'] = data
kwargs['content_type'] = 'application/json'
return kwargs
class FunctionalTestCase(django.test.TestCase, UserMixin):
"""Base class for view tests.
It adds the following to Django's `TestCase`:
- Convenient user creation & login
- Convenient POSTs, PUTs, and PATCHes with a JSON body
"""
client_class = Client
|
Remove sort function by default for table generated from dict. | from django_excel_to_model.management.commands.model_create_utils.attribute_generator import ClassAttributeCreator
import django_tables2 as tables
def get_django_tables2_from_dict(data_dict):
c = ClassAttributeCreator()
table_meta_class = type("Meta", (), {
"attrs": {'class': 'table table-striped table-bordered table-advance table-hover'},
"orderable": False,
})
table_attributes = {"Meta": table_meta_class}
table_data = {}
for data_key in data_dict.keys():
attr_name = c.refine_attr_name(data_key)
table_attributes[attr_name] = tables.Column(verbose_name=data_key)
table_data[attr_name] = data_dict[data_key]
item_table_class = type("Item" + "DictTableClass", (tables.Table,), table_attributes)
return item_table_class([table_data])
| from django_excel_to_model.management.commands.model_create_utils.attribute_generator import ClassAttributeCreator
import django_tables2 as tables
def get_django_tables2_from_dict(data_dict):
c = ClassAttributeCreator()
table_meta_class = type("Meta", (), {
"attrs": {'class': 'table table-striped table-bordered table-advance table-hover'}}
)
table_attributes = {"Meta": table_meta_class}
table_data = {}
for data_key in data_dict.keys():
attr_name = c.refine_attr_name(data_key)
table_attributes[attr_name] = tables.Column(verbose_name=data_key)
table_data[attr_name] = data_dict[data_key]
item_table_class = type("Item" + "DictTableClass", (tables.Table,), table_attributes)
return item_table_class([table_data])
|
Fix twitter url helper test. | from django.test import TestCase
from nose.tools import ok_
from mrburns.main import views
class TestViewHelpers(TestCase):
def test_twitter_share_url_fn(self):
"""Should return a proper and endoded twitter share url."""
url = views.get_tw_share_url(url='http://example.com', text='The Dude abides.',
hashtags='firefox')
ok_(url.startswith(views.TWITTER_URL + '?'))
ok_('dnt=true' in url)
ok_('hashtags=firefox' in url)
ok_('url=http%3A%2F%2Fexample.com' in url)
ok_('text=The+Dude+abides.' in url)
def test_facebook_share_url_fn(self):
"""Should return a proper and encoded facebook share url."""
url = views.get_fb_share_url('http://example.com')
ok_(url.startswith(views.FB_URL + '?'))
ok_('u=http%3A%2F%2Fexample.com' in url)
| from django.test import TestCase
from nose.tools import ok_
from mrburns.main import views
class TestViewHelpers(TestCase):
def test_twitter_share_url_fn(self):
"""Should return a proper and endoded twitter share url."""
url = views.get_tw_share_url(url='http://example.com', text='The Dude abides.')
ok_(url.startswith(views.TWITTER_URL + '?'))
ok_('dnt=true' in url)
ok_('hashtags=firefox' in url)
ok_('url=http%3A%2F%2Fexample.com' in url)
ok_('text=The+Dude+abides.' in url)
def test_facebook_share_url_fn(self):
"""Should return a proper and encoded facebook share url."""
url = views.get_fb_share_url('http://example.com')
ok_(url.startswith(views.FB_URL + '?'))
ok_('u=http%3A%2F%2Fexample.com' in url)
|
Add generic types for an optional | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* 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.intellij.debugger.streams.trace.impl.handler.type;
import com.intellij.psi.CommonClassNames;
import org.jetbrains.annotations.NotNull;
/**
* @author Vitaliy.Bibaev
*/
public interface GenericType {
@NotNull
String getVariableTypeName();
@NotNull
String getGenericTypeName();
GenericType BOOLEAN = new GenericTypeImpl("boolean", "java.lang.Boolean");
GenericType INT = new GenericTypeImpl("int", "java.lang.Integer");
GenericType DOUBLE = new GenericTypeImpl("double", "java.lang.Double");
GenericType LONG = new GenericTypeImpl("long", "java.lang.Long");
GenericType OBJECT = new ClassTypeImpl("java.lang.Object");
GenericType VOID = new GenericTypeImpl("void", "java.lang.Void");
GenericType OPTIONAL = new ClassTypeImpl(CommonClassNames.JAVA_UTIL_OPTIONAL);
GenericType OPTIONAL_INT = new ClassTypeImpl("java.lang.OptionalInt");
GenericType OPTIONAL_LONG = new ClassTypeImpl("java.lang.OptionalLong");
GenericType OPTIONAL_DOUBLE = new ClassTypeImpl("java.lang.OptionalDouble");
}
| /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* 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.intellij.debugger.streams.trace.impl.handler.type;
import org.jetbrains.annotations.NotNull;
/**
* @author Vitaliy.Bibaev
*/
public interface GenericType {
@NotNull
String getVariableTypeName();
@NotNull
String getGenericTypeName();
GenericType BOOLEAN = new GenericTypeImpl("boolean", "java.lang.Boolean");
GenericType INT = new GenericTypeImpl("int", "java.lang.Integer");
GenericType DOUBLE = new GenericTypeImpl("double", "java.lang.Double");
GenericType LONG = new GenericTypeImpl("long", "java.lang.Long");
GenericType OBJECT = new ClassTypeImpl("java.lang.Object");
GenericType VOID = new GenericTypeImpl("void", "java.lang.Void");
}
|
Revert "break test case, test ci"
This reverts commit f9c54664ff70535ac49b8d54f9a94830d312abc2. | 'use strict';
var path = require('path');
var tape = require('tape');
var app = require('express')();
var request = require('supertest');
require('../')
.argmentApp(app, {
appRoot: path.join(__dirname, 'example'),
assetsDirName: 'assets',
viewsDirName: 'views'
});
tape('partial/a', function (test) {
test.plan(2);
request(app)
.get('/a')
.expect(200)
.end(function (err, res) {
test.notOk(err);
test.equal(res.text.trim(), 'partial a');
});
});
tape('partial/deep', function (test) {
test.plan(2);
request(app)
.get('/deep')
.expect(200)
.end(function (err, res) {
test.notOk(err);
test.equal(res.text.trim(), 'deep partial');
});
});
| 'use strict';
var path = require('path');
var tape = require('tape');
var app = require('express')();
var request = require('supertest');
require('../')
.argmentApp(app, {
appRoot: path.join(__dirname, 'example'),
assetsDirName: 'assets',
viewsDirName: 'views'
});
tape('partial/a', function (test) {
test.plan(2);
request(app)
.get('/a')
.expect(200)
.end(function (err, res) {
test.notOk(err);
test.equal(res.text.trim(), 'partial aaa');
});
});
tape('partial/deep', function (test) {
test.plan(2);
request(app)
.get('/deep')
.expect(200)
.end(function (err, res) {
test.notOk(err);
test.equal(res.text.trim(), 'deep partial');
});
});
|
Integrate the hashtable Unit testcases.
* tests/AllTests.java (suite): added HashtableTests
git-svn-id: f8a4e5e023278da1e04e203c7fe051e3c4285d88@841026 13f79535-47bb-0310-9956-ffa450edef68 | /**
* ====================================================================
* Copyright (c) 2000-2001 CollabNet. All rights reserved.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://subversion.tigris.org/license-1.html.
* If newer versions of this license are posted there, you may use a
* newer version instead, at your option.
*
* This software consists of voluntary contributions made by many
* individuals. For exact contribution history, see the revision
* history and logs, available at http://subversion.tigris.org/.
* ====================================================================
*
*/
import junit.framework.*;
/**
* JUnits tests for the Java subversion binding helper functions
*/
public class AllTests {
public static void main( String [] args )
{
junit.textui.TestRunner.run( suite() );
}
public static Test suite( )
{
TestSuite suite = new TestSuite(
"All JUnit tests for the Java Subversion binding");
//add tests here
//example:
//suite.addTest( new StatusTest() );
suite.addTestSuite( DateTests.class );
suite.addTestSuite( EntryTests.class );
suite.addTestSuite( VectorTests.class );
suite.addTestSuite( HashtableTests.class );
return suite;
}
}
| /**
* ====================================================================
* Copyright (c) 2000-2001 CollabNet. All rights reserved.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://subversion.tigris.org/license-1.html.
* If newer versions of this license are posted there, you may use a
* newer version instead, at your option.
*
* This software consists of voluntary contributions made by many
* individuals. For exact contribution history, see the revision
* history and logs, available at http://subversion.tigris.org/.
* ====================================================================
*
*/
import junit.framework.*;
/**
* JUnits tests for the Java subversion binding helper functions
*/
public class AllTests {
public static void main( String [] args )
{
junit.textui.TestRunner.run( suite() );
}
public static Test suite( )
{
TestSuite suite = new TestSuite(
"All JUnit tests for the Java Subversion binding");
//add tests here
//example:
//suite.addTest( new StatusTest() );
suite.addTestSuite( DateTests.class );
suite.addTestSuite( EntryTests.class );
suite.addTestSuite( VectorTests.class );
return suite;
}
}
|
Make webpack not use hot-loader for prod builds | var path = require('path');
var webpack = require('webpack');
// If this is set, we want to build in production mode
const isProd = process.env.NODE_ENV ? true : false;
const devEntry = [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./src/client/index'
];
const prodEntry = './src/client/index';
const devPlugins = [new webpack.HotModuleReplacementPlugin()];
const prodPlugins = [
new webpack.optimize.UglifyJsPlugin(),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
})
];
const devJsLoaders = ['react-hot', 'babel'];
const prodJsLoaders = ['babel'];
module.exports = {
devtool: isProd ? undefined : 'eval-source-map',
entry: isProd ? prodEntry : devEntry,
output: {
path: path.join(__dirname, 'dist/public'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: isProd ? prodPlugins : devPlugins,
module: {
loaders: [{
test: /\.js$/,
loaders: isProd ? prodJsLoaders : devJsLoaders,
include: path.join(__dirname, 'src')
}]
}
};
| var path = require('path');
var webpack = require('webpack');
// If this is set, we want to build in production mode
const isProd = process.env.NODE_ENV ? true : false;
const devEntry = [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./src/client/index'
];
const prodEntry = './src/client/index';
const devPlugins = [new webpack.HotModuleReplacementPlugin()];
const prodPlugins = [
new webpack.optimize.UglifyJsPlugin(),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
})
];
module.exports = {
devtool: isProd ? undefined : 'eval-source-map',
entry: isProd ? prodEntry : devEntry,
output: {
path: path.join(__dirname, 'dist/public'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: isProd ? prodPlugins : devPlugins,
module: {
loaders: [{
test: /\.js$/,
loaders: ['react-hot', 'babel'],
include: path.join(__dirname, 'src')
}]
}
};
|
CAMEL-8820: Add note its currently only for languages | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel;
/**
* To perform optional initialization on an element after its properties has been configured.
* <p/>
* Currently only languages is supported using this callback.
*/
public interface AfterPropertiesConfigured {
/**
* Callback invoked after the element have configured its properties.
* <p/>
* This allows to perform any post init work.
*
* @param camelContext the Camel Context
*/
void afterPropertiesConfigured(CamelContext camelContext);
}
| /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel;
/**
* To perform optional initialization on an element after its properties has been configured.
*/
public interface AfterPropertiesConfigured {
/**
* Callback invoked after the element have configured its properties.
* <p/>
* This allows to perform any post init work.
*
* @param camelContext the Camel Context
*/
void afterPropertiesConfigured(CamelContext camelContext);
}
|
Fix macos shim for gtk 4 | try:
import gi
from gi.repository import Gtk
if Gtk.get_major_version() == 3:
gi.require_version("GtkosxApplication", "1.0")
else:
raise ValueError()
except ValueError:
macos_init = None
else:
from gi.repository import GtkosxApplication
macos_app = GtkosxApplication.Application.get()
def open_file(macos_app, path, application):
if path == __file__:
return False
app_file_manager = application.get_service("app_file_manager")
app_file_manager.load(path)
return True
def block_termination(macos_app, application):
quit = application.quit()
return not quit
def macos_init(application):
macos_app.connect("NSApplicationOpenFile", open_file, application)
macos_app.connect(
"NSApplicationBlockTermination", block_termination, application
)
| try:
import gi
gi.require_version("GtkosxApplication", "1.0")
except ValueError:
macos_init = None
else:
from gi.repository import GtkosxApplication
macos_app = GtkosxApplication.Application.get()
def open_file(macos_app, path, application):
if path == __file__:
return False
app_file_manager = application.get_service("app_file_manager")
app_file_manager.load(path)
return True
def block_termination(macos_app, application):
quit = application.quit()
return not quit
def macos_init(application):
macos_app.connect("NSApplicationOpenFile", open_file, application)
macos_app.connect(
"NSApplicationBlockTermination", block_termination, application
)
|
Add date range filter to short url service interface | <?php
declare(strict_types=1);
namespace Shlinkio\Shlink\Core\Service;
use Shlinkio\Shlink\Common\Util\DateRange;
use Shlinkio\Shlink\Core\Entity\ShortUrl;
use Shlinkio\Shlink\Core\Exception\ShortUrlNotFoundException;
use Shlinkio\Shlink\Core\Model\ShortUrlMeta;
use Zend\Paginator\Paginator;
interface ShortUrlServiceInterface
{
/**
* @param int $page
* @param string|null $searchQuery
* @param string[] $tags
* @param array|string|null $orderBy
* @return ShortUrl[]|Paginator
* @param DateRange|null $dateRange
*
* @return ShortUrl[]|Paginator
*/
public function listShortUrls(int $page = 1, ?string $searchQuery = null, array $tags = [], $orderBy = null, ?DateRange $dateRange = null);
/**
* @param string[] $tags
* @throws ShortUrlNotFoundException
*/
public function setTagsByShortCode(string $shortCode, array $tags = []): ShortUrl;
/**
* @throws ShortUrlNotFoundException
*/
public function updateMetadataByShortCode(string $shortCode, ShortUrlMeta $shortUrlMeta): ShortUrl;
}
| <?php
declare(strict_types=1);
namespace Shlinkio\Shlink\Core\Service;
use Shlinkio\Shlink\Core\Entity\ShortUrl;
use Shlinkio\Shlink\Core\Exception\ShortUrlNotFoundException;
use Shlinkio\Shlink\Core\Model\ShortUrlMeta;
use Zend\Paginator\Paginator;
interface ShortUrlServiceInterface
{
/**
* @param string[] $tags
* @param array|string|null $orderBy
* @return ShortUrl[]|Paginator
*/
public function listShortUrls(int $page = 1, ?string $searchQuery = null, array $tags = [], $orderBy = null);
/**
* @param string[] $tags
* @throws ShortUrlNotFoundException
*/
public function setTagsByShortCode(string $shortCode, array $tags = []): ShortUrl;
/**
* @throws ShortUrlNotFoundException
*/
public function updateMetadataByShortCode(string $shortCode, ShortUrlMeta $shortUrlMeta): ShortUrl;
}
|
Use Promise.all to fetch project data in parallel | let fetch = require('node-fetch');
const getRepository = async (slug) => {
const response = await fetch(`https://api.github.com/repos/mirego/${slug}`, {
headers: {
Authorization: `token ${process.env.GITHUB_TOKEN}`,
},
});
return await response.json();
};
exports.sourceNodes = async ({actions, createNodeId, createContentDigest}) => {
const projects = require('./data/projects');
const projectPromises = projects.map((project) => {
return getRepository(project.slug).then((repository) => {
actions.createNode({
...project,
id: createNodeId(project.name),
starCount: repository.stargazers_count,
createdAt: repository.created_at,
internal: {
type: 'Project',
contentDigest: createContentDigest(project.name),
},
});
});
});
await Promise.all(projectPromises);
const externalProjects = require('./data/external-projects');
for (let project of externalProjects) {
actions.createNode({
...project,
id: createNodeId(project.name),
internal: {
type: 'ExternalProject',
contentDigest: createContentDigest(project.name),
},
});
}
};
| let fetch = require('node-fetch');
const getRepository = async (slug) => {
const response = await fetch(`https://api.github.com/repos/mirego/${slug}`, {
headers: {
Authorization: `token ${process.env.GITHUB_TOKEN}`,
},
});
return await response.json();
};
exports.sourceNodes = async ({actions, createNodeId, createContentDigest}) => {
const projects = require('./data/projects');
for (let project of projects) {
const repository = await getRepository(project.slug);
actions.createNode({
...project,
id: createNodeId(project.name),
starCount: repository.stargazers_count,
createdAt: repository.created_at,
internal: {
type: 'Project',
contentDigest: createContentDigest(project.name),
},
});
}
const externalProjects = require('./data/external-projects');
for (let project of externalProjects) {
actions.createNode({
...project,
id: createNodeId(project.name),
internal: {
type: 'ExternalProject',
contentDigest: createContentDigest(project.name),
},
});
}
};
|
Fix no topics shown when loading a deck (previous commit broke all) | import rp from 'request-promise';
import {Microservices} from '../../configs/microservices';
import {isEmpty, assignToAllById} from '../../common';
export default {
// fetches the tags data
fetchTagInfo(tags) {
if (isEmpty(tags)) return Promise.resolve([]);
return rp.get({
uri: `${Microservices.tag.uri}/tags`,
qs: {
tagType: 'any',
tagName: tags.map((t) => t.tagName),
paging: false, // this allows for unpaged results
},
useQuerystring: true,
json: true,
});
},
};
| import rp from 'request-promise';
import {Microservices} from '../../configs/microservices';
import {isEmpty, assignToAllById} from '../../common';
export default {
// fetches the tags data
fetchTagInfo(tags) {
if (isEmpty(tags)) return Promise.resolve([]);
return rp.get({
uri: `${Microservices.tag.uri}/tags`,
qs: {
tagType: 'all',
tagName: tags.map((t) => t.tagName),
paging: false, // this allows for unpaged results
},
useQuerystring: true,
json: true,
});
},
};
|
Remove input from fab test | from fabric.api import *
from fabric.colors import *
env.colorize_errors = True
env.hosts = ['sanaprotocolbuilder.me']
env.user = 'root'
env.virtualenv = 'source /usr/local/bin/virtualenvwrapper.sh'
env.project_root = '/opt/sana.protocol_builder'
def test():
local('python sana_builder/manage.py syncdb --noinput')
local('python sana_builder/manage.py test webapp --noinput')
def update_host():
with cd(env.project_root), prefix(env.virtualenv), prefix('workon sana_protocol_builder'):
print(green('Pulling latest revision...'))
run('git pull origin master')
print(green('Installing dependencies...'))
run('pip install -qr requirements.txt')
print(green('Creating database tables...'))
run('python sana_builder/manage.py syncdb --noinput')
print(green('Importing fixtures...'))
run('python sana_builder/manage.py loaddata sana_builder/fixtures/pages.json')
print(green('Collecting static files...'))
run('python sana_builder/manage.py collectstatic --noinput')
print(green('Restarting gunicorn...'))
run('supervisorctl restart gunicorn')
def travis_deploy():
update_host()
def local_deploy():
local('git push origin master')
update_host()
| from fabric.api import *
from fabric.colors import *
env.colorize_errors = True
env.hosts = ['sanaprotocolbuilder.me']
env.user = 'root'
env.virtualenv = 'source /usr/local/bin/virtualenvwrapper.sh'
env.project_root = '/opt/sana.protocol_builder'
def test():
local('python sana_builder/manage.py syncdb')
local('python sana_builder/manage.py test webapp')
def update_host():
with cd(env.project_root), prefix(env.virtualenv), prefix('workon sana_protocol_builder'):
print(green('Pulling latest revision...'))
run('git pull origin master')
print(green('Installing dependencies...'))
run('pip install -qr requirements.txt')
print(green('Creating database tables...'))
run('python sana_builder/manage.py syncdb --noinput')
print(green('Importing fixtures...'))
run('python sana_builder/manage.py loaddata sana_builder/fixtures/pages.json')
print(green('Collecting static files...'))
run('python sana_builder/manage.py collectstatic --noinput')
print(green('Restarting gunicorn...'))
run('supervisorctl restart gunicorn')
def travis_deploy():
update_host()
def local_deploy():
local('git push origin master')
update_host()
|
Define raw_input as input under Python 3 | # -*- coding: utf-8 -*-
"""
example app to test running an app as subprocess within pty
"""
from __future__ import print_function, unicode_literals
import sys, time
PY3 = sys.version_info[0] >= 3
if PY3:
raw_input = input
# http://stackoverflow.com/questions/287871/print-in-terminal-with-colors-using-python
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def main():
print('hi, there!')
time.sleep(0.010)
print('let\'s get to know each other better...')
name = raw_input("Please enter your name: ")
print(bcolors.BOLD + bcolors.UNDERLINE + 'Hi %s, have a nice day!' % name +
bcolors.ENDC)
print('It was a pleasure talking to you...')
if __name__ == '__main__':
main()
| # -*- coding: utf-8 -*-
"""
example app to test running an app as subprocess within pty
"""
from __future__ import print_function, unicode_literals
import time
# http://stackoverflow.com/questions/287871/print-in-terminal-with-colors-using-python
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def main():
print('hi, there!')
time.sleep(0.010)
print('let\'s get to know each other better...')
name = raw_input("Please enter your name: ")
print(bcolors.BOLD + bcolors.UNDERLINE + 'Hi %s, have a nice day!' % name +
bcolors.ENDC)
print('It was a pleasure talking to you...')
if __name__ == '__main__':
main()
|
Change README to be Jmm documentation | //
// Copyright 2016, Yahoo Inc.
// Copyrights licensed under the New BSD License.
// See the accompanying LICENSE file for terms.
//
// [](https://travis-ci.org/jminusminus/jmmexample)
// ## Stability: 1 - Stable
// This is an example project for [Jmm](https://github.com/ricallinson/jmm).
package github.com.jminusminus.jmmexample;
public class Helloworld {
// The following jmm commands will setup up a Jmm workspace, pull down the code for this project, test it, install it and then run it.
//
// mkdir ./jmmtest
// cd ./jmmtest
// jmm here .
// jmm get github.com/jminusminus/simplebdd
// jmm get github.com/jminusminus/jmmexample
// jmm test ./src/github/com/jminusminus/jmmexample
// jmm install ./src/github/com/jminusminus/jmmexample
// jmmexample
public static void main(String args[]) {
System.out.println(Helloworld.msg());
}
// Return a congratulations message.
public static String msg() {
return "Congratulations on your first Jmm application.";
}
}
| //
// Copyright 2016, Yahoo Inc.
// Copyrights licensed under the New BSD License.
// See the accompanying LICENSE file for terms.
//
// [](https://travis-ci.org/jminusminus/jmmexample)
// ## Stability: 1 - Stable
// This is an example project for [Jmm](https://github.com/ricallinson/jmm).
package github.com.jminusminus.jmmexample;
public class Helloworld {
// The following jmm commands will setup up a Jmm workspace, pull down the code for this project, test it, install it and then run it.
//
// mkdir ./jmmtest
// cd ./jmmtest
// jmm here .
// jmm get github.com/jminusminus/simplebdd
// jmm get github.com/jminusminus/jmmexample
// jmm test ./src/github/com/jminusminus/jmmexample
// jmm install ./src/github/com/jminusminus/jmmexample
// jmmexample
public static void main(String args[]) {
System.out.println(Helloworld.msg());
}
// Return a congratulations message.
public static String msg() {
return "Congratulations on your first Jmm application.";
}
}
|
Clear the screen rather than erasing it before refreshing | #!/usr/bin/env python
import curses
import os
import time
from box import Box
from utils import load_yaml
def main(screen):
"""
Draws and redraws the screen.
"""
# Hide the cursor.
curses.curs_set(0)
# Load config from file.
config = load_yaml(os.path.expanduser('~/.suave/config.yml'))
# Create boxes from config.
boxes = []
for box in config:
boxes.append(
Box(
screen=screen,
rows=box['rows'],
columns=box['columns'],
rows_offset=box['rows-offset'],
columns_offset=box['columns-offset'],
command=box['command'],
interval=box['interval'],
)
)
while True:
# Re/draw the screen and boxes.
screen.clear()
screen.refresh()
[box.refresh() for box in boxes]
# Wait before redrawing again.
time.sleep(1)
curses.wrapper(main)
| #!/usr/bin/env python
import curses
import os
import time
from box import Box
from utils import load_yaml
def main(screen):
"""
Draws and redraws the screen.
"""
# Hide the cursor.
curses.curs_set(0)
# Load config from file.
config = load_yaml(os.path.expanduser('~/.suave/config.yml'))
# Create boxes from config.
boxes = []
for box in config:
boxes.append(
Box(
screen=screen,
rows=box['rows'],
columns=box['columns'],
rows_offset=box['rows-offset'],
columns_offset=box['columns-offset'],
command=box['command'],
interval=box['interval'],
)
)
while True:
# Re/draw the screen and boxes.
screen.erase()
screen.refresh()
[box.refresh() for box in boxes]
# Wait before redrawing again.
time.sleep(1)
curses.wrapper(main)
|
Add filter for search input. | import React from 'react'
import preload from '../public/data.json'
import ShowCard from './ShowCard'
const Search = React.createClass({
getInitialState () {
return {
searchTerm: ''
}
},
handleSearchTermChange (event) {
this.setState({searchTerm: event.target.value})
},
render () {
return (
<div className='search'>
<header>
<h1>bizzy bear's video emporium</h1>
<input onChange={this.handleSearchTermChange} value={this.state.searchTerm} type='text' placeholder='search' />
</header>
<div>
{preload.shows
.filter((show) => {
return `${show.title} ${show.description}`.toUpperCase().indexOf(this.state.searchTerm.toUpperCase()) >= 0
})
.map((show) => {
return (
<ShowCard key={show.imdbID} {...show} />
)
})}
</div>
</div>
)
}
})
export default Search
| import React from 'react'
import preload from '../public/data.json'
import ShowCard from './ShowCard'
const Search = React.createClass({
getInitialState () {
return {
searchTerm: ''
}
},
handleSearchTermChange (event) {
this.setState({searchTerm: event.target.value})
},
render () {
return (
<div className='search'>
<header>
<h1>bizzy bear's video emporium</h1>
<input onChange={this.handleSearchTermChange} value={this.state.searchTerm} type='text' placeholder='search' />
</header>
<div>
{preload.shows.map((show) => {
return (
<ShowCard key={show.imdbID} {...show} />
)
})}
</div>
</div>
)
}
})
export default Search
|
Add parent call in boot method | <?php
/*
* This file is part of the FreshDoctrineEnumBundle
*
* (c) Artem Genvald <genvaldartem@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Fresh\DoctrineEnumBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
/**
* FreshDoctrineEnumBundle.
*
* @author Artem Genvald <genvaldartem@gmail.com>
*/
class FreshDoctrineEnumBundle extends Bundle
{
/**
* {@inheritdoc}
*/
public function boot()
{
parent::boot();
$databasePlatform = $this->container->get('doctrine.dbal.default_connection')->getDatabasePlatform();
if (!$databasePlatform->hasDoctrineTypeMappingFor('enum') || 'string' !== $databasePlatform->getDoctrineTypeMapping('enum')) {
$databasePlatform->registerDoctrineTypeMapping('enum', 'string');
}
}
}
| <?php
/*
* This file is part of the FreshDoctrineEnumBundle
*
* (c) Artem Genvald <genvaldartem@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Fresh\DoctrineEnumBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
/**
* FreshDoctrineEnumBundle.
*
* @author Artem Genvald <genvaldartem@gmail.com>
*/
class FreshDoctrineEnumBundle extends Bundle
{
/**
* {@inheritdoc}
*/
public function boot()
{
$databasePlatform = $this->container->get('doctrine.dbal.default_connection')->getDatabasePlatform();
if (!$databasePlatform->hasDoctrineTypeMappingFor('enum') || 'string' !== $databasePlatform->getDoctrineTypeMapping('enum')) {
$databasePlatform->registerDoctrineTypeMapping('enum', 'string');
}
}
}
|
Add missing parameters (seems bug on django 1.7.x) | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def update_total_milestones(apps, schema_editor):
Project = apps.get_model("projects", "Project")
qs = Project.objects.filter(total_milestones__isnull=True)
qs.update(total_milestones=0)
class Migration(migrations.Migration):
dependencies = [
('projects', '0005_membership_invitation_extra_text'),
]
operations = [
migrations.RunPython(update_total_milestones),
migrations.AlterField(
model_name='project',
name='total_milestones',
field=models.IntegerField(null=False, blank=False, default=0, verbose_name='total of milestones'),
),
]
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def update_total_milestones(apps, schema_editor):
Project = apps.get_model("projects", "Project")
qs = Project.objects.filter(total_milestones__isnull=True)
qs.update(total_milestones=0)
class Migration(migrations.Migration):
dependencies = [
('projects', '0005_membership_invitation_extra_text'),
]
operations = [
migrations.RunPython(update_total_milestones),
migrations.AlterField(
model_name='project',
name='total_milestones',
field=models.IntegerField(verbose_name='total of milestones', default=0),
),
]
|
Fix implementation of "wait" block | function Scratch3ControlBlocks(runtime) {
/**
* The runtime instantiating this block package.
* @type {Runtime}
*/
this.runtime = runtime;
}
/**
* Retrieve the block primitives implemented by this package.
* @return {Object.<string, Function>} Mapping of opcode to Function.
*/
Scratch3ControlBlocks.prototype.getPrimitives = function() {
return {
'control_repeat': this.repeat,
'control_forever': this.forever,
'control_wait': this.wait,
'control_stop': this.stop
};
};
Scratch3ControlBlocks.prototype.repeat = function(argValues, util) {
// Initialize loop
if (util.stackFrame.loopCounter === undefined) {
util.stackFrame.loopCounter = parseInt(argValues[0]); // @todo arg
}
// Decrease counter
util.stackFrame.loopCounter--;
// If we still have some left, start the substack
if (util.stackFrame.loopCounter >= 0) {
util.startSubstack();
}
};
Scratch3ControlBlocks.prototype.forever = function(argValues, util) {
util.startSubstack();
};
Scratch3ControlBlocks.prototype.wait = function(argValues, util) {
util.yield();
util.timeout(function() {
util.done();
}, 1000 * argValues.DURATION);
};
Scratch3ControlBlocks.prototype.stop = function() {
// @todo - don't use this.runtime
this.runtime.stopAll();
};
module.exports = Scratch3ControlBlocks;
| function Scratch3ControlBlocks(runtime) {
/**
* The runtime instantiating this block package.
* @type {Runtime}
*/
this.runtime = runtime;
}
/**
* Retrieve the block primitives implemented by this package.
* @return {Object.<string, Function>} Mapping of opcode to Function.
*/
Scratch3ControlBlocks.prototype.getPrimitives = function() {
return {
'control_repeat': this.repeat,
'control_forever': this.forever,
'control_wait': this.wait,
'control_stop': this.stop
};
};
Scratch3ControlBlocks.prototype.repeat = function(argValues, util) {
// Initialize loop
if (util.stackFrame.loopCounter === undefined) {
util.stackFrame.loopCounter = parseInt(argValues[0]); // @todo arg
}
// Decrease counter
util.stackFrame.loopCounter--;
// If we still have some left, start the substack
if (util.stackFrame.loopCounter >= 0) {
util.startSubstack();
}
};
Scratch3ControlBlocks.prototype.forever = function(argValues, util) {
util.startSubstack();
};
Scratch3ControlBlocks.prototype.wait = function(argValues, util) {
util.yield();
util.timeout(function() {
util.done();
}, 1000 * parseFloat(argValues[0]));
};
Scratch3ControlBlocks.prototype.stop = function() {
// @todo - don't use this.runtime
this.runtime.stopAll();
};
module.exports = Scratch3ControlBlocks;
|
Implement comparing of two Part objects | package it.sieradzki.userscript_parser.metadata;
/**
* Implementation of <a href="https://developer.mozilla.org/en/Toolkit_version_format">Toolkit version format</a>
*/
public class Version implements Comparable<Version> {
private Part[] versionParts;
public Version(String versionString) {
}
@Override
public int compareTo(Version o) {
for (int i = 0; i < Math.min(versionParts.length, o.versionParts.length); i++) {
int comparedPartResult = versionParts[i].compareTo(o.versionParts[i]);
if (comparedPartResult != 0) {
return comparedPartResult;
}
}
return versionParts.length - o.versionParts.length;
}
private static class Part implements Comparable<Part> {
private Integer numberA;
private String stringB;
private Integer numberC;
private String stringD;
@Override
public int compareTo(Part o) {
int comparedFieldResult;
comparedFieldResult = numberA.compareTo(o.numberA);
if (comparedFieldResult != 0) {
return comparedFieldResult;
}
comparedFieldResult = stringB.compareTo(o.stringB);
if (comparedFieldResult != 0) {
return comparedFieldResult;
}
comparedFieldResult = numberC.compareTo(o.numberC);
if (comparedFieldResult != 0) {
return comparedFieldResult;
}
return numberA.compareTo(o.numberA);
}
}
}
| package it.sieradzki.userscript_parser.metadata;
/**
* Implementation of <a href="https://developer.mozilla.org/en/Toolkit_version_format">Toolkit version format</a>
*/
public class Version implements Comparable<Version> {
private Part[] versionParts;
public Version(String versionString) {
}
@Override
public int compareTo(Version o) {
for (int i = 0; i < Math.min(versionParts.length, o.versionParts.length); i++) {
int comparedPartResult = versionParts[i].compareTo(o.versionParts[i]);
if (comparedPartResult != 0) {
return comparedPartResult;
}
}
return versionParts.length - o.versionParts.length;
}
private static class Part implements Comparable<Part> {
private Integer numberA;
private String stringB;
private Integer numberC;
private String stringD;
@Override
public int compareTo(Part o) {
return 0;
}
}
}
|
Use ref callbacks to get component instance | /**
* @fileoverview Test helpers for mounting/unmounting components.
*
* This module has side effects.
*/
import React from 'react';
import ReactDOM from 'react-dom';
import $ from 'jquery';
const _container = document.createElement('div');
/**
* Render the given component.
*
* @param {ReactElement} element
*
* @returns {Object} The component instance.
*/
export function render(element) {
let component;
ReactDOM.render(
React.cloneElement(element, { ref: inst => { component = inst; } }),
_container
);
return component;
}
/**
* Render the given component.
*
* @param {ReactElement} element
*
* @returns {jQuery} The component's root DOM node wrapped in jQuery.
*/
export function $render(element) {
render(element);
// Return the first (and only) child in the container wrapped in jQuery.
return $(_container).children().eq(0);
}
/**
* Unmount the currently mounted component.
*/
export function unmount() {
// unmountComponentAtNode will return `false` if there was no component
// mounted at the given node. That can happen when the component was
// unmounted inside a test i.e. to test cleanup logic.
ReactDOM.unmountComponentAtNode(_container);
}
/**
* Unmount the currently mounted component after each test.
*/
afterEach(function() {
unmount();
});
| /**
* @fileoverview Test helpers for mounting/unmounting components.
*
* This module has side effects.
*/
import ReactDOM from 'react-dom';
import $ from 'jquery';
const _container = document.createElement('div');
/**
* Render the given component.
*
* @param {ReactElement} element
*
* @returns {Object} The component instance.
*/
export function render(element) {
// TODO: use ref callbacks to get the instance
return ReactDOM.render(element, _container);
}
/**
* Render the given component.
*
* @param {ReactElement} element
*
* @returns {jQuery} The component's root DOM node wrapped in jQuery.
*/
export function $render(element) {
render(element);
// Return the first (and only) child in the container wrapped in jQuery.
return $(_container).children().eq(0);
}
/**
* Unmount the currently mounted component.
*/
export function unmount() {
// unmountComponentAtNode will return `false` if there was no component
// mounted at the given node. That can happen when the component was
// unmounted inside a test i.e. to test cleanup logic.
ReactDOM.unmountComponentAtNode(_container);
}
/**
* Unmount the currently mounted component after each test.
*/
afterEach(function() {
unmount();
});
|
Call the currect RecursiveIteratorIterator function | <?php
namespace TomPHP\ConfigServiceProvider;
use RecursiveArrayIterator;
use RecursiveIteratorIterator;
final class ApplicationConfigIterator extends RecursiveIteratorIterator
{
/**
* @var string[]
*/
private $path = [];
/**
* @var string
*/
private $separator;
/**
* @param ApplicationConfig $config
*/
public function __construct(ApplicationConfig $config)
{
parent::__construct(
new RecursiveArrayIterator($config->asArray()),
RecursiveIteratorIterator::SELF_FIRST
);
$this->separator = $config->getSeparator();
}
public function key()
{
return implode($this->separator, array_merge($this->path, [parent::key()]));
}
public function next()
{
if ($this->callHasChildren()) {
array_push($this->path, parent::key());
}
parent::next();
}
public function rewind()
{
$this->path = [];
parent::rewind();
}
public function endChildren()
{
array_pop($this->path);
}
}
| <?php
namespace TomPHP\ConfigServiceProvider;
use RecursiveArrayIterator;
use RecursiveIteratorIterator;
final class ApplicationConfigIterator extends RecursiveIteratorIterator
{
/**
* @var string[]
*/
private $path = [];
/**
* @var string
*/
private $separator;
/**
* @param ApplicationConfig $config
*/
public function __construct(ApplicationConfig $config)
{
parent::__construct(
new RecursiveArrayIterator($config->asArray()),
RecursiveIteratorIterator::SELF_FIRST
);
$this->separator = $config->getSeparator();
}
public function key()
{
return implode($this->separator, array_merge($this->path, [parent::key()]));
}
public function next()
{
if ($this->hasChildren()) {
array_push($this->path, parent::key());
}
parent::next();
}
public function rewind()
{
$this->path = [];
parent::rewind();
}
public function endChildren()
{
array_pop($this->path);
}
}
|
Change needed to make SpecificPricingExtension work for a selected group | <?php
class SpecificPricingExtension extends DataExtension{
private static $has_many = array(
"SpecificPrices" => "SpecificPrice"
);
function updateCMSFields(FieldList $fields) {
if($tab = $fields->fieldByName("Root.Pricing")){
$fields = $tab->Fields();
}
if($this->owner->isInDB() && ($fields->fieldByName("BasePrice") || $fields->fieldByName("Price"))){
$fields->push(
GridField::create("SpecificPrices","Specific Prices", $this->owner->SpecificPrices(),
GridFieldConfig_RecordEditor::create()
)
);
}
}
function updateSellingPrice(&$price){
if($specificprice = SpecificPrice::filter(
$this->owner->SpecificPrices()
->filter("Price:LessThan", $price), Member::currentUser()
)->first()){
if ($specificprice->Price > 0) {
$price = $specificprice->Price;
} elseif ($specificprice->DiscountPercent > 0) {
$price *= 1.0 - $specificprice->DiscountPercent;
} else {
// this would mean both discount and price were 0
$price = 0;
}
}
}
}
| <?php
class SpecificPricingExtension extends DataExtension{
private static $has_many = array(
"SpecificPrices" => "SpecificPrice"
);
function updateCMSFields(FieldList $fields) {
if($tab = $fields->fieldByName("Root.Pricing")){
$fields = $tab->Fields();
}
if($this->owner->isInDB() && ($fields->fieldByName("BasePrice") || $fields->fieldByName("Price"))){
$fields->push(
GridField::create("SpecificPrices","Specific Prices", $this->owner->SpecificPrices(),
GridFieldConfig_RecordEditor::create()
)
);
}
}
function updateSellingPrice(&$price){
if($specificprice = SpecificPrice::filter(
$this->owner->SpecificPrices()
->filter("Price:LessThan", $price)
)->first()){
if ($specificprice->Price > 0) {
$price = $specificprice->Price;
} elseif ($specificprice->DiscountPercent > 0) {
$price *= 1.0 - $specificprice->DiscountPercent;
} else {
// this would mean both discount and price were 0
$price = 0;
}
}
}
} |
Use request.data to access file uploads | from rest_framework.exceptions import ValidationError
class ModelSerializerMixin(object):
"""Provides generic model serializer classes to views."""
model_serializer_class = None
def get_serializer_class(self):
if self.serializer_class:
return self.serializer_class
class DefaultSerializer(self.model_serializer_class):
class Meta:
model = self.queryset.model
return DefaultSerializer
class QueryFormMixin(object):
"""Provides form based handling of GET or POST requests."""
query_form_class = None
def clean_params(self):
"""Returns a validated form dict from Request parameters."""
form = self.query_form_class(
self.request.query_params or self.request.data)
if form.is_valid():
return form.cleaned_data
raise ValidationError(form.errors)
| from rest_framework.exceptions import ValidationError
class ModelSerializerMixin(object):
"""Provides generic model serializer classes to views."""
model_serializer_class = None
def get_serializer_class(self):
if self.serializer_class:
return self.serializer_class
class DefaultSerializer(self.model_serializer_class):
class Meta:
model = self.queryset.model
return DefaultSerializer
class QueryFormMixin(object):
"""Provides form based handling of GET or POST requests."""
query_form_class = None
def clean_params(self):
"""Returns a validated form dict from Request parameters."""
form = self.query_form_class(
self.request.query_params or self.request.data,
self.request.FILES or None)
if form.is_valid():
return form.cleaned_data
raise ValidationError(form.errors)
|
Remove refillQueue now that cells reinsert themselves when their number changes from 0 or not. | package sudoku
import (
"fmt"
)
type SolveDirections []*SolveStep
const (
ONLY_LEGAL_NUMBER = iota
)
type SolveStep struct {
Row int
Col int
Num int
Technique SolveTechnique
}
type SolveTechnique interface {
Name() string
Description(*SolveStep) string
Apply(*Grid) *SolveStep
}
var techniques []SolveTechnique
func init() {
//TODO: init techniques with enough space
techniques = append(techniques, onlyLegalNumberTechnique{})
}
type onlyLegalNumberTechnique struct {
}
func (self onlyLegalNumberTechnique) Name() string {
return "Only Legal Number"
}
func (self onlyLegalNumberTechnique) Description(step *SolveStep) string {
return fmt.Sprintf("%d is the only remaining valid number for that cell", step.Num)
}
func (self onlyLegalNumberTechnique) Apply(grid *Grid) *SolveStep {
//This will be a random item
obj := grid.queue.NewGetter().GetSmallerThan(2)
if obj == nil {
//There weren't any cells with one option.
return nil
}
cell := obj.(*Cell)
cell.SetNumber(cell.implicitNumber())
return &SolveStep{cell.Row, cell.Col, cell.Number(), self}
}
func (self *Grid) HumanSolve() *SolveDirections {
return nil
}
| package sudoku
import (
"fmt"
)
type SolveDirections []*SolveStep
const (
ONLY_LEGAL_NUMBER = iota
)
type SolveStep struct {
Row int
Col int
Num int
Technique SolveTechnique
}
type SolveTechnique interface {
Name() string
Description(*SolveStep) string
Apply(*Grid) *SolveStep
}
var techniques []SolveTechnique
func init() {
//TODO: init techniques with enough space
techniques = append(techniques, onlyLegalNumberTechnique{})
}
type onlyLegalNumberTechnique struct {
}
func (self onlyLegalNumberTechnique) Name() string {
return "Only Legal Number"
}
func (self onlyLegalNumberTechnique) Description(step *SolveStep) string {
return fmt.Sprintf("%d is the only remaining valid number for that cell", step.Num)
}
func (self onlyLegalNumberTechnique) Apply(grid *Grid) *SolveStep {
grid.refillQueue()
//This will be a random item
obj := grid.queue.NewGetter().GetSmallerThan(2)
if obj == nil {
//There weren't any cells with one option.
return nil
}
cell := obj.(*Cell)
cell.SetNumber(cell.implicitNumber())
return &SolveStep{cell.Row, cell.Col, cell.Number(), self}
}
func (self *Grid) HumanSolve() *SolveDirections {
return nil
}
|
Remove code overriding default jasmine timeout interval | /**
* Created by pivotal on 5/19/17.
*/
require('dotenv').config()
describe('chrome extension is loaded properly when feature tests run', function () {
it('creates a WWLTW chore in the backlog', function () {
browser.setValue("[data-test='tracker-api-token'] input", process.env.TEST_PIVOTAL_TRACKER_TOKEN)
browser.click('button=Submit')
browser.pause(1000)
browser.click('label=Test Project')
browser.pause(1000)
browser.url('https://www.pivotaltracker.com/signin')
browser.setValue("#credentials_username", process.env.TEST_PIVOTAL_TRACKER_USERNAME)
browser.click("#login_type_check_form input[type='submit']")
browser.setValue("#credentials_password", process.env.TEST_PIVOTAL_TRACKER_PASSWORD )
browser.click("#login_type_check_form input[type='submit']")
browser.click("a=Test Project")
browser.pause(1000)
expect(browser.getText(".story_name*=WWLTW for the week of")).toMatch(/WWLTW for the week of \d{1,2}\/\d{1,2}/)
})
}) | /**
* Created by pivotal on 5/19/17.
*/
require('dotenv').config()
describe('chrome extension is loaded properly when feature tests run', function () {
beforeEach(function () {
jasmine.getEnv().defaultTimeoutInterval = 1000000
})
it('creates a WWLTW chore in the backlog', function () {
browser.setValue("[data-test='tracker-api-token'] input", process.env.TEST_PIVOTAL_TRACKER_TOKEN)
browser.click('button=Submit')
browser.pause(1000)
browser.click('label=Test Project')
browser.pause(1000)
browser.url('https://www.pivotaltracker.com/signin')
browser.setValue("#credentials_username", process.env.TEST_PIVOTAL_TRACKER_USERNAME)
browser.click("#login_type_check_form input[type='submit']")
browser.setValue("#credentials_password", process.env.TEST_PIVOTAL_TRACKER_PASSWORD )
browser.click("#login_type_check_form input[type='submit']")
browser.click("a=Test Project")
browser.pause(1000)
expect(browser.getText(".story_name*=WWLTW for the week of")).toMatch(/WWLTW for the week of \d{1,2}\/\d{1,2}/)
})
}) |
Update paths in CSS build | // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var path = require('path');
var spawn = require('spawn-sync');
var source = './static/widgets/less/widgets.less';
var css_destination = './static/widgets/css/widgets.css';
var min_destination = './static/widgets/css/widgets.min.css';
function run(cmd) {
// run a command, with some help:
// - echo command
// - die on failure
// - show stdout/err
console.log('> ' + cmd.join(' '));
var p = spawn(cmd[0], cmd.slice(1));
process.stdout.write(p.stdout.toString());
process.stderr.write(p.stderr.toString());
if (p.status !== 0) {
console.error("`%s` failed with status=%s", cmd.join(' '), p.status);
process.exit(p.status);
}
return p.stdout.toString();
}
run(['lessc',
'--include-path=./static/components',
source,
css_destination,
]);
run(['cleancss',
'--source-map',
'--skip-restructuring ',
'-o',
min_destination,
css_destination]);
| // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var path = require('path');
var spawn = require('spawn-sync');
var source = './ipywidgets/static/widgets/less/widgets.less';
var css_destination = './ipywidgets/static/widgets/css/widgets.css';
var min_destination = './ipywidgets/static/widgets/css/widgets.min.css';
function run(cmd) {
// run a command, with some help:
// - echo command
// - die on failure
// - show stdout/err
console.log('> ' + cmd.join(' '));
var p = spawn(cmd[0], cmd.slice(1));
process.stdout.write(p.stdout.toString());
process.stderr.write(p.stderr.toString());
if (p.status !== 0) {
console.error("`%s` failed with status=%s", cmd.join(' '), p.status);
process.exit(p.status);
}
return p.stdout.toString();
}
run(['lessc',
'--include-path=./ipywidgets/static/components',
source,
css_destination,
]);
run(['cleancss',
'--source-map',
'--skip-restructuring ',
'-o',
min_destination,
css_destination]);
|
Use GitBook 3 page.content instead of deprecated page.sections | 'use strict';
var cheerio = require('cheerio');
var _ = require('underscore');
var multiline = require('multiline');
var template = _.template(multiline(function() {
/*
<a href="<%= url %>" title="<%= title %>" class="fancybox">
<img src="<%= url %>" alt="<%= title %>"></img>
</a>
*/
}));
module.exports = {
book: {
assets: './assets',
js: [
'jquery.min.js',
'jquery.fancybox.pack.js',
'jquery.fancybox-buttons.js',
'plugin.js'
],
css: [
'jquery.fancybox.css',
'jquery.fancybox-buttons.css'
]
},
hooks: {
page: function(page) {
var $ = cheerio.load(page.content);
$('img').each(function(index, img) {
var $img = $(img);
$img.replaceWith(template({
url: $img.attr('src'),
title: $img.attr('alt')
}));
});
page.content = $.html();
return page;
}
}
};
| 'use strict';
var cheerio = require('cheerio');
var _ = require('underscore');
var multiline = require('multiline');
var template = _.template(multiline(function() {
/*
<a href="<%= url %>" title="<%= title %>" class="fancybox">
<img src="<%= url %>" alt="<%= title %>"></img>
</a>
*/
}));
module.exports = {
book: {
assets: './assets',
js: [
'jquery.min.js',
'jquery.fancybox.pack.js',
'jquery.fancybox-buttons.js',
'plugin.js'
],
css: [
'jquery.fancybox.css',
'jquery.fancybox-buttons.css'
]
},
hooks: {
page: function(page) {
_.each(page.sections, function(section) {
var $ = cheerio.load(section.content);
$('img').each(function(index, img) {
var $img = $(img);
$img.replaceWith(template({
url: $img.attr('src'),
title: $img.attr('alt')
}));
});
section.content = $.html();
});
return page;
}
}
};
|
Fix for possible deref of cleaned up source component
@rev dwidjaja@ | /*
* Copyright (C) 2012 salesforce.com, inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
{
handleSearch : function(cmp,event){
var searchTerm = event.getParam('searchTerm') || (event.getSource() && event.getSource().getElement().value);
if (searchTerm.length > 0) {
var results_location = "#help?topic=searchResults&searchTerm=" + escape(searchTerm);
window.location = results_location;
}
}
} | /*
* Copyright (C) 2012 salesforce.com, inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
{
handleSearch : function(cmp,event){
var searchTerm = event.getParam('searchTerm') || event.getSource().getElement().value;
if (searchTerm.length > 0) {
var results_location = "#help?topic=searchResults&searchTerm=" + escape(searchTerm);
window.location = results_location;
}
}
} |
Add statements to run id_iterators tests
Closes #8 | from unittest import TestCase, main
import re
from uuid import UUID
from jsonrpcclient.id_iterators import hex_iterator, uuid_iterator, \
random_iterator
class TestHexIterator(TestCase):
def test(self):
i = hex_iterator()
self.assertEqual('1', next(i))
i = hex_iterator(9)
self.assertEqual('9', next(i))
self.assertEqual('a', next(i))
class TestUUIDIterator(TestCase):
def test(self):
i = uuid_iterator()
# Raise ValueError if badly formed hexadecimal UUID string
UUID(next(i), version=4)
class TestRandomIterator(TestCase):
def test(self):
i = random_iterator()
self.assertTrue(re.match('^[0-9,a-z]{8}$', next(i)))
if __name__ == '__main__':
main()
| from unittest import TestCase, main
import re
from uuid import UUID
from jsonrpcclient.id_iterators import hex_iterator, uuid_iterator, \
random_iterator
class TestHexIterator(TestCase):
def test(self):
i = hex_iterator()
self.assertEqual('1', next(i))
i = hex_iterator(9)
self.assertEqual('9', next(i))
self.assertEqual('a', next(i))
class TestUUIDIterator(TestCase):
def test(self):
i = uuid_iterator()
# Raise ValueError if badly formed hexadecimal UUID string
UUID(next(i), version=4)
class TestRandomIterator(TestCase):
def test(self):
i = random_iterator()
self.assertTrue(re.match('^[0-9,a-z]{8}$', next(i)))
|
Update do version 0.1.1 which should hopefully trigger automatic pypi deployment | import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-game-info',
version='0.1.1',
packages=['game_info'],
include_package_data=True,
license='BSD License',
description='A django app to gather information from game servers.',
long_description=README,
url='https://github.com/Azelphur-Servers/django-game-info',
author='Alfie "Azelphur" Day',
author_email='support@azelphur.com',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
| import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-game-info',
version='0.1',
packages=['game_info'],
include_package_data=True,
license='BSD License',
description='A django app to gather information from game servers.',
long_description=README,
url='https://github.com/Azelphur-Servers/django-game-info',
author='Alfie "Azelphur" Day',
author_email='support@azelphur.com',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
|
Update to turn off chunking | /* eslint-disable no-undef */
const FastBootAppServer = require('fastboot-app-server');
const fetch = require('node-fetch');
let server = new FastBootAppServer({
distPath: 'dist',
gzip: true, // Optional - Enables gzip compression.
host: '0.0.0.0', // Optional - Sets the host the server listens on.
port: 4000, // Optional - Sets the port the server listens on (defaults to the PORT env var or 3000).
buildSandboxGlobals(defaultGlobals) {
// Optional - Make values available to the Ember app running in the FastBoot server, e.g. "MY_GLOBAL" will be available as "GLOBAL_VALUE"
return Object.assign({}, defaultGlobals, {
btoa: function (str) {
return Buffer.from(str).toString('base64');
},
fetch,
});
},
// This should be false for Twitter/Linkedin according to https://github.com/ember-fastboot/ember-cli-fastboot/tree/master/packages/fastboot-app-server#twitter-and-linkedin
chunkedResponse: false, // Optional - Opt-in to chunked transfer encoding, transferring the head, body and potential shoeboxes in separate chunks. Chunked transfer encoding should have a positive effect in particular when the app transfers a lot of data in the shoebox.
});
server.start();
| /* eslint-disable no-undef */
const FastBootAppServer = require('fastboot-app-server');
const fetch = require('node-fetch');
let server = new FastBootAppServer({
distPath: 'dist',
gzip: true, // Optional - Enables gzip compression.
host: '0.0.0.0', // Optional - Sets the host the server listens on.
port: 4000, // Optional - Sets the port the server listens on (defaults to the PORT env var or 3000).
buildSandboxGlobals(defaultGlobals) {
// Optional - Make values available to the Ember app running in the FastBoot server, e.g. "MY_GLOBAL" will be available as "GLOBAL_VALUE"
return Object.assign({}, defaultGlobals, {
btoa: function (str) {
return Buffer.from(str).toString('base64');
},
fetch,
});
},
chunkedResponse: true, // Optional - Opt-in to chunked transfer encoding, transferring the head, body and potential shoeboxes in separate chunks. Chunked transfer encoding should have a positive effect in particular when the app transfers a lot of data in the shoebox.
});
server.start();
|
Correct UTF encoding of lgogdownloader json file. | #!/usr/bin/env python3
import json
import os
import config
from models import Game, Status, session
from flask import Flask, render_template, redirect, url_for
app = Flask(__name__)
@app.route('/')
def library():
with open(os.path.join(config.lgog_cache, 'gamedetails.json'), encoding='utf-8') as f:
data = json.load(f)
if data is None:
return "Unable to load the GOG games database."
for game in data['games']:
game['download'] = -1
state = session.query(Game.state).filter(Game.name == game['gamename']).one()
if state == 'queue':
game['download'] = 0
elif state == 'running':
game['download'] = 0
elif os.path.isdir(os.path.join(config.lgog_library, game['gamename'])):
game['download'] = 1
return render_template('library.html', data=data['games'])
@app.route('/download/<game>')
def download(game):
db_game = session.query(Game).filter(Game.name == game).one()
if db_game.state != 'running':
db_game.state = 'queue'
session.commit()
return redirect(url_for('library'))
| #!/usr/bin/env python3
import json
import os
import config
from models import Game, Status, session
from flask import Flask, render_template, redirect, url_for
app = Flask(__name__)
@app.route('/')
def library():
with open(os.path.join(config.lgog_cache, 'gamedetails.json')) as f:
data = json.load(f)
if data is None:
return "Unable to load the GOG games database."
for game in data['games']:
game['download'] = -1
state = session.query(Game.state).filter(Game.name == game['gamename']).one()
if state == 'queue':
game['download'] = 0
elif state == 'running':
game['download'] = 0
elif os.path.isdir(os.path.join(config.lgog_library, game['gamename'])):
game['download'] = 1
return render_template('library.html', data=data['games'])
@app.route('/download/<game>')
def download(game):
db_game = session.query(Game).filter(Game.name == game).one()
if db_game.state != 'running':
db_game.state = 'queue'
session.commit()
return redirect(url_for('library'))
|
Remove binding to singleton as Configuration has already Singleton scope
Change-Id: Ia43162be3ea477e10401c914f424949de4e18d6e
Signed-off-by: Jacek Centkowski <ce4a73803a80af51ece4477dad59cc7b1801c73e@collab.net> | // Copyright (C) 2017 The Android Open Source Project
//
// 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.googlesource.gerrit.plugins.webhooks;
import com.google.gerrit.common.EventListener;
import com.google.gerrit.extensions.config.FactoryModule;
import com.google.gerrit.extensions.registration.DynamicSet;
import com.google.inject.Scopes;
import java.util.concurrent.ScheduledExecutorService;
import org.apache.http.impl.client.CloseableHttpClient;
public class Module extends FactoryModule {
@Override
protected void configure() {
bind(ScheduledExecutorService.class)
.annotatedWith(WebHooksExecutor.class)
.toProvider(ExecutorProvider.class);
bind(CloseableHttpClient.class).toProvider(HttpClientProvider.class).in(Scopes.SINGLETON);
factory(PostTask.Factory.class);
DynamicSet.bind(binder(), EventListener.class).to(EventHandler.class);
}
}
| // Copyright (C) 2017 The Android Open Source Project
//
// 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.googlesource.gerrit.plugins.webhooks;
import com.google.gerrit.common.EventListener;
import com.google.gerrit.extensions.config.FactoryModule;
import com.google.gerrit.extensions.registration.DynamicSet;
import com.google.inject.Scopes;
import java.util.concurrent.ScheduledExecutorService;
import org.apache.http.impl.client.CloseableHttpClient;
public class Module extends FactoryModule {
@Override
protected void configure() {
bind(ScheduledExecutorService.class)
.annotatedWith(WebHooksExecutor.class)
.toProvider(ExecutorProvider.class);
bind(Configuration.class).in(Scopes.SINGLETON);
bind(CloseableHttpClient.class).toProvider(HttpClientProvider.class).in(Scopes.SINGLETON);
factory(PostTask.Factory.class);
DynamicSet.bind(binder(), EventListener.class).to(EventHandler.class);
}
}
|
Add bugfix - needed to increment outstanding at point of add | // Package throttled implements various helpers to manage the lifecycle of goroutines.
package throttled
// WaitGroup limits the number of concurrent goroutines that can execute at once.
type WaitGroup struct {
throttle int
completed chan bool
outstanding int
}
// NewWaitGroup instantiates a new WaitGroup with the given throttle.
func NewWaitGroup(throttle int) *WaitGroup {
return &WaitGroup{
outstanding: 0,
throttle: throttle,
completed: make(chan bool, throttle),
}
}
// Add will block until the number of goroutines being throttled
// has fallen below the throttle.
func (w *WaitGroup) Add() {
w.outstanding++
if w.outstanding > w.throttle {
select {
case <-w.completed:
w.outstanding--
return
}
}
}
// Done signal that a goroutine has completed.
func (w *WaitGroup) Done() {
w.completed <- true
}
// Wait until all of the throttled goroutines have signaled they are done.
func (w *WaitGroup) Wait() {
if w.outstanding == 0 {
return
}
for w.outstanding > 0 {
select {
case <-w.completed:
w.outstanding--
}
}
}
| // Package throttled implements various helpers to manage the lifecycle of goroutines.
package throttled
// WaitGroup limits the number of concurrent goroutines.
type WaitGroup struct {
throttle int
completed chan bool
outstanding int
}
// NewWaitGroup instantiates a new WaitGroup with the given throttle.
func NewWaitGroup(throttle int) *WaitGroup {
return &WaitGroup{
outstanding: 0,
throttle: throttle,
completed: make(chan bool, throttle),
}
}
// Add will block until the number of goroutines being throttled
// has fallen below the throttle
func (w *WaitGroup) Add() {
if w.outstanding+1 > w.throttle {
select {
case <-w.completed:
w.outstanding--
return
}
}
w.outstanding++
}
// Done signal that a goroutine has completed
func (w *WaitGroup) Done() {
w.completed <- true
}
// Wait until all of the throttled goroutines have signaled they are done
func (w *WaitGroup) Wait() {
if w.outstanding == 0 {
return
}
for w.outstanding > 0 {
select {
case <-w.completed:
w.outstanding--
}
}
}
|
Allow only non falsy header values in toObject method |
function Headers (headers) {
for (var key in headers) {
this[key] = headers[key]
}
}
Headers.prototype.get = function (header) {
return this._value(header)
}
Headers.prototype.set = function (header, value) {
var name = this._name(header)
if (name) {
this[name] = value
}
else {
this[header] = value
}
}
Headers.prototype.remove = function (header) {
var name = this._name(header)
if (name) {
delete this[name]
}
}
Headers.prototype.toObject = function () {
var headers = {}
for (var key in this) {
if (this[key] && typeof this[key] !== 'function') {
headers[key] = this[key]
}
}
return headers
}
Headers.prototype._name = function (header) {
for (var name in this) {
if (name.toLowerCase() === header.toLowerCase()) {
return name
}
}
}
Headers.prototype._value = function (header) {
for (var name in this) {
if (name.toLowerCase() === header.toLowerCase()) {
return this[name]
}
}
}
module.exports = Headers
|
function Headers (headers) {
for (var key in headers) {
this[key] = headers[key]
}
}
Headers.prototype.get = function (header) {
return this._value(header)
}
Headers.prototype.set = function (header, value) {
var name = this._name(header)
if (name) {
this[name] = value
}
else {
this[header] = value
}
}
Headers.prototype.remove = function (header) {
var name = this._name(header)
if (name) {
delete this[name]
}
}
Headers.prototype.toObject = function () {
var headers = {}
for (var key in this) {
if (typeof this[key] !== 'function') {
headers[key] = this[key]
}
}
return headers
}
Headers.prototype._name = function (header) {
for (var name in this) {
if (name.toLowerCase() === header.toLowerCase()) {
return name
}
}
}
Headers.prototype._value = function (header) {
for (var name in this) {
if (name.toLowerCase() === header.toLowerCase()) {
return this[name]
}
}
}
module.exports = Headers
|
Fix requires so they work properly | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(name='pycloudfuse',
version="0.01",
description='Fuse (Filesystem in Userspace) interface to Rackspace Cloud Files and Open Stack Object Storage (Swift)',
author='Nick Craig-Wood',
author_email='nick@memset.com',
url="https://github.com/memset/pycloudfuse",
license='MIT',
include_package_data=True,
zip_safe=False,
install_requires=['fuse-python', 'python-cloudfiles', 'ftp-cloudfs>=0.9'],
scripts=['pycloudfuse'],
#packages = find_packages(exclude=['tests', 'debian']),
#tests_require = ["nose"],
classifiers = [
'Development Status :: 4 - Beta',
'Environment :: Console',
'Programming Language :: Python',
'Operating System :: Linux',
'Environment :: No Input/Output (Daemon)',
'License :: OSI Approved :: MIT License',
],
#test_suite = "nose.collector",
)
| #!/usr/bin/env python
from setuptools import setup, find_packages
setup(name='pycloudfuse',
version="0.01",
description='Fuse (Filesystem in Userspace) interface to Rackspace Cloud Files and Open Stack Object Storage (Swift)',
author='Nick Craig-Wood',
author_email='nick@memset.com',
url="https://github.com/memset/pycloudfuse",
license='MIT',
include_package_data=True,
zip_safe=False,
install_requires=['python-fuse', 'python-cloudfiles', 'python-ftp-cloudfs'],
scripts=['pycloudfuse'],
#packages = find_packages(exclude=['tests', 'debian']),
#tests_require = ["nose"],
classifiers = [
'Development Status :: 4 - Beta',
'Environment :: Console',
'Programming Language :: Python',
'Operating System :: Linux',
'Environment :: No Input/Output (Daemon)',
'License :: OSI Approved :: MIT License',
],
#test_suite = "nose.collector",
)
|
Make thymeleaf templates not cacheable, to ease jetty redeploys | package basearch.integration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.thymeleaf.extras.springsecurity4.dialect.SpringSecurityDialect;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
@Configuration
public class ThymeleafConfiguration {
@Bean
public ServletContextTemplateResolver templateResolver() {
ServletContextTemplateResolver resolver = new ServletContextTemplateResolver();
resolver.setPrefix("/WEB-INF/thymeleaf");
resolver.setTemplateMode("HTML5");
resolver.setCacheable(false);
return resolver;
}
@Bean
public SpringSecurityDialect springSecurityDialect() {
return new SpringSecurityDialect();
}
@Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
templateEngine.addDialect(springSecurityDialect());
return templateEngine;
}
@Bean
public ThymeleafViewResolver viewResolver() {
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
viewResolver.setOrder(1);
viewResolver.setViewNames(new String[] {"*.html"});
return viewResolver;
}
}
| package basearch.integration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.thymeleaf.extras.springsecurity4.dialect.SpringSecurityDialect;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
@Configuration
public class ThymeleafConfiguration {
@Bean
public ServletContextTemplateResolver templateResolver() {
ServletContextTemplateResolver resolver = new ServletContextTemplateResolver();
resolver.setPrefix("/WEB-INF/thymeleaf");
resolver.setTemplateMode("HTML5");
return resolver;
}
@Bean
public SpringSecurityDialect springSecurityDialect() {
return new SpringSecurityDialect();
}
@Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
templateEngine.addDialect(springSecurityDialect());
return templateEngine;
}
@Bean
public ThymeleafViewResolver viewResolver() {
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
viewResolver.setOrder(1);
viewResolver.setViewNames(new String[] {"*.html"});
return viewResolver;
}
}
|
Return types in repositories & dataset | <?php
/*
* WellCommerce Open-Source E-Commerce Platform
*
* This file is part of the WellCommerce package.
*
* (c) Adam Piotrowski <adam@wellcommerce.org>
*
* For the full copyright and license information,
* please view the LICENSE file that was distributed with this source code.
*/
namespace WellCommerce\Bundle\ReviewBundle\Repository;
use Doctrine\ORM\QueryBuilder;
use WellCommerce\Bundle\DoctrineBundle\Repository\AbstractEntityRepository;
/**
* Class ReviewRepository
*
* @author Adam Piotrowski <adam@wellcommerce.org>
*/
class ReviewRepository extends AbstractEntityRepository implements ReviewRepositoryInterface
{
/**
* {@inheritdoc}
*/
public function getDataSetQueryBuilder() : QueryBuilder
{
$queryBuilder = $this->getQueryBuilder();
$queryBuilder->groupBy('review.id');
$queryBuilder->leftJoin('review.product', 'product_info');
$queryBuilder->leftJoin('product_info.translations', 'product_translation');
return $queryBuilder;
}
}
| <?php
/*
* WellCommerce Open-Source E-Commerce Platform
*
* This file is part of the WellCommerce package.
*
* (c) Adam Piotrowski <adam@wellcommerce.org>
*
* For the full copyright and license information,
* please view the LICENSE file that was distributed with this source code.
*/
namespace WellCommerce\Bundle\ReviewBundle\Repository;
use WellCommerce\Bundle\DoctrineBundle\Repository\AbstractEntityRepository;
/**
* Class ReviewRepository
*
* @author Adam Piotrowski <adam@wellcommerce.org>
*/
class ReviewRepository extends AbstractEntityRepository implements ReviewRepositoryInterface
{
public function getDataSetQueryBuilder()
{
$queryBuilder = $this->getQueryBuilder();
$queryBuilder->groupBy('review.id');
$queryBuilder->leftJoin('review.product', 'product_info');
$queryBuilder->leftJoin('product_info.translations', 'product_translation');
return $queryBuilder;
}
}
|
Write long description as git flavoured markdown | #!/usr/bin/env python
from setuptools import setup
import sys
import os
version = '1.1.6'
with open('README.md', encoding='utf-8') as f:
long_description = f.read()
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
setup(
name='africastalking',
version=version,
packages=['africastalking'],
description='Official Africa\'s Talking Python SDK',
data_files=[('', ['README.md'])],
license='MIT',
author='Africa\'s Talking',
install_requires=[
'requests>=v2.18.4',
'schema>=0.6.7'
],
python_requires=">=2.7.10",
author_email='info@africastalking.com',
url='https://github.com/AfricasTalkingLtd/africastalking-python',
download_url='https://codeload.github.com/AfricasTalkingLtd/africastalking-python/tar.gz/' + version,
keywords='ussd voice sms mpesa card bank b2b b2c sender_id payments airtime africastalking',
classifiers=[],
long_description=long_description,
long_description_content_type='text/markdown'
)
| #!/usr/bin/env python
from distutils.core import setup
import sys
import os
version = '1.1.5'
try:
import pypandoc
long_description = pypandoc.convert('README.md', 'rst')
except(IOError, ImportError):
long_description = open('README.md').read()
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
setup(
name='africastalking',
version=version,
packages=['africastalking'],
description='Official Africa\'s Talking Python SDK',
long_description=long_description,
data_files=[('', ['README.md'])],
license='MIT',
author='Africa\'s Talking',
install_requires=[
'requests>=v2.18.4',
'schema>=0.6.7'
],
python_requires=">=2.7.10",
author_email='info@africastalking.com',
url='https://github.com/AfricasTalkingLtd/africastalking-python',
download_url='https://codeload.github.com/AfricasTalkingLtd/africastalking-python/tar.gz/' + version,
keywords='ussd voice sms mpesa card bank b2b b2c sender_id payments airtime africastalking',
classifiers=[],
)
|
Use python3 version of cappy | ###############################################################################
# Copyright 2015-2019 University of Florida. All rights reserved.
# This file is part of UF CTS-IT's NACCulator project.
# Use of this source code is governed by the license found in the LICENSE file.
###############################################################################
from setuptools import setup, find_packages
VERSION="0.5.0"
setup(
name="nacculator",
version=VERSION,
author="Taeber Rapczak",
author_email="taeber@ufl.edu",
maintainer="UF CTS-IT",
maintainer_email="ctsit@ctsi.ufl.edu",
url="https://github.com/ctsit/nacculator",
license="BSD 2-Clause",
description="CSV to NACC's UDS3 format converter",
keywords=["REDCap", "NACC", "UDS", "Clinical data"],
download_url="https://github.com/ctsit/nacculator/releases/tag/" + VERSION,
package_dir = {'nacc': 'nacc'},
packages = find_packages(),
entry_points={
"console_scripts": [
"redcap2nacc = nacc.redcap2nacc:main"
]
},
install_requires=[
"cappy @ git+https://github.com/ctsit/cappy.git@2.0.0"
]
)
| ###############################################################################
# Copyright 2015-2019 University of Florida. All rights reserved.
# This file is part of UF CTS-IT's NACCulator project.
# Use of this source code is governed by the license found in the LICENSE file.
###############################################################################
from setuptools import setup, find_packages
VERSION="0.5.0"
setup(
name="nacculator",
version=VERSION,
author="Taeber Rapczak",
author_email="taeber@ufl.edu",
maintainer="UF CTS-IT",
maintainer_email="ctsit@ctsi.ufl.edu",
url="https://github.com/ctsit/nacculator",
license="BSD 2-Clause",
description="CSV to NACC's UDS3 format converter",
keywords=["REDCap", "NACC", "UDS", "Clinical data"],
download_url="https://github.com/ctsit/nacculator/releases/tag/" + VERSION,
package_dir = {'nacc': 'nacc'},
packages = find_packages(),
entry_points={
"console_scripts": [
"redcap2nacc = nacc.redcap2nacc:main"
]
},
install_requires=[
"cappy @ git+https://github.com/ctsit/cappy.git@1.2.1"
]
)
|
Update java mail message adapter. | package org.helianto.message.sender;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.helianto.message.AbstractMessageAdapter;
import org.springframework.core.io.Resource;
import org.springframework.mail.javamail.MimeMessageHelper;
/**
* Java mail message (not thread safe).
*
* @author mauriciofernandesdecastro
*/
public class JavaMailMessageAdapter extends AbstractMessageAdapter<MimeMessage> {
/**
* Java mail message constructor.
*
* @param mimeMessage
*/
public JavaMailMessageAdapter() {
super();
}
/**
* Adapter method.
*/
protected String[] getToAsStringArray() {
String[] toArray = new String[getTo().size()];
return toArray;
}
public MimeMessage getMessage() {
try {
MimeMessageHelper helper = new MimeMessageHelper(super.getMessage(), true);
helper.setTo(getToAsStringArray());
helper.setFrom(getFrom().getPrincipal());
helper.setSubject(getSubject());
helper.setText(getHtml(), true);
for (Resource file: getAttachments()) {
helper.addAttachment(file.getFilename(), file);
}
return getMessage();
} catch (MessagingException e) {
throw new IllegalArgumentException();
}
}
}
| package org.helianto.message.sender;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.helianto.message.AbstractMessageAdapter;
import org.springframework.core.io.Resource;
import org.springframework.mail.javamail.MimeMessageHelper;
/**
* Java mail message (not thread safe).
*
* @author mauriciofernandesdecastro
*/
public class JavaMailMessageAdapter extends AbstractMessageAdapter<MimeMessage> {
/**
* Java mail message constructor.
*
* @param mimeMessage
*/
public JavaMailMessageAdapter() {
super();
}
/**
* Adapter method.
*/
protected String[] getToAsStringArray() {
String[] toArray = new String[getTo().size()];
return toArray;
}
public MimeMessage getMessage() {
try {
MimeMessageHelper helper = new MimeMessageHelper(getMessage(), true);
helper.setTo(getToAsStringArray());
helper.setFrom(getFrom().getPrincipal());
helper.setSubject(getSubject());
helper.setText(getHtml(), true);
for (Resource file: getAttachments()) {
helper.addAttachment(file.getFilename(), file);
}
return getMessage();
} catch (MessagingException e) {
throw new IllegalArgumentException();
}
}
}
|
Use new 'Faker' package for fake-factory | import sys
from setuptools import setup, find_packages
import populous
requirements = [
"click",
"cached-property",
"Faker",
"dateutils",
"PyYAML",
"peloton_bloomfilters"
]
if sys.version_info < (3, 2):
requirements.append('functools32')
setup(
name="populous",
version=populous.__version__,
url=populous.__url__,
description=populous.__doc__,
author=populous.__author__,
license=populous.__license__,
long_description="TODO",
packages=find_packages(),
install_requires=requirements,
extras_require={
'tests': ['tox', 'pytest', 'pytest-mock', 'flake8'],
},
entry_points={
'console_scripts': [
'populous = populous.__main__:cli'
]
},
classifiers=[
"Development Status :: 3 - Alpha",
"License :: OSI Approved :: MIT License",
"Operating System :: POSIX",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Topic :: Utilities",
],
keywords='populous populate database',
)
| import sys
from setuptools import setup, find_packages
import populous
requirements = [
"click",
"cached-property",
"fake-factory",
"dateutils",
"PyYAML",
"peloton_bloomfilters"
]
if sys.version_info < (3, 2):
requirements.append('functools32')
setup(
name="populous",
version=populous.__version__,
url=populous.__url__,
description=populous.__doc__,
author=populous.__author__,
license=populous.__license__,
long_description="TODO",
packages=find_packages(),
install_requires=requirements,
extras_require={
'tests': ['tox', 'pytest', 'pytest-mock', 'flake8'],
},
entry_points={
'console_scripts': [
'populous = populous.__main__:cli'
]
},
classifiers=[
"Development Status :: 3 - Alpha",
"License :: OSI Approved :: MIT License",
"Operating System :: POSIX",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Topic :: Utilities",
],
keywords='populous populate database',
)
|
Change isValid to isRange and include results | import chrono from 'chrono-node'
import militaryParser from './parsers/militaryParser'
import requireMeridiemRefiner from './refiners/requireMeridiemRefiner'
import impliedAMEndRefiner from './refiners/impliedAMEndRefiner'
import impliedPMStartRefiner from './refiners/impliedPMStartRefiner'
import dayOverlapRefiner from './refiners/dayOverlapRefiner'
const parser = new chrono.Chrono(chrono.options.casualOption())
parser.parsers.push(militaryParser)
parser.refiners.push(requireMeridiemRefiner)
parser.refiners.push(impliedAMEndRefiner)
parser.refiners.push(impliedPMStartRefiner)
parser.refiners.push(dayOverlapRefiner)
export default function(str, ref) {
let rslt = parser.parse(str, ref)[0]
let isRange = rslt && rslt.start && rslt.end
let start = rslt.start ? rslt.start.date() : null
let end = rslt.end ? rslt.end.date() : null
let text = rslt.text
return { start, end, text, message, isRange, }
}
| import chrono from 'chrono-node'
import militaryParser from './parsers/militaryParser'
import requireMeridiemRefiner from './refiners/requireMeridiemRefiner'
import impliedAMEndRefiner from './refiners/impliedAMEndRefiner'
import impliedPMStartRefiner from './refiners/impliedPMStartRefiner'
import dayOverlapRefiner from './refiners/dayOverlapRefiner'
const parser = new chrono.Chrono(chrono.options.casualOption())
parser.parsers.push(militaryParser)
parser.refiners.push(requireMeridiemRefiner)
parser.refiners.push(impliedAMEndRefiner)
parser.refiners.push(impliedPMStartRefiner)
parser.refiners.push(dayOverlapRefiner)
export default function(str, ref) {
let rslt = parser.parse(str, ref)[0]
let isValid = rslt && rslt.start && rslt.end
let start = isValid ? rslt.start.date() : null
let end = isValid ? rslt.end.date() : null
let text = isValid ? rslt.text : null
return { start, end, text, isValid, }
}
|
Make the new edit button JS func visible to native land.
Forgot to include this in the commit which added the JS func. | var wmf = {}
wmf.editButtons = require('./js/transforms/addEditButtons')
wmf.compatibility = require('wikimedia-page-library').CompatibilityTransform
wmf.elementLocation = require('./js/elementLocation')
wmf.utilities = require('./js/utilities')
wmf.findInPage = require('./js/findInPage')
wmf.footerReadMore = require('wikimedia-page-library').FooterReadMore
wmf.footerMenu = require('wikimedia-page-library').FooterMenu
wmf.footerLegal = require('wikimedia-page-library').FooterLegal
wmf.footerContainer = require('wikimedia-page-library').FooterContainer
wmf.filePages = require('./js/transforms/disableFilePageEdit')
wmf.imageDimming = require('wikimedia-page-library').DimImagesTransform
wmf.tables = require('./js/transforms/collapseTables')
wmf.themes = require('wikimedia-page-library').ThemeTransform
wmf.redLinks = require('wikimedia-page-library').RedLinks
wmf.paragraphs = require('./js/transforms/relocateFirstParagraph')
wmf.images = require('./js/transforms/widenImages')
window.wmf = wmf
| var wmf = {}
wmf.compatibility = require('wikimedia-page-library').CompatibilityTransform
wmf.elementLocation = require('./js/elementLocation')
wmf.utilities = require('./js/utilities')
wmf.findInPage = require('./js/findInPage')
wmf.footerReadMore = require('wikimedia-page-library').FooterReadMore
wmf.footerMenu = require('wikimedia-page-library').FooterMenu
wmf.footerLegal = require('wikimedia-page-library').FooterLegal
wmf.footerContainer = require('wikimedia-page-library').FooterContainer
wmf.filePages = require('./js/transforms/disableFilePageEdit')
wmf.imageDimming = require('wikimedia-page-library').DimImagesTransform
wmf.tables = require('./js/transforms/collapseTables')
wmf.themes = require('wikimedia-page-library').ThemeTransform
wmf.redLinks = require('wikimedia-page-library').RedLinks
wmf.paragraphs = require('./js/transforms/relocateFirstParagraph')
wmf.images = require('./js/transforms/widenImages')
window.wmf = wmf
|
Call conn.Close if waitForOpen returns an error | // +build js,wasm
package websocket
import (
"context"
"errors"
"syscall/js"
"github.com/libp2p/go-libp2p-core/transport"
ma "github.com/multiformats/go-multiaddr"
manet "github.com/multiformats/go-multiaddr-net"
)
func (t *WebsocketTransport) maDial(ctx context.Context, raddr ma.Multiaddr) (manet.Conn, error) {
wsurl, err := parseMultiaddr(raddr)
if err != nil {
return nil, err
}
rawConn := js.Global().Get("WebSocket").New(wsurl)
conn := NewConn(rawConn)
if err := conn.waitForOpen(); err != nil {
conn.Close()
return nil, err
}
mnc, err := manet.WrapNetConn(conn)
if err != nil {
conn.Close()
return nil, err
}
return mnc, nil
}
func (t *WebsocketTransport) Listen(a ma.Multiaddr) (transport.Listener, error) {
return nil, errors.New("Listen not implemented on js/wasm")
}
| // +build js,wasm
package websocket
import (
"context"
"errors"
"syscall/js"
"github.com/libp2p/go-libp2p-core/transport"
ma "github.com/multiformats/go-multiaddr"
manet "github.com/multiformats/go-multiaddr-net"
)
func (t *WebsocketTransport) maDial(ctx context.Context, raddr ma.Multiaddr) (manet.Conn, error) {
wsurl, err := parseMultiaddr(raddr)
if err != nil {
return nil, err
}
rawConn := js.Global().Get("WebSocket").New(wsurl)
conn := NewConn(rawConn)
if err := conn.waitForOpen(); err != nil {
return nil, err
}
mnc, err := manet.WrapNetConn(conn)
if err != nil {
conn.Close()
return nil, err
}
return mnc, nil
}
func (t *WebsocketTransport) Listen(a ma.Multiaddr) (transport.Listener, error) {
return nil, errors.New("Listen not implemented on js/wasm")
}
|
Use Whoops middleware on frontend front controller, too | <?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Zend\Diactoros\Server;
use Zend\Stratigility\MiddlewarePipe;
// Instantiate the application, register providers etc.
$app = require __DIR__.'/system/bootstrap.php';
// Set up everything we need for the frontend
$app->register('Flarum\Forum\ForumServiceProvider');
$app->register('Flarum\Admin\AdminServiceProvider');
// Build a middleware pipeline for Flarum
$flarum = new MiddlewarePipe();
$flarum->pipe($app->make('Flarum\Forum\Middleware\LoginWithCookie'));
$flarum->pipe($app->make('Flarum\Api\Middleware\ReadJsonParameters'));
$admin = new MiddlewarePipe();
$admin->pipe($app->make('Flarum\Admin\Middleware\LoginWithCookieAndCheckAdmin'));
$admin->pipe($app->make('Flarum\Http\RouterMiddleware', ['routes' => $app->make('flarum.admin.routes')]));
$flarum->pipe('/admin.php', $admin);
$flarum->pipe('/index.php', $app->make('Flarum\Http\RouterMiddleware', ['routes' => $app->make('flarum.forum.routes')]));
$flarum->pipe(new \Franzl\Middleware\Whoops\Middleware());
$server = Server::createServer(
$flarum,
$_SERVER,
$_GET,
$_POST,
$_COOKIE,
$_FILES
);
$server->listen();
| <?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Zend\Diactoros\Server;
use Zend\Stratigility\MiddlewarePipe;
// Instantiate the application, register providers etc.
$app = require __DIR__.'/system/bootstrap.php';
// Set up everything we need for the frontend
$app->register('Flarum\Forum\ForumServiceProvider');
$app->register('Flarum\Admin\AdminServiceProvider');
// Build a middleware pipeline for Flarum
$flarum = new MiddlewarePipe();
$flarum->pipe($app->make('Flarum\Forum\Middleware\LoginWithCookie'));
$flarum->pipe($app->make('Flarum\Api\Middleware\ReadJsonParameters'));
$admin = new MiddlewarePipe();
$admin->pipe($app->make('Flarum\Admin\Middleware\LoginWithCookieAndCheckAdmin'));
$admin->pipe($app->make('Flarum\Http\RouterMiddleware', ['routes' => $app->make('flarum.admin.routes')]));
$flarum->pipe('/admin.php', $admin);
$flarum->pipe('/index.php', $app->make('Flarum\Http\RouterMiddleware', ['routes' => $app->make('flarum.forum.routes')]));
$server = Server::createServer(
$flarum,
$_SERVER,
$_GET,
$_POST,
$_COOKIE,
$_FILES
);
$server->listen();
|
Check time after alarm disabled | import Entity from '../Entity.js';
import printMessage from '../printMessage.js';
import action from '../action.js';
import time from '../time.js';
export class AlarmClock extends Entity {
constructor() {
super();
this.ringing = true;
}
name() {
return "alarm clock";
}
actions() {
const checkTime = action("Look at the time.", () => {
printMessage(`It is now ${time()}.`);
})
if(this.ringing) {
return [
action("Snooze", () => {
printMessage(`You sleep for another 5 minutes before the alarm clock rings again. It's now ${time()}.`);
}),
action("Turn if off.", () => {
this.ringing = false;
printMessage('You turn the alarm clock off.');
}),
checkTime
];
} else {
return [checkTime];
}
}
}
export default new AlarmClock();
| import Entity from '../Entity.js';
import printMessage from '../printMessage.js';
import action from '../action.js';
import time from '../time.js';
export class AlarmClock extends Entity {
constructor() {
super();
this.ringing = true;
}
name() {
return "alarm clock";
}
actions() {
if(this.ringing) {
return [
action("Snooze", () => {
printMessage(`You sleep for another 5 minutes before the alarm clock rings again. It's now ${time()}.`);
}),
action("Turn if off.", () => {
this.ringing = false;
printMessage('You turn the alarm clock off.');
})
];
} else {
return [];
}
}
}
export default new AlarmClock();
|
Fix up reference to moved module. | compiler.modulator.compiled = def(
[
ephox.bolt.module.modulator.modulators.compiled,
compiler.tools.io
],
function (delegate, io) {
var create = function () {
var instance = delegate.create.apply(null, arguments);
var can = function () {
return instance.can.apply(null, arguments);
};
var get = function (id) {
var spec = instance.get.apply(null, arguments);
var url = spec.url;
var serial = spec.serial;
var render = function () {
return io.read(url);
};
var load = function (define) {
// FIX sort out implicit definition behaviour.
define(id, [], function () {});
};
return {
serial: serial,
url: url,
load: load,
render: render
};
};
return {
can: can,
get: get
};
};
return {
create: create
};
}
);
| compiler.modulator.compiled = def(
[
ephox.bolt.kernel.modulator.compiled,
compiler.tools.io
],
function (delegate, io) {
var create = function () {
var instance = delegate.create.apply(null, arguments);
var can = function () {
return instance.can.apply(null, arguments);
};
var get = function (id) {
var spec = instance.get.apply(null, arguments);
var url = spec.url;
var serial = spec.serial;
var render = function () {
return io.read(url);
};
var load = function (define) {
// FIX sort out implicit definition behaviour.
define(id, [], function () {});
};
return {
serial: serial,
url: url,
load: load,
render: render
};
};
return {
can: can,
get: get
};
};
return {
create: create
};
}
);
|
Fix scrolling bug with contact me link | //Bootstrap and jquery included via CodePen. Much js functionality is in minified Bootstrap.js and configured through data attributes.
$(document).ready(function() {
function sendMail() {
var name = $('#contactName').val();
var email = $('#contactEmail').val();
var message = $('#contactMessage').val();
// message += "\n\n" + name;
var msgString = `mailto:jonathanghoffman@gmail.com?subject=new message from ${email}&body=${message}%0A${name}`;
window.open(msgString);
}
$('#contactSubmit').click(function () {
sendMail();
});
// Fix scrolling with a fixed navbar.
var navOffset = $('.navbar').height();
$('.navbar li a').click(function(event) {
var href = $(this).attr('href');
// Don't let the browser scroll, but still update the current address
// in the browser.
event.preventDefault();
window.location.hash = href;
// Explicitly scroll to where the browser thinks the element
// is, but apply the offset.
$(href)[0].scrollIntoView();
// Skip the offset for the last element.
if (href != "#contact-me") {
window.scrollBy(0, -navOffset);
}
});
});
| //Bootstrap and jquery included via CodePen. Much js functionality is in minified Bootstrap.js and configured through data attributes.
$(document).ready(function() {
function sendMail() {
var name = $('#contactName').val();
var email = $('#contactEmail').val();
var message = $('#contactMessage').val();
// message += "\n\n" + name;
var msgString = `mailto:jonathanghoffman@gmail.com?subject=new message from ${email}&body=${message}%0A${name}`;
window.open(msgString);
}
$('#contactSubmit').click(function () {
sendMail();
});
// Fix scrolling with a fixed navbar.
var navOffset = $('.navbar').height();
$('.navbar li a').click(function(event) {
var href = $(this).attr('href');
// Don't let the browser scroll, but still update the current address
// in the browser.
event.preventDefault();
window.location.hash = href;
// Explicitly scroll to where the browser thinks the element
// is, but apply the offset.
$(href)[0].scrollIntoView();
window.scrollBy(0, -navOffset);
});
});
|
Revert "Attempt to bypass test database"
This reverts commit 889713c8c4c7151ba06448a3993778a91d2abfd6. | # Local
from .base import *
# JWT Settings
def jwt_get_username_from_payload_handler(payload):
return payload.get('email')
JWT_AUTH = {
# 'JWT_SECRET_KEY': AUTH0_CLIENT_SECRET,
'JWT_AUDIENCE': AUTH0_CLIENT_ID,
'JWT_PAYLOAD_GET_USERNAME_HANDLER': jwt_get_username_from_payload_handler,
'JWT_AUTH_HEADER_PREFIX': 'Bearer',
'JWT_PUBLIC_KEY': jwt_public_key,
'JWT_ALGORITHM': 'RS256',
}
# Static Server Config
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
STATIC_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
STATIC_URL = '/static/'
STATICFILES_STORAGE = STATIC_STORAGE
# Media (aka File Upload) Server Config
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media')
MEDIA_STORAGE = 'django.core.files.storage.FileSystemStorage'
MEDIA_URL = '/media/'
DEFAULT_FILE_STORAGE = MEDIA_STORAGE
# Email
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
| # Local
from .base import *
# JWT Settings
def jwt_get_username_from_payload_handler(payload):
return payload.get('email')
JWT_AUTH = {
# 'JWT_SECRET_KEY': AUTH0_CLIENT_SECRET,
'JWT_AUDIENCE': AUTH0_CLIENT_ID,
'JWT_PAYLOAD_GET_USERNAME_HANDLER': jwt_get_username_from_payload_handler,
'JWT_AUTH_HEADER_PREFIX': 'Bearer',
'JWT_PUBLIC_KEY': jwt_public_key,
'JWT_ALGORITHM': 'RS256',
}
DATABASES['default']['TEST'] = dj_database_url.config(default=DATABASE_URL)
# Static Server Config
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
STATIC_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
STATIC_URL = '/static/'
STATICFILES_STORAGE = STATIC_STORAGE
# Media (aka File Upload) Server Config
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media')
MEDIA_STORAGE = 'django.core.files.storage.FileSystemStorage'
MEDIA_URL = '/media/'
DEFAULT_FILE_STORAGE = MEDIA_STORAGE
# Email
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
|
Rename of function from transaction module | var mysql = require('mysql')
var Transaction = require('any-db-transaction')
exports.name = 'mysql'
exports.createQuery = mysql.createQuery
exports.createTransaction = Transaction.begin.bind(null, mysql.createQuery)
exports.createConnection = function createConnection(opts, callback) {
var conn = mysql.createConnection(opts)
conn.adapter = 'mysql'
conn.begin = beginTransaction
if (callback) {
conn.connect(function (err) {
if (err) callback(err)
else callback(null, conn)
})
} else {
conn.connect()
}
conn.query = wrapQueryMethod(conn.query)
return conn
}
function wrapQueryMethod(realQuery) {
return function query() {
var q = realQuery.apply(this, arguments)
if (!q.hasOwnProperty('text')) {
Object.defineProperty(q, 'text', {
get: function () { return this.sql }
});
}
q.on('result', q.emit.bind(q, 'row'))
q._callback = wrapQueryCallback(q._callback)
return q
}
}
function wrapQueryCallback(callback) {
if (!callback) return
return function (err, rows) {
if (err) callback(err)
else {
callback(null, {
rows: rows,
rowCount: rows.length,
lastInsertId: rows.insertId
})
}
}
}
function beginTransaction (beginStatement, callback) {
return exports.createTransaction(beginStatement, callback).setConnection(this)
}
| var mysql = require('mysql')
var createTransaction = require('any-db-transaction').createFromArgs
exports.name = 'mysql'
exports.createQuery = mysql.createQuery
exports.createTransaction = createTransaction.bind(null, mysql.createQuery)
exports.createConnection = function createConnection(opts, callback) {
var conn = mysql.createConnection(opts)
conn.adapter = 'mysql'
conn.begin = beginTransaction
if (callback) {
conn.connect(function (err) {
if (err) callback(err)
else callback(null, conn)
})
} else {
conn.connect()
}
conn.query = wrapQueryMethod(conn.query)
return conn
}
function wrapQueryMethod(realQuery) {
return function query() {
var q = realQuery.apply(this, arguments)
if (!q.hasOwnProperty('text')) {
Object.defineProperty(q, 'text', {
get: function () { return this.sql }
});
}
q.on('result', q.emit.bind(q, 'row'))
q._callback = wrapQueryCallback(q._callback)
return q
}
}
function wrapQueryCallback(callback) {
if (!callback) return
return function (err, rows) {
if (err) callback(err)
else {
callback(null, {
rows: rows,
rowCount: rows.length,
lastInsertId: rows.insertId
})
}
}
}
function beginTransaction (beginStatement, callback) {
return exports.createTransaction(beginStatement, callback).setConnection(this)
}
|
Increase space between stacked nodes and their labels
Fixes #1003. | import React from 'react';
import _ from 'lodash';
function dissoc(obj, key) {
const newObj = _.clone(obj);
delete newObj[key];
return newObj;
}
export default function NodeShapeStack(props) {
const propsNoHighlight = dissoc(props, 'highlighted');
const propsOnlyHighlight = Object.assign({}, props, {onlyHighlight: true});
const Shape = props.shape;
const [dx, dy] = [0, 4];
const dsx = (props.size * 2 + (dx * 2)) / (props.size * 2);
const dsy = (props.size * 2 + (dy * 2)) / (props.size * 2);
const hls = [dsx, dsy];
return (
<g transform={`translate(${dx * -1}, ${dy * -2})`} className="stack">
<g transform={`scale(${hls})translate(${dx}, ${dy}) `} className="stack">
<Shape {...propsOnlyHighlight} />
</g>
<g transform={`translate(${dx * 2}, ${dy * 2})`}>
<Shape {...propsNoHighlight} />
</g>
<g transform={`translate(${dx * 1}, ${dy * 1})`}>
<Shape {...propsNoHighlight} />
</g>
<Shape {...propsNoHighlight} />
</g>
);
}
| import React from 'react';
import _ from 'lodash';
function dissoc(obj, key) {
const newObj = _.clone(obj);
delete newObj[key];
return newObj;
}
export default function NodeShapeStack(props) {
const propsNoHighlight = dissoc(props, 'highlighted');
const propsOnlyHighlight = Object.assign({}, props, {onlyHighlight: true});
const Shape = props.shape;
const [dx, dy] = [0, 4];
const dsx = (props.size * 2 + (dx * 2)) / (props.size * 2);
const dsy = (props.size * 2 + (dy * 2)) / (props.size * 2);
const hls = [dsx, dsy];
return (
<g transform={`translate(${dx * -1}, ${dy * -1})`} className="stack">
<g transform={`scale(${hls})translate(${dx}, ${dy}) `} className="stack">
<Shape {...propsOnlyHighlight} />
</g>
<g transform={`translate(${dx * 2}, ${dy * 2})`}>
<Shape {...propsNoHighlight} />
</g>
<g transform={`translate(${dx * 1}, ${dy * 1})`}>
<Shape {...propsNoHighlight} />
</g>
<Shape {...propsNoHighlight} />
</g>
);
}
|
Enable add button after post | angular.module('accumulatorApp', [])
.controller('AccumulatorController', ['$scope', '$http', function ($scope, $http) {
$scope.accumulator = [];
$scope.item = '';
$scope.enabled = false;
$scope.add = function () {
$scope.enabled = false;
$http.post('/api', {"message": $scope.item})
.then(function success(response) {
$scope.accumulator.unshift(response.data);
$scope.item = '';
$scope.enabled = true;
});
}
$http.get('/api')
.then(function success(response) {
$scope.accumulator = response.data;
$scope.enabled = true;
});
}]); | angular.module('accumulatorApp', [])
.controller('AccumulatorController', ['$scope', '$http', function ($scope, $http) {
$scope.accumulator = [];
$scope.item = '';
$scope.enabled = false;
$scope.add = function () {
$scope.enabled = false;
$http.post('/api', {"message": $scope.item})
.then(function success(response) {
$scope.accumulator.unshift(response.data);
$scope.item = '';
});
}
$http.get('/api')
.then(function success(response) {
$scope.accumulator = response.data;
$scope.enabled = true;
});
}]); |
Remove component installation dir when getting new | var
fs = require('fs'),
mkdirp = require('mkdirp'),
rimraf = require('rimraf'),
Builder = require('component-builder'),
config = require('../config'),
installDir = config.componentInstallDir,
utils = require('./utils'),
options = {
dest : installDir
},
component;
component = !config.useMocks ?
require('component') :
require('../mocks/component');
exports.install = function (data, callback) {
var pkg = component.install(data.repo, '*', options);
pkg.on('end', callback);
// Clear out install directory to get latest
rimraf(utils.getInstallDir(data.repo), function () {
pkg.install();
});
};
exports.build = function (data, callback) {
var builder = new Builder(utils.getInstallDir(data.repo));
builder.build(function (err, res) {
var
dirPath = utils.getBuildDir(data.repo),
scriptPath = utils.getBuildScriptPath(data.repo);
if (err || (res && !res.js)) {
return callback(err);
}
mkdirp(dirPath, function (err) {
if (err) {
return callback(err);
}
fs.writeFile(scriptPath, res.js, callback);
});
});
};
| var
fs = require('fs'),
mkdirp = require('mkdirp'),
Builder = require('component-builder'),
config = require('../config'),
installDir = config.componentInstallDir,
utils = require('./utils'),
options = {
dest : installDir
},
component;
component = !config.useMocks ?
require('component') :
require('../mocks/component');
exports.install = function (data, callback) {
var pkg = component.install(data.repo, '*', options);
pkg.on('end', callback);
pkg.install();
};
exports.build = function (data, callback) {
var builder = new Builder(utils.getInstallDir(data.repo));
builder.build(function (err, res) {
var
dirPath = utils.getBuildDir(data.repo),
scriptPath = utils.getBuildScriptPath(data.repo);
if (err || (res && !res.js)) {
return callback(err);
}
mkdirp(dirPath, function (err) {
if (err) {
return callback(err);
}
fs.writeFile(scriptPath, res.js, callback);
});
});
};
|
Disable impersonation logging during testing | import sys
import django
from django.conf import settings
APP_NAME = 'impersonate'
settings.configure(
DEBUG=True,
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
},
USE_TZ=True,
ROOT_URLCONF='{0}.tests'.format(APP_NAME),
MIDDLEWARE_CLASSES=(
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'impersonate.middleware.ImpersonateMiddleware',
),
INSTALLED_APPS=(
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.admin',
APP_NAME,
),
# turn off for testing, override in logging-specific tests
IMPERSONATE_DISABLE_LOGGING=True,
)
from django.test.utils import get_runner
try:
django.setup()
except AttributeError:
pass
TestRunner = get_runner(settings)
test_runner = TestRunner()
failures = test_runner.run_tests([APP_NAME])
if failures:
sys.exit(failures)
| import sys
import django
from django.conf import settings
APP_NAME = 'impersonate'
settings.configure(
DEBUG=True,
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
},
USE_TZ=True,
ROOT_URLCONF='{0}.tests'.format(APP_NAME),
MIDDLEWARE_CLASSES=(
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'impersonate.middleware.ImpersonateMiddleware',
),
INSTALLED_APPS=(
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.admin',
APP_NAME,
),
# turn off for testing, override in logging-specific tests
IMPERSONATE_SESSION_LOGGING=False,
)
from django.test.utils import get_runner
try:
django.setup()
except AttributeError:
pass
TestRunner = get_runner(settings)
test_runner = TestRunner()
failures = test_runner.run_tests([APP_NAME])
if failures:
sys.exit(failures)
|
Fix error if .git directory doesn't exists | 'use strict';
var url = require('url');
var path = require('path');
var utils = require('./utils');
module.exports = function(dir, cb) {
if (typeof dir === 'function') {
cb = dir;
dir = '';
}
utils.origin(utils.cwd(dir), function (err, giturl) {
if (err) return cb(err);
if(!giturl) return cb('cannot find ".git/config"');
var parsed = url.parse(giturl);
var segments = parsed.pathname.split(path.sep);
cb(null, utils.filename(segments.pop()));
});
};
module.exports.sync = function(dir) {
var giturl = utils.origin.sync(utils.cwd(dir));
if (!giturl) {
console.error(utils.red('cannot find ".git/config"'));
return null;
}
var parsed = url.parse(giturl);
var segments = parsed.pathname.split(path.sep);
return utils.filename(segments.pop());
};
| 'use strict';
var url = require('url');
var path = require('path');
var utils = require('./utils');
module.exports = function(dir, cb) {
if (typeof dir === 'function') {
cb = dir;
dir = '';
}
utils.origin(utils.cwd(dir), function (err, giturl) {
if (err) return cb(err);
var parsed = url.parse(giturl);
var segments = parsed.pathname.split(path.sep);
cb(null, utils.filename(segments.pop()));
});
};
module.exports.sync = function(dir) {
var giturl = utils.origin.sync(utils.cwd(dir));
if (!giturl) {
console.error(utils.red('cannot find ".git/config"'));
return null;
}
var parsed = url.parse(giturl);
var segments = parsed.pathname.split(path.sep);
return utils.filename(segments.pop());
};
|
Rename uploaded files to their SHA1 | import hashlib
from rest.models import Sound
from rest.serializers import SoundSerializer
from rest_framework import generics
def hashfile(afile, hasher, blocksize=65536):
buf = afile.read(blocksize)
while len(buf) > 0:
hasher.update(buf)
buf = afile.read(blocksize)
return hasher.digest()
class SoundList(generics.ListCreateAPIView):
queryset = Sound.objects.all()
serializer_class = SoundSerializer
def perform_create(self, serializer):
sound = self.request._files['sound']
codec = sound.content_type.split('/')[-1]
size = sound._size
duration = 0.0 # TODO
tempfile = self.request._files['sound'].file.name
sha1 = hashfile(open(tempfile, 'rb'), hashlib.sha1()).hex()
self.request._files['sound']._name = sha1
# TODO: validate calculated parameters before saving
# TODO: if file already uploaded, do not save
serializer.save(codec=codec, size=size, duration=duration, sha1=sha1)
class SoundDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Sound.objects.all()
serializer_class = SoundSerializer
| import hashlib
from rest.models import Sound
from rest.serializers import SoundSerializer
from rest_framework import generics
def hashfile(afile, hasher, blocksize=65536):
buf = afile.read(blocksize)
while len(buf) > 0:
hasher.update(buf)
buf = afile.read(blocksize)
return hasher.digest()
class SoundList(generics.ListCreateAPIView):
queryset = Sound.objects.all()
serializer_class = SoundSerializer
def perform_create(self, serializer):
sound = self.request._files['sound']
codec = sound.content_type.split('/')[-1]
size = sound._size
duration = 0.0 # TODO
tempfile = self.request._files['sound'].file.name
sha1 = hashfile(open(tempfile, 'rb'), hashlib.sha1()).hex()
# TODO: validate calculated parameters before saving
# TODO: if file already uploaded, do not save
serializer.save(codec=codec, size=size, duration=duration, sha1=sha1)
class SoundDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Sound.objects.all()
serializer_class = SoundSerializer
|
Add configparser to the install_requires list. | from setuptools import setup, find_packages
requires = [
'configparser',
'python-dateutil',
'pytz',
'requests',
'simplejson'
]
setup(
name='amaascore',
version='0.1.7',
description='Asset Management as a Service - Core SDK',
license='Apache License 2.0',
url='https://github.com/amaas-fintech/amaas-core-sdk-python',
author='AMaaS',
author_email='tech@amaas.com',
classifiers=[
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
],
packages=find_packages(exclude=['tests']), # Very annoying that this doesnt work - I have to include a MANIFEST
install_requires=requires,
)
| from setuptools import setup, find_packages
requires = [
'python-dateutil',
'pytz',
'requests',
'simplejson'
]
setup(
name='amaascore',
version='0.1.7',
description='Asset Management as a Service - Core SDK',
license='Apache License 2.0',
url='https://github.com/amaas-fintech/amaas-core-sdk-python',
author='AMaaS',
author_email='tech@amaas.com',
classifiers=[
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
],
packages=find_packages(exclude=['tests']), # Very annoying that this doesnt work - I have to include a MANIFEST
install_requires=requires,
)
|
Use readFile instead of readFileSync in tests | const test = require('ava')
const path = require('path')
const { readdirSync, readFile } = require('fs')
const { compile, format } = require('../')
const fixtures = path.join(__dirname, 'fixtures')
const fixture = file => path.join(fixtures, file)
const testFiles = readdirSync(fixtures)
.filter(file => file.endsWith('.js'))
.map(file => ({
[file]: {
js: new Promise((resolve, reject) => {
readFile(fixture(file), (err, data) => {
if (err) return reject(err)
resolve(data.toString())
})
}),
re: new Promise((resolve, reject) => {
readFile(fixture(file.replace('.js', '.re')), (err, data) => {
if (err) return reject(err)
resolve(data.toString())
})
})
}
}))
.reduce((all, mod) => Object.assign({}, all, mod), {})
const compareSources = async (t, { js, re }) => {
t.is(compile(await js), format(await re))
}
Object.entries(testFiles).forEach(([moduleName, source]) => {
test(`Compile ${moduleName}`, compareSources, source)
}) | const test = require('ava')
const path = require('path')
const { readdirSync, readFileSync } = require('fs')
const { compile, format } = require('../')
const fixtures = path.join(__dirname, 'fixtures')
const fixture = file => path.join(fixtures, file)
const testFiles = readdirSync(fixtures)
.filter(file => file.endsWith('.js'))
.map(file => ({
[file]: {
js: readFileSync(fixture(file)).toString(),
re: readFileSync(fixture(file.replace('.js', '.re'))).toString()
}
}))
.reduce((all, mod) => Object.assign({}, all, mod), {})
const compareSources = (t, { js, re }) => {
t.is(compile(js), format(re))
}
Object.entries(testFiles).forEach(([moduleName, source]) => {
test(`Compile ${moduleName}`, compareSources, source)
}) |
Update workingOn initial state so it matches empty state | export const initialState = {
user: {
isAuthenticated: false,
email: '',
userType: '',
isAdmin: false
},
global: {
workingOn: null
},
rootPath: "/florence",
teams: {
active: {},
all: [],
allIDsAndNames: [],
users: []
},
datasets: {
all: [],
jobs: []
},
collections: {
all: [],
active: null,
toDelete: {}
},
notifications: [],
preview: {
selectedPage: null
}
}; | export const initialState = {
user: {
isAuthenticated: false,
email: '',
userType: '',
isAdmin: false
},
global: {
workingOn: {}
},
rootPath: "/florence",
teams: {
active: {},
all: [],
allIDsAndNames: [],
users: []
},
datasets: {
all: [],
jobs: []
},
collections: {
all: [],
active: null,
toDelete: {}
},
notifications: [],
preview: {
selectedPage: null
}
}; |
Allow React HTML to be set | module.exports = {
"extends": "justinlocsei/configurations/es6",
"ecmaFeatures": {
"jsx": true
},
"env": {
"browser": true
},
"plugins": [
"react"
],
"rules": {
"jsx-quotes": [2, "prefer-double"],
"react/jsx-boolean-value": [2, "always"],
"react/jsx-curly-spacing": [2, "never"],
"react/jsx-handler-names": 2,
"react/jsx-no-bind": 2,
"react/jsx-no-duplicate-props": [2, {"ignoreCase": true}],
"react/jsx-no-undef": 2,
"react/jsx-pascal-case": 2,
"react/jsx-uses-vars": 2,
"react/no-did-mount-set-state": 2,
"react/no-did-update-set-state": 2,
"react/no-direct-mutation-state": 2,
"react/no-multi-comp": 2,
"react/no-unknown-property": 2,
"react/prop-types": 2,
"react/require-extension": 2,
"react/self-closing-comp": 2,
"react/wrap-multilines": 2
}
};
| module.exports = {
"extends": "justinlocsei/configurations/es6",
"ecmaFeatures": {
"jsx": true
},
"env": {
"browser": true
},
"plugins": [
"react"
],
"rules": {
"jsx-quotes": [2, "prefer-double"],
"react/jsx-boolean-value": [2, "always"],
"react/jsx-curly-spacing": [2, "never"],
"react/jsx-handler-names": 2,
"react/jsx-no-bind": 2,
"react/jsx-no-duplicate-props": [2, {"ignoreCase": true}],
"react/jsx-no-undef": 2,
"react/jsx-pascal-case": 2,
"react/jsx-uses-vars": 2,
"react/no-danger": 2,
"react/no-did-mount-set-state": 2,
"react/no-did-update-set-state": 2,
"react/no-direct-mutation-state": 2,
"react/no-multi-comp": 2,
"react/no-unknown-property": 2,
"react/prop-types": 2,
"react/require-extension": 2,
"react/self-closing-comp": 2,
"react/wrap-multilines": 2
}
};
|
Fix flake8 in app test | # -*- coding: utf-8 -*-
def test_app_title(app):
"""Simply tests if the default app title meets the expectations.
Args:
app (:class:`{{cookiecutter.app_class_name}}`): Default app instance
Raises:
AssertionError: If the title does not match
"""
assert app.title == '{{cookiecutter.app_title}}'
def test_carousel(app):
"""Test for the carousel widget of the app checking the slides' names.
Args:
app (:class:`{{cookiecutter.app_class_name}}`): Default app instance
Raises:
AssertionError: If the names of the slides do not match the expectations
"""
names = [slide.name for slide in app.carousel.slides]
expected = ['hello', 'kivy', 'cookiecutterdozer', 'license', 'github']
assert names == expected
| # -*- coding: utf-8 -*-
import pytest
def test_app_title(app):
"""Simply tests if the default app title meets the expectations.
Args:
app (:class:`{{cookiecutter.app_class_name}}`): Default app instance
Raises:
AssertionError: If the title does not match
"""
assert app.title == '{{cookiecutter.app_title}}'
def test_carousel(app):
"""Test for the carousel widget of the app checking the slides' names.
Args:
app (:class:`{{cookiecutter.app_class_name}}`): Default app instance
Raises:
AssertionError: If the names of the slides do not match the expectations
"""
names = [slide.name for slide in app.carousel.slides]
expected = ['hello', 'kivy', 'cookiecutterdozer', 'license', 'github']
assert names == expected
|
Fix reinitializing Grav in tests | <?php
namespace Grav;
use Codeception\Util\Fixtures;
use Faker\Factory;
use Grav\Common\Grav;
ini_set('error_log', __DIR__ . '/error.log');
$grav = function() {
Grav::resetInstance();
$grav = Grav::instance();
$grav['config']->init();
foreach (array_keys($grav['setup']->getStreams()) as $stream) {
@stream_wrapper_unregister($stream);
}
$grav['streams'];
$grav['plugins']->init();
$grav['themes']->init();
$grav['uri']->init();
$grav['debugger']->init();
$grav['assets']->init();
$grav['config']->set('system.cache.enabled', false);
$grav['locator']->addPath('tests', '', 'tests', false);
return $grav;
};
Fixtures::add('grav', $grav);
$fake = Factory::create();
Fixtures::add('fake', $fake);
| <?php
namespace Grav;
use Codeception\Util\Fixtures;
use Faker\Factory;
use Grav\Common\Grav;
ini_set('error_log', __DIR__ . '/error.log');
$grav = function() {
Grav::resetInstance();
$grav = Grav::instance();
$grav['config']->init();
$grav['streams'];
$grav['plugins']->init();
$grav['themes']->init();
$grav['uri']->init();
$grav['debugger']->init();
$grav['assets']->init();
$grav['config']->set('system.cache.enabled', false);
$grav['locator']->addPath('tests', '', 'tests', false);
return $grav;
};
Fixtures::add('grav', $grav);
$fake = Factory::create();
Fixtures::add('fake', $fake);
|
Add an alias for the bound watcher instance.
Signed-off-by: Jason Lewis <b136be6b8ecc2c62ceb9857ec62bf85489a45e0c@gmail.com> | <?php
namespace JasonLewis\ResourceWatcher\Integration;
use Illuminate\Support\ServiceProvider;
use JasonLewis\ResourceWatcher\Tracker;
use JasonLewis\ResourceWatcher\Watcher;
class LaravelServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->singleton('watcher', function ($app) {
return new Watcher(new Tracker, $app['files']);
});
$this->app->alias('watcher', 'JasonLewis\ResourceWatcher\Watcher');
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return ['watcher'];
}
}
| <?php
namespace JasonLewis\ResourceWatcher\Integration;
use Illuminate\Support\ServiceProvider;
use JasonLewis\ResourceWatcher\Tracker;
use JasonLewis\ResourceWatcher\Watcher;
class LaravelServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->singleton('watcher', function ($app) {
return new Watcher(new Tracker, $app['files']);
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return ['watcher'];
}
}
|
Add display user public key | /**
* Secret View
*
* @copyright (c) 2018 Passbolt SARL
* @licence AGPL-3.0 http://www.gnu.org/licenses/agpl-3.0.en.html
*/
"use strict";
var AppView = require('../appView.js');
class UserGetView extends AppView {
constructor (data) {
super();
this.data = [];
this.user = data.body;
this.data[0] = {
'first name': this.user.Profile.first_name,
'last name': this.user.Profile.last_name,
'username': this.user.User.username,
'fingerprint': this.user.Gpgkey.fingerprint,
'UUID': this.user.User.id
};
}
render() {
console.log(this.columnify(this.data, {
minWidth: 20,
columns: ['first name', 'last name', 'username', 'fingerprint', 'UUID'],
config: {
'username' : {maxWidth: 64}
}
}));
console.log('');
console.log(this.user.Gpgkey.armored_key);
}
}
module.exports = UserGetView; | /**
* Secret View
*
* @copyright (c) 2018 Passbolt SARL
* @licence AGPL-3.0 http://www.gnu.org/licenses/agpl-3.0.en.html
*/
"use strict";
var AppView = require('../appView.js');
class UserGetView extends AppView {
constructor (data) {
super();
this.data = [];
var u;
u = data.body;
this.data[0] = {
'first name': u.Profile.first_name,
'last name': u.Profile.last_name,
'username': u.User.username,
'fingerprint': u.Gpgkey.fingerprint,
'UUID': u.User.id
};
}
render() {
console.log(this.columnify(this.data, {
minWidth: 20,
columns: ['first name', 'last name', 'username', 'fingerprint', 'UUID'],
config: {
'username' : {maxWidth: 64}
}
}));
}
}
module.exports = UserGetView; |
Use fs.readSync's options to get base64 string
A tiny simplification. | var postcss = require('postcss'),
mime = require('mime'),
fs = require('fs');
module.exports = postcss.plugin('postcss-data-uri', function (opts) {
return function (css) {
css.walkDecls(/background(\-image)?/i, function (decl) {
var rePattern = /data-uri\(\s*['|"]?(.*?)['|"]?\s*\)/i,
path;
if (rePattern.test(decl.value)) {
path = decl.value.match(rePattern)[1];
if (fs.existsSync(path)) {
decl.value = decl.value.replace(rePattern, 'url(data:' + mime.lookup(path) + ';base64,' + fs.readFileSync(path, 'base64') + ')');
} else {
console.log('Image ',path,' not found.')
}
}
});
};
});
| var postcss = require('postcss'),
mime = require('mime'),
fs = require('fs');
module.exports = postcss.plugin('postcss-data-uri', function (opts) {
return function (css) {
css.walkDecls(/background(\-image)?/i, function (decl) {
var rePattern = /data-uri\(\s*['|"]?(.*?)['|"]?\s*\)/i,
path;
if (rePattern.test(decl.value)) {
path = decl.value.match(rePattern)[1];
if (fs.existsSync(path)) {
decl.value = decl.value.replace(rePattern, 'url(data:' + mime.lookup(path) + ';base64,' + new Buffer(fs.readFileSync(path)).toString('base64') + ')');
} else {
console.log('Image ',path,' not found.')
}
}
});
};
}); |
Fix XHR proxy with non-standard ports
If a non-standard port is used, then the port will double-up at the moment, leading to a failure to contact `example.com:8080:8080`. Specifying `hostname` rather than `host` fixes this issue. | // Copyright (c) Microsoft Corporation. All rights reserved.
var http = require('http'),
https = require('https'),
url = require('url');
module.exports.attach = function (app) {
app.all('/xhr_proxy', function proxyXHR(request, response) {
var requestURL = url.parse(unescape(request.query.rurl));
request.headers.host = requestURL.host;
// fixes encoding issue
delete request.headers['accept-encoding'];
var options = {
hostname: requestURL.hostname,
path: requestURL.path,
port: requestURL.port,
method: request.method,
headers: request.headers
};
var proxyCallback = function (proxyReponse) {
proxyReponse.pipe(response);
};
if (requestURL.protocol === 'https:') {
https.request(options, proxyCallback).end();
} else {
http.request(options, proxyCallback).end();
}
});
};
| // Copyright (c) Microsoft Corporation. All rights reserved.
var http = require('http'),
https = require('https'),
url = require('url');
module.exports.attach = function (app) {
app.all('/xhr_proxy', function proxyXHR(request, response) {
var requestURL = url.parse(unescape(request.query.rurl));
request.headers.host = requestURL.host;
// fixes encoding issue
delete request.headers['accept-encoding'];
var options = {
host: requestURL.host,
path: requestURL.path,
port: requestURL.port,
method: request.method,
headers: request.headers
};
var proxyCallback = function (proxyReponse) {
proxyReponse.pipe(response);
};
if (requestURL.protocol === 'https:') {
https.request(options, proxyCallback).end();
} else {
http.request(options, proxyCallback).end();
}
});
};
|
Throw an exception on an unsupported callable type | <?php
function create_callable($type, $mode)
{
switch ($type) {
case 'method':
return [new TestClass(), 'method'.camelize($mode)];
case 'static_method':
return ['TestClass', 'staticMethod'.camelize($mode)];
case 'invoked_method':
return (new ReflectionClass('Invoke'.camelize($mode).'Class'))->newInstance();
case 'closure':
return (new ReflectionFunction('function_'.$mode))->getClosure();
case 'function':
return 'function_'.$mode;
}
throw new \InvalidArgumentException(sprintf('Unsupported callable type "%s".', $type));
}
function camelize($string)
{
return str_replace(' ', '', ucwords(str_replace('_', ' ', $string)));
}
| <?php
function create_callable($type, $mode)
{
switch ($type) {
case 'method':
return [new TestClass(), 'method'.camelize($mode)];
case 'static_method':
return ['TestClass', 'staticMethod'.camelize($mode)];
case 'invoked_method':
return (new ReflectionClass('Invoke'.camelize($mode).'Class'))->newInstance();
case 'closure':
return (new ReflectionFunction('function_'.$mode))->getClosure();
case 'function':
return 'function_'.$mode;
}
}
function camelize($string)
{
return str_replace(' ', '', ucwords(str_replace('_', ' ', $string)));
}
|
Fix sending along arguments to parent on willTransition | import { inject as service } from '@ember/service';
import EmberRouter from '@ember/routing/router';
import ENV from '../config/environment';
import Configuration from 'ember-routable-modal/configuration';
export default {
name: 'ember-routable-modal',
initialize: function() {
const config = ENV['ember-routable-modal'] || {};
Configuration.load(config);
EmberRouter.reopen({
currentRoutedModalService: service('current-routed-modal'),
willTransition() {
this._super(...arguments);
this.get('currentRoutedModalService').clear();
}
});
}
};
| import { inject as service } from '@ember/service';
import EmberRouter from '@ember/routing/router';
import ENV from '../config/environment';
import Configuration from 'ember-routable-modal/configuration';
export default {
name: 'ember-routable-modal',
initialize: function() {
const config = ENV['ember-routable-modal'] || {};
Configuration.load(config);
EmberRouter.reopen({
currentRoutedModalService: service('current-routed-modal'),
willTransition() {
this._super();
this.get('currentRoutedModalService').clear();
}
});
}
};
|
Fix botched keyword args in rebuild_export_task() | from celery.task import task
from corehq.apps.export.export import get_export_file, rebuild_export
from couchexport.models import Format
from couchexport.tasks import escape_quotes
from soil.util import expose_cached_download
@task
def populate_export_download_task(export_instances, filters, download_id, filename=None, expiry=10 * 60 * 60):
export_file = get_export_file(export_instances, filters)
file_format = Format.from_format(export_file.format)
filename = filename or export_instances[0].name
escaped_filename = escape_quotes('%s.%s' % (filename, file_format.extension))
payload = export_file.file.payload
expose_cached_download(
payload,
expiry,
".{}".format(file_format.extension),
mimetype=file_format.mimetype,
content_disposition='attachment; filename="%s"' % escaped_filename,
download_id=download_id,
)
export_file.file.delete()
@task(queue='background_queue', ignore_result=True)
def rebuild_export_task(export_instance, last_access_cutoff=None, filter=None):
rebuild_export(export_instance, last_access_cutoff, filter)
| from celery.task import task
from corehq.apps.export.export import get_export_file, rebuild_export
from couchexport.models import Format
from couchexport.tasks import escape_quotes
from soil.util import expose_cached_download
@task
def populate_export_download_task(export_instances, filters, download_id, filename=None, expiry=10 * 60 * 60):
export_file = get_export_file(export_instances, filters)
file_format = Format.from_format(export_file.format)
filename = filename or export_instances[0].name
escaped_filename = escape_quotes('%s.%s' % (filename, file_format.extension))
payload = export_file.file.payload
expose_cached_download(
payload,
expiry,
".{}".format(file_format.extension),
mimetype=file_format.mimetype,
content_disposition='attachment; filename="%s"' % escaped_filename,
download_id=download_id,
)
export_file.file.delete()
@task(queue='background_queue', ignore_result=True, last_access_cutoff=None, filter=None)
def rebuild_export_task(export_instance):
rebuild_export(export_instance)
|
Change .map to .forEach so that we can append to a list | import { expeditions } from 'constants/expeditions';
const RECENT_EXPEDITIONS_LENGTH = 4;
export function findExpedition(key) {
return expeditions[key] ? expeditions[key] : expeditions.DEFAULT;
}
export const expeditionsInGroup = (group, allWorkflows) =>
allWorkflows.filter(e => e.display_name.startsWith(group));
export function recentExpeditions(allWorkflows, classifications) {
const ids = classifications.map(c => c.links.workflow)
.filter((v, i, self) => self.indexOf(v) === i);
const recent = [];
ids.forEach(id => {
const workflow = allWorkflows.find(w => w.id === id);
if (workflow) {
const expedition = findExpedition(workflow.display_name);
expedition.id = workflow.id;
expedition.active = workflow.active;
recent.push(expedition);
}
});
if (recent.length > RECENT_EXPEDITIONS_LENGTH) { recent.length = RECENT_EXPEDITIONS_LENGTH; }
return recent;
}
| import { expeditions } from 'constants/expeditions';
const RECENT_EXPEDITIONS_LENGTH = 4;
export function findExpedition(key) {
return expeditions[key] ? expeditions[key] : expeditions.DEFAULT;
}
export const expeditionsInGroup = (group, allWorkflows) =>
allWorkflows.filter(e => e.display_name.startsWith(group));
export function recentExpeditions(allWorkflows, classifications) {
const recent = classifications.map(c => c.links.workflow)
.filter((v, i, self) => self.indexOf(v) === i)
.map(id => {
const workflow = allWorkflows.find(w => w.id === id);
if (workflow) {
const expedition = findExpedition(workflow.display_name);
expedition.id = workflow.id;
expedition.active = workflow.active;
return expedition;
}
});
if (recent.length > RECENT_EXPEDITIONS_LENGTH) { recent.length = RECENT_EXPEDITIONS_LENGTH; }
return recent;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.