text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Add sample param to CV function
Boolean param to make possible to calculate coefficient of variation
for population (default is sample).
|
from .standard_deviation import standard_deviation
from .mean import mean
def coefficient_of_variation(data, sample = True):
"""
The `coefficient of variation`_ is the ratio of the standard deviation to the mean.
.. _`coefficient of variation`: https://en.wikipedia.org/wiki/Coefficient_of_variation
Args:
data: A list of numerical objects.
Returns:
A float object.
Examples:
>>> coefficient_of_variation([1, 2, 3])
0.5
>>> ss.coefficient_of_variation([1, 2, 3], False)
0.408248290463863
>>> coefficient_of_variation([1, 2, 3, 4])
0.5163977794943222
>>> coefficient_of_variation([-1, 0, 1, 2, 3, 4])
1.247219128924647
"""
return standard_deviation(data, sample) / mean(data)
|
from .standard_deviation import standard_deviation
from .mean import mean
def coefficient_of_variation(data):
"""
The `coefficient_of_variation`_ is the ratio of the standard deviation to the mean
.. _`coefficient of variation`: https://en.wikipedia.org/wiki/Coefficient_of_variation
Args:
data: A list of numerical objects.
Returns:
A float object.
Examples:
>>> coefficient_of_variation([1, 2, 3])
0.5
>>> coefficient_of_variation([1, 2, 3, 4])
0.5163977794943222
>>> coefficient_of_variation([-1, 0, 1, 2, 3, 4])
1.247219128924647
"""
return standard_deviation(data) / mean(data)
|
Use defineConfiguration in main route
|
"use strict";
angular.module('arethusa.core').constant('MAIN_ROUTE', {
controller: 'MainCtrl',
template: '<div ng-include="template"></div>',
resolve: {
loadConfiguration: function($q, $http, $route, configurator) {
var params = $route.current.params;
var confPath = './static/configs/';
var confUrl;
// Fall back to default and wrong paths to conf files
// need to be handled separately eventually
if (params.conf) {
confUrl = confPath + params.conf + '.json';
} else if (params.conf_file) {
confUrl = params.conf_file;
} else {
confUrl = confPath + 'default.json';
}
return $http({
method: 'GET',
url: confUrl,
}).then(function(result) {
configurator.defineConfiguration(result.data);
});
}
}
});
|
"use strict";
angular.module('arethusa.core').constant('MAIN_ROUTE', {
controller: 'MainCtrl',
template: '<div ng-include="template"></div>',
resolve: {
loadConfiguration: function($q, $http, $route, configurator) {
var params = $route.current.params;
var confPath = './static/configs/';
var confUrl;
// Fall back to default and wrong paths to conf files
// need to be handled separately eventually
if (params.conf) {
confUrl = confPath + params.conf + '.json';
} else if (params.conf_file) {
confUrl = params.conf_file;
} else {
confUrl = confPath + 'default.json';
}
return $http({
method: 'GET',
url: confUrl,
}).then(function(result) {
configurator.configuration = result.data;
});
}
}
});
|
Add an additional match line for http
Add an additional match line for http so the script script runs on http/s.
|
// ==UserScript==
// @name Display Stats
// @namespace https://github.com/EFox2413/initiumGrease
// @version 0.1
// @description try to take over the world!
// @author EFox2413
// @match https://www.playinitium.com/*
// @match http://www.playinitium.com/*
// @grant none
// ==/UserScript==
/* jshint -W097 */
'use strict';
var $ = window.jQuery;
var charDiv = $('.character-display-box').children(" div:nth-child(3)").children( 'a' );
var statsItems;
var statsID = ["S", "D", "I", "W"];
var href = $( '.character-display-box').children().first().attr( "rel" );
$.ajax({
url: href,
type: "GET",
success: function(data) {
statsItems = $(data).find('.main-item-subnote');
statsItems.each(function( index ) {
if ( index > 0 ) {
charDiv.append( " <span style=\"font-size:small\"> " + statsID[index - 1] + ":" + $( this ).text().split(" ")[0] + " </span>");
}
});
}
});
|
// ==UserScript==
// @name Display Stats
// @namespace https://github.com/EFox2413/initiumGrease
// @version 0.1
// @description try to take over the world!
// @author EFox2413
// @match https://www.playinitium.com/*
// @grant none
// ==/UserScript==
/* jshint -W097 */
'use strict';
var $ = window.jQuery;
var charDiv = $('.character-display-box').children(" div:nth-child(3)").children( 'a' );
var statsItems;
var statsID = ["S", "D", "I", "W"];
var href = $( '.character-display-box').children().first().attr( "rel" );
$.ajax({
url: href,
type: "GET",
success: function(data) {
statsItems = $(data).find('.main-item-subnote');
statsItems.each(function( index ) {
if ( index > 0 ) {
charDiv.append( " <span style=\"font-size:small\"> " + statsID[index - 1] + ":" + $( this ).text().split(" ")[0] + " </span>");
}
});
}
});
|
Use shortcuts-nightly.json to resolve model shortcuts
|
# inspired from:
# https://python-packaging-user-guide.readthedocs.org/en/latest/single_source_version/
# https://github.com/pypa/warehouse/blob/master/warehouse/__about__.py
__title__ = 'spacy-nightly'
__version__ = '2.0.0a18'
__summary__ = 'Industrial-strength Natural Language Processing (NLP) with Python and Cython'
__uri__ = 'https://spacy.io'
__author__ = 'Explosion AI'
__email__ = 'contact@explosion.ai'
__license__ = 'MIT'
__release__ = False
__docs_models__ = 'https://alpha.spacy.io/usage/models'
__download_url__ = 'https://github.com/explosion/spacy-models/releases/download'
__compatibility__ = 'https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json'
__shortcuts__ = 'https://raw.githubusercontent.com/explosion/spacy-models/master/shortcuts-nightly.json'
__model_files__ = 'https://raw.githubusercontent.com/explosion/spacy-dev-resources/develop/templates/model/'
|
# inspired from:
# https://python-packaging-user-guide.readthedocs.org/en/latest/single_source_version/
# https://github.com/pypa/warehouse/blob/master/warehouse/__about__.py
__title__ = 'spacy-nightly'
__version__ = '2.0.0a18'
__summary__ = 'Industrial-strength Natural Language Processing (NLP) with Python and Cython'
__uri__ = 'https://spacy.io'
__author__ = 'Explosion AI'
__email__ = 'contact@explosion.ai'
__license__ = 'MIT'
__release__ = False
__docs_models__ = 'https://alpha.spacy.io/usage/models'
__download_url__ = 'https://github.com/explosion/spacy-models/releases/download'
__compatibility__ = 'https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json'
__shortcuts__ = 'https://raw.githubusercontent.com/explosion/spacy-models/master/shortcuts.json'
__model_files__ = 'https://raw.githubusercontent.com/explosion/spacy-dev-resources/develop/templates/model/'
|
Add license header for MPL 2.0
|
/*
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
var BASE = 'extensions.auto-confirm@myokoym.net.';
var prefs = require('lib/prefs').prefs;
function log(message) {
if (prefs.getPref(BASE + 'debug')) {
console.log("auto-confirm: " + message);
}
}
load('lib/WindowManager');
var global = this;
function handleWindow(aWindow)
{
log("handleWindow");
var doc = aWindow.document;
if (doc.documentElement.localName === 'dialog' &&
doc.documentElement.id === 'commonDialog') {
handleCommonDialog(aWindow);
return;
}
}
function handleCommonDialog(aWindow)
{
log("commonDialog");
aWindow.setTimeout(function() {
log("cancelDialog");
doc.documentElement.cancelDialog();
}, 10000);
}
WindowManager.addHandler(handleWindow);
function shutdown()
{
WindowManager = undefined;
global = undefined;
}
|
var BASE = 'extensions.auto-confirm@myokoym.net.';
var prefs = require('lib/prefs').prefs;
function log(message) {
if (prefs.getPref(BASE + 'debug')) {
console.log("auto-confirm: " + message);
}
}
load('lib/WindowManager');
var global = this;
function handleWindow(aWindow)
{
log("handleWindow");
var doc = aWindow.document;
if (doc.documentElement.localName === 'dialog' &&
doc.documentElement.id === 'commonDialog') {
handleCommonDialog(aWindow);
return;
}
}
function handleCommonDialog(aWindow)
{
log("commonDialog");
aWindow.setTimeout(function() {
log("cancelDialog");
doc.documentElement.cancelDialog();
}, 10000);
}
WindowManager.addHandler(handleWindow);
function shutdown()
{
WindowManager = undefined;
global = undefined;
}
|
Disable date_hierarchy for now since it requires tzinfo in MySQL
|
# -*- coding: utf-8 -*-
from django.contrib import admin
from .models import Project, Repository, Change, Builder, Build
class ProjectAdmin(admin.ModelAdmin):
list_display = ('name',)
search_fields = ('name',)
class RepositoryAdmin(admin.ModelAdmin):
list_display = ('name',)
search_fields = ('name',)
class ChangeAdmin(admin.ModelAdmin):
list_display = ('project', 'repository', 'revision', 'when', 'who')
list_filter = ('project', 'repository', 'when')
search_fields = ('revision', 'comments', 'who')
#date_hierarchy = 'when'
class BuilderAdmin(admin.ModelAdmin):
list_display = ('name', 'link')
search_fields = ('name', 'link')
class BuildAdmin(admin.ModelAdmin):
filter_horizontal = ('changes',)
list_display = ('builder', 'number', 'result', 'simplified_result',
'start_time', 'end_time', 'duration')
list_filter = ('builder', 'result', 'simplified_result', 'start_time')
search_fields = ('changes__revision', 'changes__comments', 'changes__who')
#date_hierarchy = 'start_time'
admin.site.register(Project, ProjectAdmin)
admin.site.register(Repository, RepositoryAdmin)
admin.site.register(Change, ChangeAdmin)
admin.site.register(Builder, BuilderAdmin)
admin.site.register(Build, BuildAdmin)
|
# -*- coding: utf-8 -*-
from django.contrib import admin
from .models import Project, Repository, Change, Builder, Build
class ProjectAdmin(admin.ModelAdmin):
list_display = ('name',)
search_fields = ('name',)
class RepositoryAdmin(admin.ModelAdmin):
list_display = ('name',)
search_fields = ('name',)
class ChangeAdmin(admin.ModelAdmin):
list_display = ('project', 'repository', 'revision', 'when', 'who')
list_filter = ('project', 'repository', 'when')
search_fields = ('revision', 'comments', 'who')
date_hierarchy = 'when'
class BuilderAdmin(admin.ModelAdmin):
list_display = ('name', 'link')
search_fields = ('name', 'link')
class BuildAdmin(admin.ModelAdmin):
filter_horizontal = ('changes',)
list_display = ('builder', 'number', 'result', 'simplified_result',
'start_time', 'end_time', 'duration')
list_filter = ('builder', 'result', 'simplified_result', 'start_time')
search_fields = ('changes__revision', 'changes__comments', 'changes__who')
date_hierarchy = 'start_time'
admin.site.register(Project, ProjectAdmin)
admin.site.register(Repository, RepositoryAdmin)
admin.site.register(Change, ChangeAdmin)
admin.site.register(Builder, BuilderAdmin)
admin.site.register(Build, BuildAdmin)
|
Test AEP and non-API 404s
Signed-off-by: shaisachs <47bd79f9420edf5d0991d1e2710179d4e040d480@ngpvan.com>
|
/*global describe, it */
/*exported should */
/*jshint -W030 */
var should = require('should'),
supertest = require('supertest'),
app = require('../app');
describe('notSupported', function() {
it('should not support any resources', function(done) {
supertest(app).
get('/api/v1/questions').
expect(500, function(err, res) {
should.equal(res.body.request_type, 'atomic');
should.equal(res.body.response_code, 500);
res.body.resource_status.should.be.length(1);
should.equal(res.body.resource_status[0].resource, '*');
should.equal(res.body.resource_status[0].response_code, '500');
res.body.resource_status[0].errors.should.be.length(1);
should.equal(
res.body.resource_status[0].errors[0].code,
'NOT_SUPPORTED');
done();
});
});
it('should 404 non-api requests', function(done) {
supertest(app).
get('/allTheThings').
expect(404, done);
});
});
|
/*global describe, it */
/*exported should */
/*jshint -W030 */
var should = require('should'),
supertest = require('supertest'),
app = require('../app');
describe('notSupported', function() {
it('should not support anything', function(done) {
supertest(app).
get('/api/v1/').
expect(500, function(err, res) {
should.equal(res.body.request_type, 'atomic');
should.equal(res.body.response_code, 500);
res.body.resource_status.should.be.length(1);
should.equal(res.body.resource_status[0].resource, '*');
should.equal(res.body.resource_status[0].response_code, '500');
res.body.resource_status[0].errors.should.be.length(1);
should.equal(
res.body.resource_status[0].errors[0].code,
'NOT_SUPPORTED');
done();
});
});
});
|
Revert "Complete the Expects Koans"
This reverts commit d41553a5d48d0d5f10e9f90e0cf4f84e1faf1a73.
|
describe("About Expects", function() {
// We shall contemplate truth by testing reality, via spec expectations.
it("should expect true", function() {
expect(false).toBeTruthy(); // This should be true
});
// To understand reality, we must compare our expectations against reality.
it("should expect equality", function() {
var expectedValue = FILL_ME_IN;
var actualValue = 1 + 1;
expect(actualValue === expectedValue).toBeTruthy();
});
// Some ways of asserting equality are better than others.
it("should assert equality a better way", function() {
var expectedValue = FILL_ME_IN;
var actualValue = 1 + 1;
// toEqual() compares using common sense equality.
expect(actualValue).toEqual(expectedValue);
});
// Sometimes you need to be precise about what you "type".
it("should assert equality with ===", function() {
var expectedValue = FILL_ME_IN;
var actualValue = (1 + 1).toString();
// toBe() will always use === to compare.
expect(actualValue).toBe(expectedValue);
});
// Sometimes we will ask you to fill in the values.
it("should have filled in values", function() {
expect(1 + 1).toEqual(FILL_ME_IN);
});
});
|
describe("About Expects", function() {
// We shall contemplate truth by testing reality, via spec expectations.
it("should expect true", function() {
expect(true).toBeTruthy(); // This should be true
});
// To understand reality, we must compare our expectations against reality.
it("should expect equality", function() {
var expectedValue = 2;
var actualValue = 1 + 1;
expect(actualValue === expectedValue).toBeTruthy();
});
// Some ways of asserting equality are better than others.
it("should assert equality a better way", function() {
var expectedValue = 2;
var actualValue = 1 + 1;
// toEqual() compares using common sense equality.
expect(actualValue).toEqual(expectedValue);
});
// Sometimes you need to be precise about what you "type".
it("should assert equality with ===", function() {
var expectedValue = '2';
var actualValue = (1 + 1).toString();
// toBe() will always use === to compare.
expect(actualValue).toBe(expectedValue);
});
// Sometimes we will ask you to fill in the values.
it("should have filled in values", function() {
expect(1 + 1).toEqual(2);
});
});
|
Fix indentation problem and line length (PEP8)
|
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
@python_2_unicode_compatible
class Email(models.Model):
"""Model to store outgoing email information"""
from_email = models.TextField(_("from e-mail"))
recipients = models.TextField(_("recipients"))
subject = models.TextField(_("subject"))
body = models.TextField(_("body"))
ok = models.BooleanField(_("ok"), default=False, db_index=True)
date_sent = models.DateTimeField(_("date sent"), auto_now_add=True,
db_index=True)
def __str__(self):
return "{s.recipients}: {s.subject}".format(s=self)
class Meta:
verbose_name = _("e-mail")
verbose_name_plural = _("e-mails")
ordering = ('-date_sent',)
|
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
@python_2_unicode_compatible
class Email(models.Model):
"""Model to store outgoing email information"""
from_email = models.TextField(_("from e-mail"))
recipients = models.TextField(_("recipients"))
subject = models.TextField(_("subject"))
body = models.TextField(_("body"))
ok = models.BooleanField(_("ok"), default=False, db_index=True)
date_sent = models.DateTimeField(_("date sent"), auto_now_add=True, db_index=True)
def __str__(self):
return "{s.recipients}: {s.subject}".format(s=self)
class Meta:
verbose_name = _("e-mail")
verbose_name_plural = _("e-mails")
ordering = ('-date_sent',)
|
Add links on 'about me' to Oracle and Tape Storage.
|
<?php require('../header-navbar.php'); ?>
<div class="row">
<div class="col-md-12">
<h1>About me</h1>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-md-10 col-md-offset-1 col-lg-8 col-lg-offset-2">
<p>I'm Rob Dimsdale, a software developer currently based near Boulder, CO, where I work for <a href="http://www.oracle.com">Oracle</a> in the <a href="http://www.oracle.com/us/products/servers-storage/storage/tape-storage/overview/index.html">Tape Storage</a> division (yes that business is still going and is in fact quite healthy). Prior to moving to the US I worked for <a href="http://www.softwire.com">Softwire</a> in London, UK.</p>
<p>Whilst my primary focus to date has been Java web applications with a decent dose of systems-administration, I'm interested in all sorts of languages and frameworks. At the low-level I've worked on embedded C projects and hardware and at the opposite end I'm working on projects using scripting languages including Python and MATLAB.</p>
<p>For more details, see my <a href="/resume/">resume</a></p>
</div>
</div>
<br/>
<?php require('../buttons.php'); ?>
<?php require('../footer.php'); ?>
|
<?php require('../header-navbar.php'); ?>
<div class="row">
<div class="col-md-12">
<h1>About me</h1>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-md-10 col-md-offset-1 col-lg-8 col-lg-offset-2">
<p>I'm Rob Dimsdale, a software developer currently based near Boulder, CO, where I work for Oracle in the Tape Storage division (yes that business is still going and is in fact quite healthy). Prior to moving to the US I worked for <a href="http://www.softwire.com">Softwire</a> in London, UK.</p>
<p>Whilst my primary focus to date has been Java web applications with a decent dose of systems-administration, I'm interested in all sorts of languages and frameworks. At the low-level I've worked on embedded C projects and hardware and at the opposite end I'm working on projects using scripting languages including Python and MATLAB.</p>
<p>For more details, see my <a href="/resume/">resume</a></p>
</div>
</div>
<br/>
<?php require('../buttons.php'); ?>
<?php require('../footer.php'); ?>
|
Add some extra characters in
|
const config = require('config');
const crypto = require('crypto');
module.exports.info = {
name: 'Rate and Rank',
description: 'Interprets and determines the relevant rank for a query',
category: 'Fun',
aliases: [
'rate',
'rank'
],
use: [
{
name: '',
value: 'Rate the empty air of silence after you and your children\'s deaths, past the end of civilisation, past the end of our Sun, past the heat death of the universe, and is at a global temperature of absolute zero.'
}, {
name: '<thing>',
value: 'Rate the thing'
}
]
};
module.exports.command = (message) => {
if (message.input) {
const input = message.input.replace(/[^@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\]^_`abcdefghijklmno0123456789:;<=>?pqrstuvwxyz{|}~!ツ/' ]/g, '');
const hash = crypto.createHash('md5').update(input + config.get('secret')).digest('hex').substring(0, 4);
const rank = parseInt(hash, 16) % 11;
const thing = message.input.length < 100 ? input : `${input.substring(0, 100)}...`;
message.channel.createMessage(`I ${message.command} ${thing} a ${rank} out of 10`);
}
};
|
const config = require('config');
const crypto = require('crypto');
module.exports.info = {
name: 'Rate and Rank',
description: 'Interprets and determines the relevant rank for a query',
category: 'Fun',
aliases: [
'rate',
'rank'
],
use: [
{
name: '',
value: 'Rate the empty air of silence after you and your children\'s deaths, past the end of civilisation, past the end of our Sun, past the heat death of the universe, and is at a global temperature of absolute zero.'
}, {
name: '<thing>',
value: 'Rate the thing'
}
]
};
module.exports.command = (message) => {
if (message.input) {
const input = message.input.replace(/[^@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\]^_`abcdefghijklmno0123456789:;<=>?pqrstuvwxyz{|}~!ツ ]/g, '');
const hash = crypto.createHash('md5').update(input + config.get('secret')).digest('hex').substring(0, 4);
const rank = parseInt(hash, 16) % 11;
const thing = message.input.length < 100 ? input : `${input.substring(0, 100)}...`;
message.channel.createMessage(`I ${message.command} ${thing} a ${rank} out of 10`);
}
};
|
Change to using a request writer interface.
|
package upload
import "github.com/materials-commons/mcstore/pkg/app/flow"
type uploader struct {
tracker *uploadTracker
w RequestWriter
}
func newUploader() *uploader {
return &uploader{
tracker: newUploadTracker(),
}
}
func (u *uploader) processRequest(request *flow.Request) error {
if err := u.w.Write(request); err != nil {
// write failed for some reason
return err
}
if u.uploadDone(request) {
u.assembleUpload(request)
}
return nil
}
func (u *uploader) uploadDone(request *flow.Request) bool {
id := request.UploadID()
count := u.tracker.increment(id)
return count == request.FlowTotalChunks
}
func (u *uploader) assembleUpload(request *flow.Request) {
assembler := newAssembler(request, u.tracker)
assembler.launch()
}
type uploadFinisher struct {
uploadID string
tracker *uploadTracker
}
func newUploadFinisher(uploadID string, tracker *uploadTracker) *uploadFinisher {
return &uploadFinisher{
uploadID: uploadID,
tracker: tracker,
}
}
func (f *uploadFinisher) Finish() error {
f.tracker.clear(f.uploadID)
return nil
}
|
package upload
import "github.com/materials-commons/mcstore/pkg/app/flow"
type uploader struct {
tracker *uploadTracker
}
func newUploader() *uploader {
return &uploader{
tracker: newUploadTracker(),
}
}
func (u *uploader) processRequest(request *flow.Request) error {
if err := request.Write(); err != nil {
// write failed for some reason
return err
}
if u.uploadDone(request) {
u.assembleUpload(request)
}
return nil
}
func (u *uploader) uploadDone(request *flow.Request) bool {
id := request.UploadID()
count := u.tracker.increment(id)
return count == request.FlowTotalChunks
}
func (u *uploader) assembleUpload(request *flow.Request) {
assembler := newAssembler(request, u.tracker)
assembler.launch()
}
type uploadFinisher struct {
uploadID string
tracker *uploadTracker
}
func newUploadFinisher(uploadID string, tracker *uploadTracker) *uploadFinisher {
return &uploadFinisher{
uploadID: uploadID,
tracker: tracker,
}
}
func (f *uploadFinisher) Finish() error {
f.tracker.clear(f.uploadID)
return nil
}
|
Add inline field mixin to base block class.
|
import inlineFieldMixin from 'mixins/inlineFieldMixin';
export default {
props: [
'type',
'index',
'fields',
'other'
],
mixins: [inlineFieldMixin],
data() {
return { ...this.fields };
},
created() {
this.fieldElements = {};
this.watching = {};
this.watchFields(this.fields);
// should only be triggered when all fields are overwitten
this.$watch('fields', () => {
this.watchFields(this.fields);
});
},
methods: {
watchFields(fields) {
Object.keys(fields).map((name) => {
if(!this.watching[name]) {
this.watching[name] = true;
this.$watch(`fields.${name}`, (newVal) => {
if(this.internalChange) {
this.internalChange = false;
return;
}
this[name] = newVal;
}, {
deep: true
});
}
});
}
}
};
|
export default {
props: [
'type',
'index',
'fields',
'other'
],
data() {
return this.fields;
},
created() {
this.watching = {};
this.watchFields(this.fields);
// should only be triggered when all fields are overwitten
this.$watch('fields', () => {
this.watchFields(this.fields);
});
// TODO: deal with fields that have nested data?
},
methods: {
watchFields(fields) {
Object.keys(fields).map((name) => {
if(!this.watching[name]) {
this.watching[name] = true;
this.$watch(`fields.${name}`, (newVal) => {
this[name] = newVal;
}, {
deep: true
});
}
});
}
}
};
|
Build script: move resolveModuleSource outside waterfall function
|
const babel = require('babel-core');
const glob = require('glob');
const fs = require('fs');
const _ = require('async');
const babelrc = {
presets: ['es2015'],
plugins: ['add-module-exports'],
resolveModuleSource(source) {
return source
.replace('./util', './lib/util')
.replace('../util', './util');
},
};
glob('{index,*/**}.js', { cwd: 'src' }, (globErr, files) => {
_.each(files, (file, done) => {
_.waterfall([
(transformDone) => {
babel.transformFile(`src/${file}`, babelrc, transformDone);
},
(result, writeDone) => {
const dest = file.replace(/^util/, 'lib/util');
fs.writeFile(dest, result.code, writeDone);
},
], done);
}, (err) => {
if (err) return console.error('Error writing lib files:', err);
console.info('lib files written');
});
});
|
const babel = require('babel-core');
const glob = require('glob');
const fs = require('fs');
const _ = require('async');
const babelrc = {
presets: ['es2015'],
plugins: ['add-module-exports'],
};
glob('{index,*/**}.js', { cwd: 'src' }, (globErr, files) => {
_.each(files, (file, done) => {
_.waterfall([
(transformDone) => {
const options = Object.assign({
resolveModuleSource(source) {
return source
.replace('./util', './lib/util')
.replace('../util', './util');
},
}, babelrc);
babel.transformFile(`src/${file}`, options, transformDone);
},
(result, writeDone) => {
const dest = file.replace(/^util/, 'lib/util');
fs.writeFile(dest, result.code, writeDone);
},
], done);
}, (err) => {
if (err) return console.error('Error writing lib files:', err);
console.info('lib files written');
});
});
|
Fix TypeError on mandrill email sending
json.loads() does not accept bytes as input in python < 3.6.
|
# coding: utf8
import json
import logging
from labonneboite.conf import settings
logger = logging.getLogger('main')
class EmailClient(object):
to = settings.FORM_EMAIL
from_email = settings.ADMIN_EMAIL
subject = 'nouveau message entreprise LBB'
class MandrillClient(EmailClient):
def __init__(self, mandrill):
self.mandrill = mandrill
def send(self, html):
from_email = self.from_email
to_email = self.to
response = self.mandrill.send_email(
subject=self.subject,
to=[{'email': to_email}],
html=html,
from_email=from_email)
content = json.loads(response.content.decode())
if content[0]["status"] != "sent":
raise Exception("email was not sent from %s to %s" % (from_email, to_email))
return response
|
# coding: utf8
import json
import logging
from labonneboite.conf import settings
logger = logging.getLogger('main')
class EmailClient(object):
to = settings.FORM_EMAIL
from_email = settings.ADMIN_EMAIL
subject = 'nouveau message entreprise LBB'
class MandrillClient(EmailClient):
def __init__(self, mandrill):
self.mandrill = mandrill
def send(self, html):
from_email = self.from_email
to_email = self.to
response = self.mandrill.send_email(
subject=self.subject,
to=[{'email': to_email}],
html=html,
from_email=from_email)
content = json.loads(response.content)
if content[0]["status"] != "sent":
raise Exception("email was not sent from %s to %s" % (from_email, to_email))
return response
|
Add support for new auth plugins.
|
<?php
namespace Captcha\Controller;
use App\Controller\AppController;
use Cake\Event\EventInterface;
/**
* @property \Captcha\Model\Table\CaptchasTable $Captchas
* @property \Captcha\Controller\Component\PreparerComponent $Preparer
*/
class CaptchaController extends AppController {
/**
* @var string
*/
protected $modelClass = 'Captcha.Captchas';
/**
* @return void
*/
public function initialize(): void {
parent::initialize();
$this->loadComponent('Captcha.Preparer');
}
/**
* @param \Cake\Event\EventInterface $event
* @return \Cake\Http\Response|null|void
*/
public function beforeFilter(EventInterface $event) {
if (isset($this->Auth)) {
$this->Auth->allow();
} elseif (isset($this->Authentication) && method_exists($this->Authentication, 'addUnauthenticatedActions')) {
$this->Authentication->addUnauthenticatedActions(['display']);
}
}
/**
* Displays a captcha image
*
* @param int|null $id
* @return \Cake\Http\Response|null|void
*/
public function display($id = null) {
$captcha = $this->Captchas->get($id);
$captcha = $this->Preparer->prepare($captcha);
$this->set(compact('captcha'));
$this->viewBuilder()->setClassName('Captcha.Captcha');
$this->viewBuilder()->setTemplatePath('Captcha');
}
}
|
<?php
namespace Captcha\Controller;
use App\Controller\AppController;
use Cake\Event\EventInterface;
/**
* @property \Captcha\Model\Table\CaptchasTable $Captchas
* @property \Captcha\Controller\Component\PreparerComponent $Preparer
*/
class CaptchaController extends AppController {
/**
* @var string
*/
protected $modelClass = 'Captcha.Captchas';
/**
* @return void
*/
public function initialize(): void {
parent::initialize();
$this->loadComponent('Captcha.Preparer');
}
/**
* @param \Cake\Event\EventInterface $event
* @return \Cake\Http\Response|null|void
*/
public function beforeFilter(EventInterface $event) {
if (isset($this->Auth)) {
$this->Auth->allow();
}
}
/**
* Displays a captcha image
*
* @param int|null $id
* @return \Cake\Http\Response|null|void
*/
public function display($id = null) {
$captcha = $this->Captchas->get($id);
$captcha = $this->Preparer->prepare($captcha);
$this->set(compact('captcha'));
$this->viewBuilder()->setClassName('Captcha.Captcha');
$this->viewBuilder()->setTemplatePath('Captcha');
}
}
|
Fix resolver failing for default param descriptions.
|
import BaseResolver from './BaseResolver';
import { STRING } from '../parsers/Types';
/**
* @classdesc Options resolver for command parameter definitions.
* @extends BaseResolver
*/
export default class ParameterResolver extends BaseResolver {
/**
* Constructor.
*/
constructor() {
super();
this.resolver.setRequired('name')
.setDefaults({
description: null,
optional: false,
type: STRING,
repeatable: false,
literal: false,
defaultValue: options => (options.repeatable ? [] : null),
})
.setAllowedTypes('name', 'string')
.setAllowedTypes('description', ['string', 'null'])
.setAllowedTypes('optional', 'boolean')
.setAllowedTypes('type', 'string')
.setAllowedTypes('repeatable', 'boolean')
.setAllowedTypes('literal', 'boolean');
}
}
|
import BaseResolver from './BaseResolver';
import { STRING } from '../parsers/Types';
/**
* @classdesc Options resolver for command parameter definitions.
* @extends BaseResolver
*/
export default class ParameterResolver extends BaseResolver {
/**
* Constructor.
*/
constructor() {
super();
this.resolver.setRequired('name')
.setDefaults({
description: null,
optional: false,
type: STRING,
repeatable: false,
literal: false,
defaultValue: options => (options.repeatable ? [] : null),
})
.setAllowedTypes('name', 'string')
.setAllowedTypes('optional', 'boolean')
.setAllowedTypes('type', 'string')
.setAllowedTypes('repeatable', 'boolean')
.setAllowedTypes('literal', 'boolean');
}
}
|
Add setup and teardown to hash table test suite.
|
import org.junit.*;
public class HashTableTest {
private HashTable ht;
@Before
public void init() {
ht = new HashTable(17);
}
@After
public void clear() {
ht = null;
}
@Test
public void testInsertEntry() {
ht.hashFunctionMod("5");
// Assert here
}
@Test
public void testFindKeyLast() {
ht.hashFunctionMod("35");
ht.hashFunctionMod("40");
ht.hashFunctionMod("45");
ht.hashFunctionMod("50");
ht.hashFunctionMod("55");
// Assert here
}
@Test
public void testFindKeyFirst() {
ht.hashFunctionMod("35");
ht.hashFunctionMod("40");
ht.hashFunctionMod("45");
ht.hashFunctionMod("50");
ht.hashFunctionMod("55");
// Assert here
}
}
|
import org.junit.*;
public class HashTableTest {
@Test
public void testInsertEntry() {
HashTable ht = new HashTable(17);
ht.hashFunctionMod("5");
}
@Test
public void testFindKeyLast() {
HashTable ht = new HashTable(17);
ht.hashFunctionMod("35");
ht.hashFunctionMod("40");
ht.hashFunctionMod("45");
ht.hashFunctionMod("50");
ht.hashFunctionMod("55");
}
@Test
public void testFindKeyFirst() {
HashTable ht = new HashTable(17);
ht.hashFunctionMod("35");
ht.hashFunctionMod("40");
ht.hashFunctionMod("45");
ht.hashFunctionMod("50");
ht.hashFunctionMod("55");
}
}
|
[test] Add one more failed server
|
var net = require('net'),
path = require('path'),
assert = require('assert'),
spawn = require('child_process').spawn,
cb = require('assert-called');
var PORT = 5434;
var server = net.createServer(cb(function (socket) {
var data = '';
socket.on('readable', cb(function () {
var chunk = socket.read();
if (chunk) {
data += chunk;
}
}));
socket.on('end', cb(function () {
data = data.split('\n').filter(Boolean).map(JSON.parse);
assert(data.length > 0);
server.close();
}));
}));
server.listen(PORT, function () {
var child = spawn(
path.join(__dirname, '..', 'estragon'),
[
'-h', '127.0.0.1:' + (PORT - 2).toString(),
'-h', '127.0.0.1:' + (PORT - 1).toString(),
'-h', '127.0.0.1:' + PORT.toString(),
'--', 'node', path.join(__dirname, 'fixtures', 'exit-after-1-s.js')
]
);
});
|
var net = require('net'),
path = require('path'),
assert = require('assert'),
spawn = require('child_process').spawn,
cb = require('assert-called');
var PORT = 5434;
var server = net.createServer(cb(function (socket) {
var data = '';
socket.on('readable', cb(function () {
var chunk = socket.read();
if (chunk) {
data += chunk;
}
}));
socket.on('end', cb(function () {
data = data.split('\n').filter(Boolean).map(JSON.parse);
assert(data.length > 0);
server.close();
}));
}));
server.listen(PORT, function () {
var child = spawn(
path.join(__dirname, '..', 'estragon'),
[
'-h', '127.0.0.1:' + (PORT - 1).toString(),
'-h', '127.0.0.1:' + PORT.toString(),
'--', 'node', path.join(__dirname, 'fixtures', 'exit-after-1-s.js')
]
);
});
|
Add momentum scrolling on iOS for book lists
|
// @flow
/**
* Part of GDL gdl-frontend.
* Copyright (C) 2017 GDL
*
* See LICENSE
*/
import * as React from 'react';
import Flex from './Flex';
import type { Book } from '../types';
import BookCardCover from './BookCardCover';
import { Link } from '../routes';
const FlexScroller = Flex.extend`
overflow-x: auto;
-webkit-overflow-scrolling: touch;
`;
type Props = {
books: Array<Book>,
route: (book: Book) => string,
};
const BookList = ({ books, route, ...props }: Props) => (
<FlexScroller mx={-6} {...props}>
{books.map(book => (
<Link route={route(book)} key={book.id}>
<a>
<BookCardCover book={book} mx={6} />
</a>
</Link>
))}
</FlexScroller>
);
BookList.defaultProps = {
route: (book: Book) => `/${book.language.code}/books/${book.id}`,
};
export default BookList;
|
// @flow
/**
* Part of GDL gdl-frontend.
* Copyright (C) 2017 GDL
*
* See LICENSE
*/
import * as React from 'react';
import Flex from './Flex';
import type { Book } from '../types';
import BookCardCover from './BookCardCover';
import { Link } from '../routes';
const FlexScroller = Flex.extend`
overflow-x: auto;
`;
type Props = {
books: Array<Book>,
route: (book: Book) => string,
};
const BookList = ({ books, route, ...props }: Props) => (
<FlexScroller mx={-6} {...props}>
{books.map(book => (
<Link route={route(book)} key={book.id}>
<a>
<BookCardCover book={book} mx={6} />
</a>
</Link>
))}
</FlexScroller>
);
BookList.defaultProps = {
route: (book: Book) => `/${book.language.code}/books/${book.id}`,
};
export default BookList;
|
Use 401 for CSRF failure. Always CSRF even in DEBUG
|
# Oxypanel
# File: util/csrf.py
# Desc: csrf protection!
from uuid import uuid4
from flask import session, abort, request, Markup
from app import app
# Check all POST/PUT/DELETE's
# 403 on failure
@app.before_request
def csrf_check():
# TODO: Check referrer matches us
# Check a valid csrf_token was presented
if request.method in ['POST', 'PUT', 'DELETE']:
token = session.pop('csrf_token', None)
if not token or token != str(request.form.get('csrf_token')):
abort(401)
# Generate/store CSRF tokens
def generate_csrf():
if 'csrf_token' not in session:
session['csrf_token'] = str(uuid4())
return session['csrf_token']
app.jinja_env.globals['csrf_token'] = generate_csrf
# Template shortcut
def generate_csrf_input():
token = generate_csrf()
return Markup('<input type="hidden" name="csrf_token" value="{0}" />'.format(token))
app.jinja_env.globals['csrf_input'] = generate_csrf_input
|
# Oxypanel
# File: util/csrf.py
# Desc: csrf protection!
from uuid import uuid4
from flask import session, abort, request, Markup
import config
from app import app
# Check all POST/PUT/DELETE's
# 403 on failure
@app.before_request
def csrf_check():
# No check when debugging
if config.DEBUG:
return
# TODO: Check referrer matches us
# Check a valid csrf_token was presented
if request.method in ['POST', 'PUT', 'DELETE']:
token = session.pop('csrf_token', None)
if not token or token != str(request.form.get('csrf_token')):
abort(403)
# Generate/store CSRF tokens
def generate_csrf():
if 'csrf_token' not in session:
session['csrf_token'] = str(uuid4())
return session['csrf_token']
app.jinja_env.globals['csrf_token'] = generate_csrf
# Template shortcut
def generate_csrf_input():
token = generate_csrf()
return Markup('<input type="hidden" name="csrf_token" value="{0}" />'.format(token))
app.jinja_env.globals['csrf_input'] = generate_csrf_input
|
Clear easy mode on /cto
Why are we clearing bypass mode but not easy mode?
|
package vg.civcraft.mc.citadel.command.commands;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import vg.civcraft.mc.citadel.PlayerState;
import vg.civcraft.mc.citadel.Utility;
import vg.civcraft.mc.civmodcore.command.PlayerCommand;
import java.util.ArrayList;
import java.util.List;
public class Off extends PlayerCommand{
public Off(String name) {
super(name);
setIdentifier("cto");
setDescription("Turns all Reinforcement Modes off.");
setUsage("/cto");
setArguments(0,0);
}
@Override
public boolean execute(CommandSender sender, String[] args) {
if (!(sender instanceof Player)){
sender.sendMessage("Must be a player to run this command.");
return true;
}
Player p = (Player) sender;
PlayerState state = PlayerState.get(p);
state.reset();
if (state.isBypassMode()) {
state.toggleBypassMode();
}
if (state.getEasyMode()) {
state.toggleEasyMode();
}
Utility.sendAndLog(p, ChatColor.GREEN, "Reinforcement mode has been set to Normal.");
return true;
}
@Override
public List<String> tabComplete(CommandSender sender, String[] args) {
return new ArrayList<String>();
}
}
|
package vg.civcraft.mc.citadel.command.commands;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import vg.civcraft.mc.citadel.PlayerState;
import vg.civcraft.mc.citadel.Utility;
import vg.civcraft.mc.civmodcore.command.PlayerCommand;
import java.util.ArrayList;
import java.util.List;
public class Off extends PlayerCommand{
public Off(String name) {
super(name);
setIdentifier("cto");
setDescription("Turns all Reinforcement Modes off.");
setUsage("/cto");
setArguments(0,0);
}
@Override
public boolean execute(CommandSender sender, String[] args) {
if (!(sender instanceof Player)){
sender.sendMessage("Must be a player to run this command.");
return true;
}
Player p = (Player) sender;
PlayerState state = PlayerState.get(p);
state.reset();
if (state.isBypassMode()) {
state.toggleBypassMode();
}
Utility.sendAndLog(p, ChatColor.GREEN, "Reinforcement mode has been set to Normal.");
return true;
}
@Override
public List<String> tabComplete(CommandSender sender, String[] args) {
return new ArrayList<String>();
}
}
|
Adjust javascript for updated html structure
|
var loadTodos = function() {
$.ajax({
url: "/graphql?query={todoList{id,text,done}}"
}).done(function(data) {
console.log(data);
var dataParsed = JSON.parse(data);
var todos = dataParsed.data.todoList;
if (!todos.length) {
$('.todo-list-container').append('<p>There are no tasks for you today</p>');
}
$.each(todos, function(i, v) {
var doneHtml = '<input id="' + v.id + '" type="checkbox"' + (v.done ? ' checked="checked"' : '') + '>';
var labelHtml = '<label for="' + v.id + '">' + doneHtml + v.text + '</label>';
var itemHtml = '<div class="todo-item">' + labelHtml + '</div>';
$('.todo-list-container').append(itemHtml);
});
});
};
$(document).ready(function() {
loadTodos();
});
|
var loadTodos = function() {
$.ajax({
url: "/graphql?query={todoList{id,text,done}}",
context: document.body
}).done(function(data) {
console.log(data);
var dataParsed = JSON.parse(data);
var todos = dataParsed.data.todoList;
if (!$('.todo-list').length) {
$(this).append('<div class="todo-list"></div>');
}
if (!todos.length) {
$(this).append('<p>There are no tasks for you today</p>');
}
$.each(todos, function(i, v) {
var doneHtml = '<input id="' + v.id + '" type="checkbox"' + (v.done ? ' checked="checked"' : '') + '>';
var labelHtml = '<label for="' + v.id + '">' + doneHtml + v.text + '</label>';
var itemHtml = '<div class="todo-item">' + labelHtml + '</div>';
$('.todo-list').append(itemHtml);
});
});
};
$(document).ready(function() {
loadTodos();
});
|
Change version number (v2.2 -> v2.2.1)
|
from distutils.core import setup, Extension
setup(name='python-pytun',
author='montag451',
author_email='montag451 at laposte.net',
maintainer='montag451',
maintainer_email='montag451 at laposte.net',
url='https://github.com/montag451/pytun',
description='Linux TUN/TAP wrapper for Python',
long_description=open('README.rst').read(),
version='2.2.1',
ext_modules=[Extension('pytun', ['pytun.c'])],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX :: Linux',
'Programming Language :: C',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: System :: Networking'])
|
from distutils.core import setup, Extension
setup(name='python-pytun',
author='montag451',
author_email='montag451 at laposte.net',
maintainer='montag451',
maintainer_email='montag451 at laposte.net',
url='https://github.com/montag451/pytun',
description='Linux TUN/TAP wrapper for Python',
long_description=open('README.rst').read(),
version='2.2',
ext_modules=[Extension('pytun', ['pytun.c'])],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX :: Linux',
'Programming Language :: C',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: System :: Networking'])
|
Write out tgif package if run.
|
#!/usr/bin/env php
<?php
// vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
/**
* Generate a config file that generates a {@link global_version} based on
* the subversion version and it into the file specified by $1.
*
* This is done using the
* {@link http://svnbook.red-bean.com/en/1.1/re57.html svnversion} command.
*
* @package tgiframework
* @subpackage bootstrap
* @copyright 2009 terry chay <tychay@php.net
*/
$latest_version = max(explode(':',exec('svnversion -n'))); //sometimes you get back a range...
$data = sprintf('<?php /** @package tgiframework */ return array(\'global_version\'=>%d); ?>',$latest_version);
/**
* Bootstrap tgif_file for writing
*/
include_once(dirname(dirname(__FILE__)).'/class/tgif/file.php');
tgif_file::put_contents($_SERVER['argv'][1], $data);
?>
|
#!/usr/bin/env php
<?php
// vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
/**
* Generate a config file that generates a {@link global_version} based on
* the subversion version and it into the file specified by $1.
*
* This is done using the
* {@link http://svnbook.red-bean.com/en/1.1/re57.html svnversion} command.
*
* @package tgiframework
* @subpackage bootstrap
* @copyright 2009 terry chay <tychay@php.net
*/
$latest_version = max(explode(':',exec('svnversion -n'))); //sometimes you get back a range...
$data = sprintf('<?php return array(\'global_version\'=>%d); ?>',$latest_version);
/**
* Bootstrap tgif_file for writing
*/
include_once(dirname(dirname(__FILE__)).'/class/tgif/file.php');
tgif_file::put_contents($_SERVER['argv'][1], $data);
?>
|
Move badge instance list beneath 'badges' url
|
from __future__ import unicode_literals
from django.conf.urls import patterns, url
from . import views
from django.contrib.admin.views.decorators import staff_member_required
urlpatterns = patterns(
"",
url(r"^hello/$", "badgekit_webhooks.views.hello", name="badgekit_webhooks_hello"),
url(r"^issued/$", "badgekit_webhooks.views.badge_issued_hook",
name="badge_issued_hook"),
url(r"^claim/([-A-Za-z0-9_]+)/$", 'badgekit_webhooks.views.claim_page'),
url(r"^claim/([-A-Za-z0-9_]+)/email/(html|text)$", 'badgekit_webhooks.views.show_claim_email',
name="show_claim_email"),
url(r"^issue/$", staff_member_required(views.SendClaimCodeView.as_view()),
name="badge_issue_form"),
url(r"^claimcode/([-A-Za-z.0-9_]+)/$",
views.ClaimCodeClaimView.as_view(), name='claimcode_claim'),
url(r"^badges/$", "badgekit_webhooks.views.list_badges_view", name="badges_list"),
url(r"^badges/([-A-Za-z.0-9_]+)/instances/$", staff_member_required(views.badge_instance_list),
name="badge_instance_list"),
)
|
from __future__ import unicode_literals
from django.conf.urls import patterns, url
from . import views
from django.contrib.admin.views.decorators import staff_member_required
urlpatterns = patterns(
"",
url(r"^hello/$", "badgekit_webhooks.views.hello", name="badgekit_webhooks_hello"),
url(r"^issued/$", "badgekit_webhooks.views.badge_issued_hook",
name="badge_issued_hook"),
url(r"^instances/([-A-Za-z.0-9_]+)/$", staff_member_required(views.badge_instance_list),
name="badge_instance_list"),
url(r"^claim/([-A-Za-z0-9_]+)/$", 'badgekit_webhooks.views.claim_page'),
url(r"^claim/([-A-Za-z0-9_]+)/email/(html|text)$", 'badgekit_webhooks.views.show_claim_email',
name="show_claim_email"),
url(r"^issue/$", staff_member_required(views.SendClaimCodeView.as_view()),
name="badge_issue_form"),
url(r"^claimcode/([-A-Za-z.0-9_]+)/$",
views.ClaimCodeClaimView.as_view(), name='claimcode_claim'),
url(r"^badges/$", "badgekit_webhooks.views.list_badges_view", name="badges_list"),
)
|
Switch to UTF-8 encoding of file to reflect contributor's name correctly
|
function addslashes (str) {
// http://kevin.vanzonneveld.net
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: Ates Goral (http://magnetiq.com)
// + improved by: marrtins
// + improved by: Nate
// + improved by: Onno Marsman
// + input by: Denny Wardhana
// + improved by: Brett Zamir (http://brett-zamir.me)
// + improved by: Oskar Larsson Högfeldt (http://oskar-lh.name/)
// * example 1: addslashes("kevin's birthday");
// * returns 1: 'kevin\'s birthday'
return (str+'').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
}
|
function addslashes (str) {
// http://kevin.vanzonneveld.net
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: Ates Goral (http://magnetiq.com)
// + improved by: marrtins
// + improved by: Nate
// + improved by: Onno Marsman
// + input by: Denny Wardhana
// + improved by: Brett Zamir (http://brett-zamir.me)
// + improved by: Oskar Larsson Hgfeldt (http://oskar-lh.name/)
// * example 1: addslashes("kevin's birthday");
// * returns 1: 'kevin\'s birthday'
return (str+'').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
}
|
Release: Copy created MSI to dedicated folder.
* The "dist" folder is erased each time and we determine the result
name from being the only MSI file.
|
# Copyright 2017, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# 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.
#
""" Release: Create Windows MSI files for Nuitka
"""
import os
import shutil
from nuitka.tools.Basics import goHome
from nuitka.tools.release.MSI import createMSIPackage
def main():
goHome()
msi_filename = createMSIPackage()
if not os.path.exists("msi"):
os.makedirs("msi")
shutil.move(msi_filename, "msi")
if __name__ == "__main__":
main()
|
# Copyright 2017, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# 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.
#
""" Release: Create Windows MSI files for Nuitka
"""
from nuitka.tools.release.MSI import createMSIPackage
def main():
createMSIPackage()
if __name__ == "__main__":
main()
|
Allow more time for jasmine to start up in tests
|
import sys
from subprocess import Popen, PIPE
from time import sleep
import requests
def get_with_retries(url):
n = 0
while True:
try:
return requests.get(url)
except requests.ConnectionError:
if n < 20:
n += 1
sleep(0.1)
else:
raise
def test_standalone_serves_html():
process = Popen([sys.executable, '-c', 'from jasmine.entry_points import standalone; standalone()', '--config', 'test/fixture_files/jasmine.yml'])
try:
req = get_with_retries('http://localhost:8888/')
assert req.status_code == 200
assert 'main.js' in req.text
assert 'main.css' in req.text
assert '__spec__/someSpec.js' in req.text
finally:
process.terminate()
def test_ci():
process = Popen([sys.executable, '-c', 'from jasmine.entry_points import continuous_integration; continuous_integration()', '--config', 'test/fixture_files/jasmine.yml'], stdout=PIPE)
output = process.communicate()[0]
process.wait()
assert process.returncode == 0
assert '1 specs, 0 failed' in str(output)
|
import sys
from subprocess import Popen, PIPE
from time import sleep
import requests
def get_with_retries(url):
n = 0
while True:
try:
return requests.get(url)
except requests.ConnectionError:
if n < 5:
n += 1
sleep(0.1)
else:
raise
def test_standalone_serves_html():
process = Popen([sys.executable, '-c', 'from jasmine.entry_points import standalone; standalone()', '--config', 'test/fixture_files/jasmine.yml'])
try:
req = get_with_retries('http://localhost:8888/')
assert req.status_code == 200
assert 'main.js' in req.text
assert 'main.css' in req.text
assert '__spec__/someSpec.js' in req.text
finally:
process.terminate()
def test_ci():
process = Popen([sys.executable, '-c', 'from jasmine.entry_points import continuous_integration; continuous_integration()', '--config', 'test/fixture_files/jasmine.yml'], stdout=PIPE)
output = process.communicate()[0]
process.wait()
assert process.returncode == 0
assert '1 specs, 0 failed' in str(output)
|
Fix issue in special_entity_handler function
|
import re
RE_SPECIAL_ENTITY = re.compile('&#(1[2-6][0-9]);')
def smart_str(value, encoding='utf-8'):
"""
Normalize unicode/byte string to byte string.
"""
if isinstance(value, unicode):
value = value.encode(encoding)
return value
def smart_unicode(value, encoding='utf-8'):
"""
Normalize unicode/btye string to unicode string.
"""
if not isinstance(value, unicode):
value = value.decode(encoding)
return value
def special_entity_handler(match):
num = int(match.group(1))
if 128 <= num <= 160:
try:
return '&#%d;' % ord(chr(num).decode('cp1252'))
except UnicodeDecodeError:
return match.group(0)
else:
return match.group(0)
def fix_special_entities(body):
return RE_SPECIAL_ENTITY.sub(special_entity_handler, body)
|
import re
RE_SPECIAL_ENTITY = re.compile('&#(1[2-6][0-9]);')
def smart_str(value, encoding='utf-8'):
"""
Normalize unicode/byte string to byte string.
"""
if isinstance(value, unicode):
value = value.encode(encoding)
return value
def smart_unicode(value, encoding='utf-8'):
"""
Normalize unicode/btye string to unicode string.
"""
if not isinstance(value, unicode):
value = value.decode(encoding)
return value
def special_entity_handler(match):
num = int(match.group(1))
if 128 <= num <= 160:
return '&#%d;' % ord(chr(num).decode('cp1252'))
else:
return match.group(0)
def fix_special_entities(body):
return RE_SPECIAL_ENTITY.sub(special_entity_handler, body)
|
Update format of wave file generator.
|
#!/usr/bin/env python
import struct
wavelist = []
for s in range(12):
wave = {'method': 'POST'}
wave['url'] = 'http://localhost:3520/scenes/{0}/_load'.format(s + 1)
wave['name'] = 'Scene {0:02}'.format(s + 1)
wave['data'] = ''
wavelist.append(wave)
for wave in wavelist:
reqdata = '\n'.join((wave['method'], wave['url'], wave['data']))
reqlen = len(reqdata)
if reqlen % 2 == 1:
reqdata += '\n'
reqlen += 1
filelen = 36 + 8 + reqlen
riffchunk = struct.pack('<4sL4s', 'RIFF'.encode(), filelen, 'WAVE'.encode())
fmtchunk = struct.pack('<4sL2H2L2H', 'fmt '.encode(), 16, 1, 1, 22050, 44100, 2, 16)
datachunk = struct.pack('<4sL', 'data'.encode(), 0)
reqchunk = struct.pack('<4sL', 'req '.encode(), reqlen) + reqdata.encode()
with open(wave['name'] + '.wav', 'wb') as f:
f.write(riffchunk + fmtchunk + datachunk + reqchunk)
|
#!/usr/bin/env python
wavelist = []
for p in range(48):
for s in range(24):
wave = {'method': 'PUT', 'url': 'http://localhost:3520/scenes/_current'}
wave['name'] = 'P{0:02}-S{1:02}'.format(p + 1, s + 1)
wave['data'] = {'id': p * 24 + s}
wavelist.append(wave)
import json
import struct
for wave in wavelist:
reqdata = '\n'.join((wave['method'], wave['url'], json.dumps(wave['data'])))
reqlen = len(reqdata)
if reqlen % 2 == 1:
reqdata += '\n'
reqlen += 1
filelen = 36 + 8 + reqlen
riffchunk = struct.pack('<4sL4s', 'RIFF'.encode(), filelen, 'WAVE'.encode())
fmtchunk = struct.pack('<4sL2H2L2H', 'fmt '.encode(), 16, 1, 1, 22050, 44100, 2, 16)
datachunk = struct.pack('<4sL', 'data'.encode(), 0)
reqchunk = struct.pack('<4sL', 'req '.encode(), reqlen) + reqdata.encode()
with open(wave['name'] + '.wav', 'wb') as f:
f.write(riffchunk + fmtchunk + datachunk + reqchunk)
|
Remove redundant index (from unique constraint)
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateNewsPosts extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('news_posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('version')->nullable();
$table->string('slug')->unique();
$table->string('hash')->unique()->nullable();
$table->string('tumblr_id')->nullable();
$table->text('page')->nullable();
$table->timestampsTz();
$table->timestampTz('published_at')->nullable();
$table->index('published_at');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('news_posts');
}
}
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateNewsPosts extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('news_posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('version')->nullable();
$table->string('slug')->unique();
$table->string('hash')->unique()->nullable();
$table->string('tumblr_id')->nullable();
$table->text('page')->nullable();
$table->timestampsTz();
$table->timestampTz('published_at')->nullable();
$table->index('slug');
$table->index('published_at');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('news_posts');
}
}
|
Fix typo in test string for constructor
|
<?php
namespace FullyBaked\Pslackr\Messages;
use PHPUnit_Framework_TestCase;
use Exception;
class CustomMessageTest extends PHPUnit_Framework_TestCase
{
public function testConstructorSetsTextProperty()
{
$text = 'This is a test message';
$relection = new \ReflectionClass('FullyBaked\Pslackr\Messages\CustomMessage');
$property = $relection->getProperty('text');
$property->setAccessible(true);
$message = $this->getMockBuilder('FullyBaked\Pslackr\Messages\CustomMessage')
->setConstructorArgs([$text])
->getMock();
$this->assertEquals($text, $property->getValue($message));
}
}
|
<?php
namespace FullyBaked\Pslackr\Messages;
use PHPUnit_Framework_TestCase;
use Exception;
class CustomMessageTest extends PHPUnit_Framework_TestCase
{
public function testConstructorSetsTextProperty()
{
$text = 'This is as test message';
$relection = new \ReflectionClass('FullyBaked\Pslackr\Messages\CustomMessage');
$property = $relection->getProperty('text');
$property->setAccessible(true);
$message = $this->getMockBuilder('FullyBaked\Pslackr\Messages\CustomMessage')
->setConstructorArgs([$text])
->getMock();
$this->assertEquals($text, $property->getValue($message));
}
}
|
Test that null values are also stored
|
describe("Almacen", function() {
it("should set data in the localStorage", function() {
almacen.local.set("string", "hello");
almacen.local.set("number", 23);
almacen.local.set("boolean", true);
almacen.local.set("array", [1,2,3,4,5,6]);
almacen.local.set("object", { "foo": "bar" });
almacen.local.set("null", null);
expect(almacen.local.has("date")).to.equal(false);
expect(almacen.local.has("string")).to.equal(true);
expect(almacen.local.has("number")).to.equal(true);
expect(almacen.local.has("boolean")).to.equal(true);
expect(almacen.local.has("array")).to.equal(true);
expect(almacen.local.has("object")).to.equal(true);
expect(almacen.local.has("null")).to.equal(true);
expect(almacen.local.get("string")).to.equal("hello");
expect(almacen.local.get("number")).to.equal(23);
expect(almacen.local.get("boolean")).to.equal(true);
expect(almacen.local.get("array")).to.have.property("length").to.equal(6);
expect(almacen.local.get("object")).to.have.property("foo").to.equal("bar");
expect(almacen.local.get("null")).to.be.null;
});
});
|
describe("Almacen", function() {
it("should set data in the localStorage", function() {
almacen.local.set("string", "hello");
almacen.local.set("number", 23);
almacen.local.set("boolean", true);
almacen.local.set("array", [1,2,3,4,5,6]);
almacen.local.set("object", { "foo": "bar" });
expect(almacen.local.has("date")).to.equal(false);
expect(almacen.local.has("string")).to.equal(true);
expect(almacen.local.has("number")).to.equal(true);
expect(almacen.local.has("boolean")).to.equal(true);
expect(almacen.local.has("array")).to.equal(true);
expect(almacen.local.has("object")).to.equal(true);
expect(almacen.local.get("string")).to.equal("hello");
expect(almacen.local.get("number")).to.equal(23);
expect(almacen.local.get("boolean")).to.equal(true);
expect(almacen.local.get("array")).to.have.property("length").to.equal(6);
expect(almacen.local.get("object")).to.have.property("foo").to.equal("bar");
});
});
|
Delete unused module local constants.
|
import collections
from data import crossword, warehouse
from puzzle.problems.crossword import _base_crossword_problem
class CrosswordProblem(_base_crossword_problem._BaseCrosswordProblem):
@staticmethod
def score(lines):
return _base_crossword_problem.score(lines)
def _solve(self):
clue = ''.join(self.lines)
clue_keywords = crossword.clue_keywords(clue)
cursor = warehouse.get('/phrases/crossword/cursor')
results = crossword.query(cursor, clue)
if not results:
return {}
max_frequency = max([f for _, f, _ in results])
ranked = []
for (solution, frequency, keywords) in results:
score = 0.0
for keyword in clue_keywords:
# Increase score by how often the keyword appeared in other clues.
score += keywords[keyword] / frequency
# Normalize score based on how many keywords were considered.
score /= len(clue_keywords)
rank = score * frequency / max_frequency
if rank:
ranked.append((solution, rank))
return collections.OrderedDict(
sorted(ranked, key=lambda x: x[1], reverse=True))
|
import collections
import re
from data import crossword, warehouse
from puzzle.problems.crossword import _base_crossword_problem
_CROSSWORD_REGEX = re.compile(r'^.*\(([\d\s,|]+)\)$')
_INTS = re.compile(r'(\d+)')
class CrosswordProblem(_base_crossword_problem._BaseCrosswordProblem):
@staticmethod
def score(lines):
return _base_crossword_problem.score(lines)
def _solve(self):
clue = ''.join(self.lines)
clue_keywords = crossword.clue_keywords(clue)
cursor = warehouse.get('/phrases/crossword/cursor')
results = crossword.query(cursor, clue)
if not results:
return {}
max_frequency = max([f for _, f, _ in results])
ranked = []
for (solution, frequency, keywords) in results:
score = 0.0
for keyword in clue_keywords:
# Increase score by how often the keyword appeared in other clues.
score += keywords[keyword] / frequency
# Normalize score based on how many keywords were considered.
score /= len(clue_keywords)
rank = score * frequency / max_frequency
if rank:
ranked.append((solution, rank))
return collections.OrderedDict(
sorted(ranked, key=lambda x: x[1], reverse=True))
|
Use RFC822 date strings for date parser unit tests
|
// Copyright 2015 NF Design UG (haftungsbeschraenkt). All rights reserved.
// Use of this source code is governed by the Apache License v2.0
// which can be found in the LICENSE file.
package imapclient
import (
"testing"
"time"
)
const utilsTestLogPrefix = "date_test.go: "
func TestDateParse(t *testing.T) {
var (
testdate string = "Mon, 02 Jan 2005 15:04:06 -0700 (MST)"
timet time.Time
err error
)
timet, err = parseDate(testdate)
if err != nil {
t.Fatal("Error parsing date: " + err.Error())
}
if timet.Format(time.RFC822) != "02 Jan 05 15:04 MST" {
t.Fatal("Error parsing date, got: " + timet.Format(time.RFC822))
}
testdate = "2 Jan 05 15:04 CET"
timet, err = parseDate(testdate)
if err != nil {
t.Fatal("Error parsing date: " + err.Error())
}
if timet.Format(time.RFC822) != "02 Jan 05 15:04 CET" {
t.Fatal("Error parsing date, got: " + timet.Format(time.RFC822))
}
}
|
// Copyright 2015 NF Design UG (haftungsbeschraenkt). All rights reserved.
// Use of this source code is governed by the Apache License v2.0
// which can be found in the LICENSE file.
package imapclient
import (
"testing"
"time"
)
const utilsTestLogPrefix = "date_test.go: "
func TestDateParse(t *testing.T) {
var (
testdate string = "Mon, 02 Jan 2005 15:04:06 -0700 (MST)"
timet time.Time
err error
)
timet, err = parseDate(testdate)
if err != nil {
t.Fatal("Error parsing date: " + err.Error())
}
if timet.Unix() != 1104703446 {
t.Fatal("Time parsed wrong")
}
testdate = "2 Jan 05 15:04 CET"
timet, err = parseDate(testdate)
if err != nil {
t.Fatal("Error parsing date: " + err.Error())
}
if timet.Unix() != 1104674640 {
t.Fatal("Time parsed wrong")
}
}
|
Update comments for form clear button.
|
/* ==========================================================================
Initialize Chosen.js
========================================================================== */
$(".chosen-select").chosen({
width: '100%',
no_results_text: "Oops, nothing found!"
});
/* ==========================================================================
Clear form button
- Clear checkboxes and selects
- Clear Chosen.js elements
- Clear jquery.custom-input elements
========================================================================== */
$('.js-form_clear').on('click', function() {
var $this = $(this),
$form = $this.parents('form');
// Clear checkboxes
$form.find('[type="checkbox"]')
.removeAttr('checked');
// Clear select options
$form.find('select option')
.removeAttr('selected');
$form.find('select option:first')
.attr('selected', true);
// Clear .custom-input elements
$form.find('.custom-input').trigger('updateState');
// Clear Chosen.js elements
$form.find('.chosen-select')
.val('')
.trigger("chosen:updated");
});
|
/* ==========================================================================
Initialize Chosen.js
========================================================================== */
$(".chosen-select").chosen({
width: '100%',
no_results_text: "Oops, nothing found!"
});
// Reset buttons sould also reset Chosen.js elements
$('.js-form_clear').on('click', function() {
var $this = $(this),
$form = $this.parents('form');
// Reset checkboxes
$form.find('[type="checkbox"]')
.removeAttr('checked');
// Reset select options
$form.find('select option')
.removeAttr('selected');
$form.find('select option:first')
.attr('selected', true);
// Reset .custom-input elements
$form.find('.custom-input').trigger('updateState');
// Reset Chosen.js elements
$form.find('.chosen-select')
.val('')
.trigger("chosen:updated");
});
|
Add auto abuse reports after multiple downvotes
|
// Abuse reports
//
'use strict';
const Mongoose = require('mongoose');
const Schema = Mongoose.Schema;
module.exports = function (N, collectionName) {
let AbuseReport = new Schema({
// _id of reported content
src: Schema.ObjectId,
// N.shared.content_type (FORUM_POST, BLOG_ENTRY, ...)
type: Number,
// Report text
text: String,
// Flag defining whether this report was created automatically
auto_reported: Boolean,
// Parser options
params_ref: Schema.ObjectId,
// User _id
from: Schema.ObjectId
}, {
versionKey: false
});
// Duplicate check for auto-created abuse reports
AbuseReport.index({ src: 1, auto_reported: 1 }, { sparse: true });
N.wire.on('init:models', function emit_init_AbuseReport() {
return N.wire.emit('init:models.' + collectionName, AbuseReport);
});
N.wire.on('init:models.' + collectionName, function init_model_AbuseReport(schema) {
N.models[collectionName] = Mongoose.model(collectionName, schema);
});
};
|
// Abuse reports
//
'use strict';
const Mongoose = require('mongoose');
const Schema = Mongoose.Schema;
module.exports = function (N, collectionName) {
let AbuseReport = new Schema({
// _id of reported content
src: Schema.ObjectId,
// N.shared.content_type (FORUM_POST, BLOG_ENTRY, ...)
type: Number,
// Report text
text: String,
// Parser options
params_ref: Schema.ObjectId,
// User _id
from: Schema.ObjectId
}, {
versionKey: false
});
N.wire.on('init:models', function emit_init_AbuseReport() {
return N.wire.emit('init:models.' + collectionName, AbuseReport);
});
N.wire.on('init:models.' + collectionName, function init_model_AbuseReport(schema) {
N.models[collectionName] = Mongoose.model(collectionName, schema);
});
};
|
Fix subprocess on Python 2.6
|
from __future__ import absolute_import
from subprocess import *
def check_output(*popenargs, **kwargs):
r"""Run command with arguments and return its output as a byte
string.
If the exit code was non-zero it raises a CalledProcessError. The
CalledProcessError object will have the return code in the
returncode
attribute and output in the output attribute.
The arguments are the same as for the Popen constructor. Example::
>>> check_output(["ls", "-l", "/dev/null"])
'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
The stdout argument is not allowed as it is used internally.
To capture standard error in the result, use stderr=STDOUT.::
>>> check_output(["/bin/sh", "-c",
... "ls -l non_existent_file ; exit 0"],
... stderr=STDOUT)
'ls: non_existent_file: No such file or directory\n'
"""
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
process = Popen(stdout=PIPE, *popenargs, **kwargs)
output, unused_err = process.communicate()
retcode = process.poll()
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
raise CalledProcessError(retcode, cmd)
return output
|
from __future__ import absolute_import
from subprocess import *
def check_output(*popenargs, **kwargs):
r"""Run command with arguments and return its output as a byte
string.
If the exit code was non-zero it raises a CalledProcessError. The
CalledProcessError object will have the return code in the
returncode
attribute and output in the output attribute.
The arguments are the same as for the Popen constructor. Example::
>>> check_output(["ls", "-l", "/dev/null"])
'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
The stdout argument is not allowed as it is used internally.
To capture standard error in the result, use stderr=STDOUT.::
>>> check_output(["/bin/sh", "-c",
... "ls -l non_existent_file ; exit 0"],
... stderr=STDOUT)
'ls: non_existent_file: No such file or directory\n'
"""
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
process = Popen(stdout=PIPE, *popenargs, **kwargs)
output, unused_err = process.communicate()
retcode = process.poll()
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
raise subprocess.CalledProcessError(retcode, cmd)
return output
|
Replace subcategory__ prefix to endpoint response field names.
|
from .models import Star
from employees.models import Employee
from rest_framework import serializers
class EmployeeSimpleSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
fields = ('pk', 'username', 'first_name', 'last_name')
class StarSerializer(serializers.ModelSerializer):
class Meta:
model = Star
fields = ('pk', 'date', 'text', 'from_user', 'to_user', 'category', 'subcategory')
class StarSmallSerializer(serializers.ModelSerializer):
from_user = EmployeeSimpleSerializer()
class Meta:
model = Star
depth = 1
fields = ('pk', 'date', 'text', 'category', 'from_user')
class StarSwaggerSerializer(serializers.ModelSerializer):
class Meta:
model = Star
fields = ('pk', 'category', 'subcategory', 'text')
class StarEmployeesSubcategoriesSerializer(serializers.Serializer):
pk = serializers.IntegerField(source='subcategory__pk')
name = serializers.CharField(max_length=100, source='subcategory__name')
num_stars = serializers.IntegerField()
class StarTopEmployeeLists(serializers.Serializer):
to_user__id = serializers.IntegerField()
to_user__username = serializers.CharField(max_length=100)
to_user__first_name = serializers.CharField(max_length=100)
to_user__last_name = serializers.CharField(max_length=100)
num_stars = serializers.IntegerField()
|
from .models import Star
from employees.models import Employee
from rest_framework import serializers
class EmployeeSimpleSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
fields = ('pk', 'username', 'first_name', 'last_name')
class StarSerializer(serializers.ModelSerializer):
class Meta:
model = Star
fields = ('pk', 'date', 'text', 'from_user', 'to_user', 'category', 'subcategory')
class StarSmallSerializer(serializers.ModelSerializer):
from_user = EmployeeSimpleSerializer()
class Meta:
model = Star
depth = 1
fields = ('pk', 'date', 'text', 'category', 'from_user')
class StarSwaggerSerializer(serializers.ModelSerializer):
class Meta:
model = Star
fields = ('pk', 'category', 'subcategory', 'text')
class StarEmployeesSubcategoriesSerializer(serializers.Serializer):
subcategory__pk = serializers.IntegerField()
subcategory__name = serializers.CharField(max_length=100)
num_stars = serializers.IntegerField()
class StarTopEmployeeLists(serializers.Serializer):
to_user__id = serializers.IntegerField()
to_user__username = serializers.CharField(max_length=100)
to_user__first_name = serializers.CharField(max_length=100)
to_user__last_name = serializers.CharField(max_length=100)
num_stars = serializers.IntegerField()
|
Make it clear which makeCouch we're using
|
var vm = require('vm');
var fs = require('fs');
// this is the context in which all of our test code will run
var initSandbox = {
console: console,
require: require,
setTimeout: setTimeout,
clearTimeout: clearTimeout,
Buffer: Buffer
};
var context = vm.createContext(initSandbox);
if(!process.argv[2]) {
console.log('No makeCouch.js specified');
process.exit(1);
}
else {
console.log('Using ' + process.argv[2]);
}
fs.readFile('../browser/qunit/qunit/qunit.js', 'utf-8', function(err, data) {
if(err) {
throw err;
}
vm.runInContext(data, context);
fs.readFile('../../sag.js', 'utf-8', function(err, data) {
if(err) {
throw err;
}
vm.runInContext(data, context);
fs.readFile(process.argv[2], 'utf-8', function(err, data) {
vm.runInContext(data, context);
fs.readFile('../sag-tests.js', 'utf-8', function(err, data) {
if(err) {
throw err;
}
vm.runInContext(data, context);
});
});
});
});
|
var vm = require('vm');
var fs = require('fs');
// this is the context in which all of our test code will run
var initSandbox = {
console: console,
require: require,
setTimeout: setTimeout,
clearTimeout: clearTimeout,
Buffer: Buffer
};
var context = vm.createContext(initSandbox);
if(!process.argv[2]) {
console.log('No makeCouch.js specified');
process.exit(1);
}
fs.readFile('../browser/qunit/qunit/qunit.js', 'utf-8', function(err, data) {
if(err) {
throw err;
}
vm.runInContext(data, context);
fs.readFile('../../sag.js', 'utf-8', function(err, data) {
if(err) {
throw err;
}
vm.runInContext(data, context);
fs.readFile(process.argv[2], 'utf-8', function(err, data) {
vm.runInContext(data, context);
fs.readFile('../sag-tests.js', 'utf-8', function(err, data) {
if(err) {
throw err;
}
vm.runInContext(data, context);
});
});
});
});
|
Use promise.map to build requests
Requires moving buildRequest into inner fn scope
|
var Promise = require('bluebird')
var request = require('got')
var extend = require('xtend')
var BASE_URL = 'http://www.broadbandmap.gov/broadbandmap/broadband/jun2014/'
module.exports = function broadbandMap (lat, long, options) {
options = extend({
types: ['wireline', 'wireless']
}, options || {})
return Promise.map(options.type, buildRequest)
.spread(function (res1, res2) {
var results = []
if (res1 && res1.body) results.push(JSON.parse(res1.body).Results)
if (res2 && res2.body) results.push(JSON.parse(res2.body).Results)
return results
})
.catch(function (err) {
throw err
})
function buildRequest (type) {
return request.get(BASE_URL + type + '?latitude=' +
lat + '&longitude=' + long + '&format=json')
}
}
|
var Promise = require('bluebird')
var request = require('got')
var extend = require('xtend')
var BASE_URL = 'http://www.broadbandmap.gov/broadbandmap/broadband/jun2014/'
module.exports = function broadbandMap (lat, long, options) {
options = extend({
types: ['wireline', 'wireless']
}, options || {})
var promises = []
options.types.forEach(function (type) {
promises.push(buildRequest(lat, long, type))
})
return Promise.all(promises)
.spread(function (res1, res2) {
var results = []
if (res1 && res1.body) results.push(JSON.parse(res1.body).Results)
if (res2 && res2.body) results.push(JSON.parse(res2.body).Results)
return results
})
.catch(function (err) {
throw err
})
}
function buildRequest (lat, long, type) {
return request.get(BASE_URL + type + '?latitude=' +
lat + '&longitude=' + long + '&format=json')
}
|
Fix group id query case
|
import graphene
from falmer.schema.schema import DjangoConnectionField
from falmer.studentgroups.types import StudentGroup
from . import types
from . import models
class Query(graphene.ObjectType):
all_groups = DjangoConnectionField(StudentGroup)
group = graphene.Field(types.StudentGroup, group_id=graphene.Int())
def resolve_all_groups(self, info):
qs = models.StudentGroup.objects \
.order_by('name') \
.select_related('msl_group', 'logo')
return qs
def resolve_group(self, info, **kwargs):
group_id = kwargs.get('group_id')
return models.StudentGroup.objects \
.select_related('logo').get(pk=group_id)
|
import graphene
from falmer.schema.schema import DjangoConnectionField
from falmer.studentgroups.types import StudentGroup
from . import types
from . import models
class Query(graphene.ObjectType):
all_groups = DjangoConnectionField(StudentGroup)
group = graphene.Field(types.StudentGroup, groupId=graphene.Int())
def resolve_all_groups(self, info):
qs = models.StudentGroup.objects \
.order_by('name') \
.select_related('msl_group', 'logo')
return qs
def resolve_group(self, info, **kwargs):
group_id = kwargs.get('group_id')
return models.StudentGroup.objects \
.select_related('logo').get(pk=group_id)
|
Add explanatory comments regarding odd Jenkins behaviour
|
<?php
use Doctrine\Common\Annotations\AnnotationRegistry;
/**
* Explicitly include some dependencies that otherwise result in 'class not found'
* errors when running on Jenkins.
*
* Works on local dev environment. Works on live. Works on Travis. Doesn't work on Jenkins.
*/
if (getenv('IS_JENKINS') === 'true') {
$jenkinsNeedsThese = array(
'Stripe' => '/stripe/stripe-php/lib/Stripe.php',
'ExpressiveDate' => '/jasonlewis/expressive-date/src/ExpressiveDate.php'
);
foreach ($jenkinsNeedsThese as $class => $path) {
if (!class_exists($class)) {
require_once(realpath(__DIR__ . '/../vendor' . $path));
}
}
}
$loader = require __DIR__.'/../vendor/autoload.php';
// intl
if (!function_exists('intl_get_error_code')) {
require_once __DIR__.'/../vendor/symfony/symfony/src/Symfony/Component/Locale/Resources/stubs/functions.php';
$loader->add('', __DIR__.'/../vendor/symfony/symfony/src/Symfony/Component/Locale/Resources/stubs');
}
AnnotationRegistry::registerLoader(array($loader, 'loadClass'));
return $loader;
|
<?php
use Doctrine\Common\Annotations\AnnotationRegistry;
if (getenv('IS_JENKINS') === 'true') {
$jenkinsNeedsThese = array(
'Stripe' => '/stripe/stripe-php/lib/Stripe.php',
'ExpressiveDate' => '/jasonlewis/expressive-date/src/ExpressiveDate.php'
);
foreach ($jenkinsNeedsThese as $class => $path) {
if (!class_exists($class)) {
require_once(realpath(__DIR__ . '/../vendor' . $path));
}
}
}
$loader = require __DIR__.'/../vendor/autoload.php';
// intl
if (!function_exists('intl_get_error_code')) {
require_once __DIR__.'/../vendor/symfony/symfony/src/Symfony/Component/Locale/Resources/stubs/functions.php';
$loader->add('', __DIR__.'/../vendor/symfony/symfony/src/Symfony/Component/Locale/Resources/stubs');
}
AnnotationRegistry::registerLoader(array($loader, 'loadClass'));
return $loader;
|
Fix issue with https and Google analytics tracking code.
Use `str::after($string, $after);` to always get the (sub)domain without `http://` or `https://`.
|
<?php ///////////////////////////////////////////////////////
// ----------------------------------------------------------
// SNIPPET
// ----------------------------------------------------------
// Google analytics.js
// ----------------------------------------------------------
// Enable and set analytics ID/API KEY in config.php
// ----------------------------------------------------------
/////////////////////////////////////////////////////////////
// ----------------------------------------------------------
// Google Universal Analytics
// ----------------------------------------------------------
if (c::get('google.analytics') == true && c::get('google.analytics.id') != 'TRACKING ID IS NOT SET'):
// Respect user's privacy (https://blog.j15h.nu/web-analytics-privacy/)
if ('navigator.doNotTrack' != 'yes' && 'navigator.doNotTrack' != '1' && 'navigator.msDoNotTrack' != '1'): ?>
<script>window.ga=function(){ga.q.push(arguments)};ga.q=[];ga.l=+new Date;ga('create','<?php echo c::get("google.analytics.id", "TRACKING ID IS NOT SET"); ?>','<?php echo str::after($site->url(), '://'); ?>');ga('set', 'anonymizeIp', true);ga('set', 'forceSSL', true);ga('send','pageview')</script>
<script src="https://www.google-analytics.com/analytics.js" async defer></script>
<?php endif; ?>
<?php else: ?>
<!-- NO TRACKING SET! -->
<?php endif; ?>
|
<?php ///////////////////////////////////////////////////////
// ----------------------------------------------------------
// SNIPPET
// ----------------------------------------------------------
// Google analytics.js
// ----------------------------------------------------------
// Enable and set analytics ID/API KEY in config.php
// ----------------------------------------------------------
/////////////////////////////////////////////////////////////
// ----------------------------------------------------------
// Google Universal Analytics
// ----------------------------------------------------------
if (c::get('google.analytics') == true && c::get('google.analytics.id') != 'TRACKING ID IS NOT SET'):
// Respect user's privacy (https://blog.j15h.nu/web-analytics-privacy/)
if ('navigator.doNotTrack' != 'yes' && 'navigator.doNotTrack' != '1' && 'navigator.msDoNotTrack' != '1'): ?>
<script>window.ga=function(){ga.q.push(arguments)};ga.q=[];ga.l=+new Date;ga('create','<?php echo c::get("google.analytics.id", "TRACKING ID IS NOT SET"); ?>','<?php echo str::substr($site->url(), 7); ?>');ga('set', 'anonymizeIp', true);ga('set', 'forceSSL', true);ga('send','pageview')</script>
<script src="https://www.google-analytics.com/analytics.js" async defer></script>
<?php endif; ?>
<?php else: ?>
<!-- NO TRACKING SET! -->
<?php endif; ?>
|
Change how we get course ids to avoid memory issues
|
"""
Export course metadata for all courses
"""
from django.core.management.base import BaseCommand
from xmodule.modulestore.django import modulestore
from cms.djangoapps.export_course_metadata.signals import export_course_metadata
from cms.djangoapps.export_course_metadata.tasks import export_course_metadata_task
class Command(BaseCommand):
"""
Export course metadata for all courses
"""
help = 'Export course metadata for all courses'
def handle(self, *args, **options):
"""
Execute the command
"""
export_course_metadata_for_all_courses()
def export_course_metadata_for_all_courses():
"""
Export course metadata for all courses
"""
courses = modulestore().get_course_summaries()
for course in courses:
export_course_metadata_task.delay(str(course.id))
|
"""
Export course metadata for all courses
"""
from django.core.management.base import BaseCommand
from xmodule.modulestore.django import modulestore
from cms.djangoapps.export_course_metadata.signals import export_course_metadata
from cms.djangoapps.export_course_metadata.tasks import export_course_metadata_task
class Command(BaseCommand):
"""
Export course metadata for all courses
"""
help = 'Export course metadata for all courses'
def handle(self, *args, **options):
"""
Execute the command
"""
export_course_metadata_for_all_courses()
def export_course_metadata_for_all_courses():
"""
Export course metadata for all courses
"""
module_store = modulestore()
courses = module_store.get_courses()
for course in courses:
export_course_metadata_task.delay(str(course.id))
|
Fix resource check for grouping scope
|
<?php
namespace Luminary\Services\ApiQuery\Grouping;
use Illuminate\Database\Eloquent\Model;
use Luminary\Services\ApiQuery\Eloquent\BaseScope;
class Scope extends BaseScope
{
/**
* Apply to the Query Scope
*
* @param $builder
* @param Model $model
* @return void
*/
public function apply($builder, Model $model) :void
{
$this->builder = $builder;
$this->model = $model;
$group = $this->grouping();
if(!empty($group)) {
$builder->groupBy($group);
}
}
/**
* Get the query fields
*
* @return array
*/
protected function grouping() :array
{
$resource = $this->resource();
return $this->query()->grouping($resource);
}
}
|
<?php
namespace Luminary\Services\ApiQuery\Grouping;
use Illuminate\Database\Eloquent\Model;
use Luminary\Services\ApiQuery\Eloquent\BaseScope;
class Scope extends BaseScope
{
/**
* Apply to the Query Scope
*
* @param $builder
* @param Model $model
* @return void
*/
public function apply($builder, Model $model) :void
{
$this->builder = $builder;
$this->model = $model;
$group = $this->grouping();
if(!empty($group)) {
$builder->groupBy($group);
}
}
/**
* Get the query fields
*
* @return array
*/
protected function grouping() :array
{
$resource = str_replace('_', '-', $this->resource());
return $this->query()->grouping($resource);
}
}
|
Make the step actually do something.
|
import time
from lettuce import step
from lettuce import world
from lettuce_webdriver.util import assert_true
from lettuce_webdriver.util import assert_false
import logging
log = logging.getLogger(__name__)
def wait_for_elem(browser, sel, timeout=15):
start = time.time()
elems = []
while time.time() - start < timeout:
elems = browser.find_elements_by_css_selector(sel)
if elems:
return elems
time.sleep(0.2)
return elems
@step(r'There should be an element matching \$\("(.*?)"\) within (\d+) seconds?')
def wait_for_element_by_selector(step, selector, seconds):
log.error(selector)
elems = wait_for_elem(world.browser, selector, seconds)
assert_true(step, elems)
__all__ = ['wait_for_element_by_selector']
|
from lettuce import step
from lettuce import world
from lettuce_webdriver.util import assert_true
from lettuce_webdriver.util import assert_false
import logging
log = logging.getLogger(__name__)
def wait_for_elem(browser, xpath, timeout=15):
start = time.time()
elems = []
while time.time() - start < timeout:
elems = browser.find_elements_by_css_selector(xpath)
if elems:
return elems
time.sleep(0.2)
return elems
@step(r'There should be an element matching \$\("(.*?)"\) within (\d+) seconds?')
def wait_for_element_by_selector(step, selector, seconds):
log.error(selector)
#elems = wait_for_elem(world.browser, selector, seconds)
#assert_true(step, elems)
__all__ = ['wait_for_element_by_selector']
|
Improve formatting in failfast test
|
/*
* Copyright 2016 Google 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.
*/
package com.google.android.libraries.remixer;
import com.google.android.libraries.remixer.annotation.RemixerBinder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class FailfastTest {
@Test(expected = IllegalStateException.class)
public void binderFailsFast() {
RemixerBinder.bind(this);
}
@Test(expected = IllegalStateException.class)
public void remixerAddFailsFast() {
Remixer.getInstance().addItem(new Trigger.Builder().setContext(this).setKey("key").build());
}
}
|
/*
* Copyright 2016 Google 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.
*/
package com.google.android.libraries.remixer;
import com.google.android.libraries.remixer.annotation.RemixerBinder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class FailfastTest {
@Test(expected = IllegalStateException.class)
public void binderFailsFast() {
RemixerBinder.bind(this);
}
@Test(expected = IllegalStateException.class)
public void remixerAddFailsFast() {
Remixer.getInstance().addItem(new Trigger.Builder().setContext(this).setKey("key").build());
}
}
|
Fix URI decode error breaking messages
|
module.exports = function (root, cb) {
root.addEventListener('click', (ev) => {
if (ev.altKey || ev.ctrlKey || ev.metaKey || ev.shiftKey || ev.defaultPrevented) {
return true
}
let anchor = null
for (let n = ev.target; n.parentNode; n = n.parentNode) {
if (n.nodeName === 'A') {
anchor = n
break
}
}
if (!anchor) return true
let href = anchor.getAttribute('href')
if (href.startsWith('#')) {
try {
href = decodeURIComponent(href)
} catch (e) {
// Safely ignore error because href isn't URI-encoded.
}
}
if (href) {
let isUrl
let url
try {
url = new URL(href)
isUrl = true
} catch (e) {
isUrl = false
}
if (isUrl && (url.host || url.protocol === 'magnet:')) {
cb(href, true)
} else if (href !== '#') {
cb(href, false, anchor.anchor)
}
}
ev.preventDefault()
ev.stopPropagation()
})
}
|
module.exports = function (root, cb) {
root.addEventListener('click', (ev) => {
if (ev.altKey || ev.ctrlKey || ev.metaKey || ev.shiftKey || ev.defaultPrevented) {
return true
}
let anchor = null
for (let n = ev.target; n.parentNode; n = n.parentNode) {
if (n.nodeName === 'A') {
anchor = n
break
}
}
if (!anchor) return true
let href = anchor.getAttribute('href')
try {
href = decodeURIComponent(href)
} catch (e) {
// Safely ignore error because href isn't URI-encoded.
}
if (href) {
let isUrl
let url
try {
url = new URL(href)
isUrl = true
} catch (e) {
isUrl = false
}
if (isUrl && (url.host || url.protocol === 'magnet:')) {
cb(href, true)
} else if (href !== '#') {
cb(href, false, anchor.anchor)
}
}
ev.preventDefault()
ev.stopPropagation()
})
}
|
Check game when player quits
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mafia.server.bus.events;
import com.mafia.server.bus.notify.NotifyViewState;
import com.mafia.server.model.state.Game;
import com.mafia.server.model.state.Player;
import com.mafia.server.model.state.Repository;
import javax.websocket.Session;
/**
*
* @author Just1689
*/
public class PlayerEvents {
public static void playerQuits(Session session) {
Player player = Repository.getPlayerBySession(session);
if (player != null) {
if (player.getGame() == null) {
return;
}
player.getGame().removePlayer(player);
GameEvents.checkGame(player.getGame());
}
}
public static Player makePlayer(String name, String passCode, String sessionId) {
return new Player(name, passCode, sessionId);
}
public static void joinGame(Player player, Game game) {
player.setGame(game);
game.addPlayer(player);
NotifyViewState.nofity(game);
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mafia.server.bus.events;
import com.mafia.server.bus.notify.NotifyGame;
import com.mafia.server.bus.notify.NotifyViewState;
import com.mafia.server.model.state.Game;
import com.mafia.server.model.state.Player;
import com.mafia.server.model.state.Repository;
import javax.websocket.Session;
/**
*
* @author Just1689
*/
public class PlayerEvents {
public static void playerQuits(Session session) {
Player player = Repository.getPlayerBySession(session);
if (player != null) {
player.getGame().removePlayer(player);
}
//Todo: notify?
}
public static Player makePlayer(String name, String passCode, String sessionId) {
return new Player(name, passCode, sessionId);
}
public static void joinGame(Player player, Game game) {
player.setGame(game);
game.addPlayer(player);
NotifyViewState.nofity(game);
}
}
|
Fix crash in reload task in dashboard
|
package com.rehivetech.beeeon.threading.task;
import android.content.Context;
import com.rehivetech.beeeon.controller.Controller;
import com.rehivetech.beeeon.exception.AppException;
import java.util.EnumSet;
/**
* Created by martin on 29.3.16.
*/
public class ReloadDashboardDataTask extends ReloadGateDataTask{
public ReloadDashboardDataTask(Context context, boolean forceReload, ReloadWhat what) {
super(context, forceReload, what);
}
public ReloadDashboardDataTask(Context context, boolean forceReload, EnumSet<ReloadWhat> what) {
super(context, forceReload, what);
}
@Override
public Boolean doInBackground(String... params) {
try {
if (!super.doInBackground(params[0])) {
return false;
}
} catch (AppException e) {
return false;
}
if (params.length == 1) {
return true;
}
return Controller.getInstance(mContext).getWeatherModel().reloadWeather(mContext, params[0], params[1], params[2]);
}
}
|
package com.rehivetech.beeeon.threading.task;
import android.content.Context;
import com.rehivetech.beeeon.controller.Controller;
import java.util.EnumSet;
/**
* Created by martin on 29.3.16.
*/
public class ReloadDashboardDataTask extends ReloadGateDataTask{
public ReloadDashboardDataTask(Context context, boolean forceReload, ReloadWhat what) {
super(context, forceReload, what);
}
public ReloadDashboardDataTask(Context context, boolean forceReload, EnumSet<ReloadWhat> what) {
super(context, forceReload, what);
}
@Override
public Boolean doInBackground(String... params) {
if (!super.doInBackground(params[0])) {
return false;
}
if (params.length == 1) {
return true;
}
return Controller.getInstance(mContext).getWeatherModel().reloadWeather(mContext, params[0], params[1], params[2]);
}
}
|
Add "X-Molotov-Agent" header on authentication token refresh requests.
|
chrome.webRequest.onBeforeSendHeaders.addListener(
function(details) {
details.requestHeaders.push({
name: "X-Molotov-Agent",
value: "{\"app_id\":\"electron_app\",\"app_build\":1,\"app_version_name\":\"0.9.6\",\"type\":\"desktop\",\"os\":\"\",\"os_version\":\"\",\"manufacturer\":\"\",\"serial\":\"\",\"model\":\"\",\"brand\":\"\"}"
});
return {requestHeaders: details.requestHeaders};
},
{
urls: [
"https://fapi.molotov.tv/v2/auth/login",
"https://fapi.molotov.tv/v2/auth/refresh/*"
],
types: ["xmlhttprequest"]
},
["blocking", "requestHeaders"]
);
|
chrome.webRequest.onBeforeSendHeaders.addListener(
function(details) {
details.requestHeaders.push({
name: "X-Molotov-Agent",
value: "{\"app_id\":\"electron_app\",\"app_build\":1,\"app_version_name\":\"0.9.6\",\"type\":\"desktop\",\"os\":\"\",\"os_version\":\"\",\"manufacturer\":\"\",\"serial\":\"\",\"model\":\"\",\"brand\":\"\"}"
});
return {requestHeaders: details.requestHeaders};
},
{
urls: [
"https://fapi.molotov.tv/v2/auth/login"
],
types: ["xmlhttprequest"]
},
["blocking", "requestHeaders"]
);
|
Fix spelling error for carousel image
|
app.controller('HomeController', ['$http', function($http) {
console.log('HomeController running');
var self = this;
self.dataArray = [
{
src: '../assets/images/carousel/genome.jpg'
},
{
src: '../assets/images/carousel/falkirk-wheel.jpg'
},
{
src: '../assets/images/carousel/iss.jpg'
},
{
src: '../assets/images/carousel/shark.jpg'
},
{
src: '../assets/images/carousel/snowflake.jpg'
},
{
src: '../assets/images/carousel/virus.jpg'
},
{
src: '../assets/images/carousel/rock-formation.jpg'
},
{
src: '../assets/images/carousel/circuit-board.jpg'
}
];
}]);
|
app.controller('HomeController', ['$http', function($http) {
console.log('HomeController running');
var self = this;
self.dataArray = [
{
src: '../assets/images/carousel/genome.jpg'
},
{
src: '../assets/images/carousel/falkirk-wheel.jpg'
},
{
src: '../assets/images/carousel/iss.jpg'
},
{
src: '../assets/images/carousel/shark.jpg'
},
{
src: '../assets/images/carousel/snowflake.jpg'
},
{
src: '../assets/images/carousel/virus.jpg'
},
{
src: '../assets/images/carousel/rock-formation.jpgg'
},
{
src: '../assets/images/carousel/circuit-board.jpg'
}
];
}]);
|
Fix Activity Stream category title
|
class AllHangs(object):
title = "All Hangs"
@staticmethod
def matches_hang(_):
return True
class DevtoolsHangs(object):
title = "Devtools Hangs"
@staticmethod
def matches_hang(hang):
#pylint: disable=unused-variable
stack, duration, thread, runnable, process, annotations, build_date, platform = hang
return stack is not None and any(isinstance(frame, basestring) and "devtools/" in frame
for frame, lib in stack)
class ActivityStreamHangs(object):
title = "Activity Stream Hangs"
@staticmethod
def matches_hang(hang):
#pylint: disable=unused-variable
stack, duration, thread, runnable, process, annotations, build_date, platform = hang
return stack is not None and any(isinstance(frame, basestring) and "activity-stream/" in frame
for frame, lib in stack)
def get_tracked_stats():
return [AllHangs, DevtoolsHangs, ActivityStreamHangs]
|
class AllHangs(object):
title = "All Hangs"
@staticmethod
def matches_hang(_):
return True
class DevtoolsHangs(object):
title = "Devtools Hangs"
@staticmethod
def matches_hang(hang):
#pylint: disable=unused-variable
stack, duration, thread, runnable, process, annotations, build_date, platform = hang
return stack is not None and any(isinstance(frame, basestring) and "devtools/" in frame
for frame, lib in stack)
class ActivityStreamHangs(object):
title = "Devtools Hangs"
@staticmethod
def matches_hang(hang):
#pylint: disable=unused-variable
stack, duration, thread, runnable, process, annotations, build_date, platform = hang
return stack is not None and any(isinstance(frame, basestring) and "activity-stream/" in frame
for frame, lib in stack)
def get_tracked_stats():
return [AllHangs, DevtoolsHangs, ActivityStreamHangs]
|
Add warning about root token necessity
|
from fabric.api import task, local
from buildercore import project
import utils
import sys
import logging
LOG = logging.getLogger(__name__)
def vault_addr():
defaults, _ = project.raw_project_map()
return defaults['aws']['vault']['address']
def vault_policy():
return 'builder-user'
@task
def login():
cmd = "VAULT_ADDR=%s vault login" % vault_addr()
local(cmd)
@task
def logout():
cmd = "rm -f ~/.vault-token"
local(cmd)
@task
def token_lookup(token):
cmd = "VAULT_ADDR=%s VAULT_TOKEN=%s vault token lookup" % (vault_addr(), token)
local(cmd)
@task
def token_create():
print("Warning: you should be authenticated with a root token to effectively create a new token here")
token = utils.get_input('token display name: ')
if not token or not token.strip():
print("a token display name is required")
sys.exit(1)
cmd = "VAULT_ADDR=%s vault token create -policy=%s -display-name=%s" % (vault_addr(), vault_policy(), token)
local(cmd)
@task
def token_revoke(token):
cmd = "VAULT_ADDR=%s vault token revoke %s" % (vault_addr(), token)
local(cmd)
|
from fabric.api import task, local
from buildercore import project
import utils
import sys
import logging
LOG = logging.getLogger(__name__)
def vault_addr():
defaults, _ = project.raw_project_map()
return defaults['aws']['vault']['address']
def vault_policy():
return 'builder-user'
@task
def login():
cmd = "VAULT_ADDR=%s vault login" % vault_addr()
local(cmd)
@task
def logout():
cmd = "rm -f ~/.vault-token"
local(cmd)
@task
def token_lookup(token):
cmd = "VAULT_ADDR=%s VAULT_TOKEN=%s vault token lookup" % (vault_addr(), token)
local(cmd)
@task
def token_create():
token = utils.get_input('token display name: ')
if not token or not token.strip():
print("a token display name is required")
sys.exit(1)
cmd = "VAULT_ADDR=%s vault token create -policy=%s -display-name=%s" % (vault_addr(), vault_policy(), token)
local(cmd)
@task
def token_revoke(token):
cmd = "VAULT_ADDR=%s vault token revoke %s" % (vault_addr(), token)
local(cmd)
|
Add sufficient leading lines to indicate the launching program of this script.
|
#!/usr/bin/python3
# -*- encoding: utf8 -*-
'''
Created on Mar 28, 2017
@author: Jack Rausch
'''
import http.client
import json
import ssl
import tbapy
#import requests
URL = "http://www.thebluealliance.com/api/v2/"
HEADER_KEY = "X-TBA-App-Id"
HEADER_VAL = 'frc4215:data-analysis:.1'
#I was thinking that we should turn this into a class so that we can have an instance for each regional
def api_is_up():
conn = http.client.HTTPConnection(URL,80)
conn.request('GET',"/status",{HEADER_KEY : HEADER_VAL})
response = conn.getresponse()
return response.read()
def get_event_teams(event_key):
tba = tbapy.TBA(HEADER_VAL)
jsonified = tba.event_teams(event_key)
teams = []
for team in jsonified:
teams.append(team["key"])
return teams
teams = get_event_teams('2010sc')
print(teams)
#up = api_is_up()
#print(up)
|
'''
Created on Mar 28, 2017
@author: Jack Rausch
'''
import http.client
import json
import ssl
import tbapy
#import requests
URL = "http://www.thebluealliance.com/api/v2/"
HEADER_KEY = "X-TBA-App-Id"
HEADER_VAL = 'frc4215:data-analysis:.1'
#I was thinking that we should turn this into a class so that we can have an instance for each regional
def api_is_up():
conn = http.client.HTTPConnection(URL,80)
conn.request('GET',"/status",{HEADER_KEY : HEADER_VAL})
response = conn.getresponse()
return response.read()
def get_event_teams(event_key):
tba = tbapy.TBA(HEADER_VAL)
jsonified = tba.event_teams(event_key)
teams = []
for team in jsonified:
teams.append(team["key"])
return teams
teams = get_event_teams('2010sc')
print(teams)
#up = api_is_up()
#print(up)
|
Fix a bug with setVersion and setPlatform
I noticed that the platform wasn't being set when running the app and that version was only being set in the snowflake.js by calling set instead of dispatch.
|
/**
* # authReducer.js
*
* The reducer for all the actions from the various log states
*/
'use strict';
/**
* ## Imports
*
* InitialState
*/
import InitialState from './deviceInitialState';
/**
* Device actions to test
*/
const {
SET_PLATFORM,
SET_VERSION,
SET_STATE
} = require('../../lib/constants').default;
const initialState = new InitialState;
/**
* ## deviceReducer function
* @param {Object} state - initialState
* @param {Object} action - type and payload
*/
export default function deviceReducer(state = initialState, action) {
if (!(state instanceof InitialState)) return initialState.merge(state);
switch (action.type) {
/**
* ### set the platform in the state
*
*/
case SET_PLATFORM:
const platform = action.payload;
return state.set('platform', platform);
/**
* ### set the version in the state
*
*/
case SET_VERSION:
const version = action.payload;
return state.set('version', version);
/**
* ### restore your state
*
* Support for Hot Loading
*/
case SET_STATE:
const device = JSON.parse(action.payload).device;
var next = state.set('isMobile',device.isMobile)
.set('platform',device.platform)
.set('version',device.version);
return next;
}
return state;
}
|
/**
* # authReducer.js
*
* The reducer for all the actions from the various log states
*/
'use strict';
/**
* ## Imports
*
* InitialState
*/
import InitialState from './deviceInitialState';
/**
* Device actions to test
*/
const {
SET_PLATFORM,
SET_VERSION,
SET_STATE
} = require('../../lib/constants');
const initialState = new InitialState;
/**
* ## deviceReducer function
* @param {Object} state - initialState
* @param {Object} action - type and payload
*/
export default function deviceReducer(state = initialState, action) {
if (!(state instanceof InitialState)) return initialState.merge(state);
switch (action.type) {
/**
* ### set the platform in the state
*
*/
case SET_PLATFORM:
const {platform} = action.payload;
return state.set('platform', platform);
/**
* ### set the version in the state
*
*/
case SET_VERSION:
const {version} = action.payload;
return state.set('version', version);
/**
* ### restore your state
*
* Support for Hot Loading
*/
case SET_STATE:
const device = JSON.parse(action.payload).device;
var next = state.set('isMobile',device.isMobile)
.set('platform',device.platform)
.set('version',device.version);
return next;
}
return state;
}
|
Check that display_name actually exists
|
const CoreView = require('backbone/core-view');
const template = require('./support-view/support-banner.tpl');
const checkAndBuildOpts = require('../../cartodb3/helpers/required-opts');
const REQUIRED_OPTS = [
'userModel'
];
/**
* Decide what support block app should show
*
*/
module.exports = CoreView.extend({
initialize: function (options) {
checkAndBuildOpts(options, REQUIRED_OPTS, this);
},
render: function () {
this.$el.html(
template({
userType: this._getUserType(),
orgDisplayEmail: this._getOrgAdminEmail(),
isViewer: this._userModel.isViewer()
})
);
return this;
},
_getUserType: function () {
var accountType = this._userModel.get('account_type').toLowerCase();
// Get user type
if (this._userModel.isOrgOwner()) {
return 'org_admin';
} else if (this._userModel.isInsideOrg()) {
return 'org';
} else if (accountType === 'internal' || accountType === 'partner' || accountType === 'ambassador') {
return 'internal';
} else if (accountType !== 'free') {
return 'client';
} else {
return 'regular';
}
},
_getOrgAdminEmail: function () {
if (this._userModel.isInsideOrg()) {
return this._userModel.organization && this._userModel.organization.display_email;
}
return null;
}
});
|
const CoreView = require('backbone/core-view');
const template = require('./support-view/support-banner.tpl');
const checkAndBuildOpts = require('../../cartodb3/helpers/required-opts');
const REQUIRED_OPTS = [
'userModel'
];
/**
* Decide what support block app should show
*
*/
module.exports = CoreView.extend({
initialize: function (options) {
checkAndBuildOpts(options, REQUIRED_OPTS, this);
},
render: function () {
this.$el.html(
template({
userType: this._getUserType(),
orgDisplayEmail: this._getOrgAdminEmail(),
isViewer: this._userModel.isViewer()
})
);
return this;
},
_getUserType: function () {
var accountType = this._userModel.get('account_type').toLowerCase();
// Get user type
if (this._userModel.isOrgOwner()) {
return 'org_admin';
} else if (this._userModel.isInsideOrg()) {
return 'org';
} else if (accountType === 'internal' || accountType === 'partner' || accountType === 'ambassador') {
return 'internal';
} else if (accountType !== 'free') {
return 'client';
} else {
return 'regular';
}
},
_getOrgAdminEmail: function () {
return this._userModel.isInsideOrg() ? this._userModel.organization.display_email : null;
}
});
|
Set focus automatically to first field
|
const $answer = $('.answer')
const {makeRichText} = require('./math-editor')
const save = ($elem, async = true) => $.post({
url: '/save',
data: {text: $elem.html(), answerId: $elem.attr('id')},
async
})
function saveScreenshot(questionId) {
return ({data, type, id}) => {
return $.post({
type: 'POST',
url: `/saveImg?answerId=${questionId}&id=${id}`,
data: data,
processData: false,
contentType: type
}).then(res => {
console.log('heh', res)
return res.url
})
}
}
const richTextOptions = id => ({
screenshot: {
saver: data => saveScreenshot(id)(data)
}
})
$answer.each((i, answer) => {
makeRichText(answer, richTextOptions(answer.id))
$.get(`/load?answerId=${answer.id}`, data => data && $(answer).html(data.html))
}).on('keypress', e => {
if (e.ctrlKey && !e.altKey && !e.shiftKey && e.key === 's') {
e.preventDefault()
save($(e.target))
}
})
$('#answer1').focus()
|
const $answer = $('.answer')
const {makeRichText} = require('./math-editor')
const save = ($elem, async = true) => $.post({
url: '/save',
data: {text: $elem.html(), answerId: $elem.attr('id')},
async
})
function saveScreenshot(questionId) {
return ({data, type, id}) => {
return $.post({
type: 'POST',
url: `/saveImg?answerId=${questionId}&id=${id}`,
data: data,
processData: false,
contentType: type
}).then(res => {
console.log('heh', res)
return res.url
})
}
}
const richTextOptions = id => ({
screenshot: {
saver: data => saveScreenshot(id)(data)
}
})
$answer.each((i, answer) => {
makeRichText(answer, richTextOptions(answer.id))
$.get(`/load?answerId=${answer.id}`, data => data && $(answer).html(data.html))
}).on('keypress', e => {
if (e.ctrlKey && !e.altKey && !e.shiftKey && e.key === 's') {
e.preventDefault()
save($(e.target))
}
})
|
Use url instead of home-page. Separate keywords by commas.
|
import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = "ideone",
version = "0.0.1",
author = "Joe Schafer",
author_email = "joe@jschaf.com",
url = "http://github.com/jschaf/ideone-api/",
description = "A Python binding to the Ideone (Online Compiler) API.",
license = "BSD",
platforms = ["any"],
keywords = "API, ideone, codepad",
packages = ['ideone'],
long_description=read('README.rst'),
classifiers=[
"Development Status :: 3 - Alpha",
"Topic :: Utilities",
"License :: OSI Approved :: BSD License",
],
install_requires=['suds',]
)
|
import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = "ideone",
version = "0.0.1",
author = "Joe Schafer",
author_email = "joe@jschaf.com",
home-page = "http://github.com/jschaf/ideone-api/",
summary = "A Python binding to the Ideone (Online Compiler) API.",
description = "A Python binding to the Ideone (Online Compiler) API.",
license = "BSD",
platforms = ["any"],
keywords = "API ideone codepad",
packages = ['ideone'],
long_description=read('README.rst'),
classifiers=[
"Development Status :: 3 - Alpha",
"Topic :: Utilities",
"License :: OSI Approved :: BSD License",
],
install_requires=['suds',]
)
|
Fix minor object parameter conflict with PHPUnit.
|
<?php
namespace League\Plates\Template;
class DataTest extends \PHPUnit_Framework_TestCase
{
private $template_data;
public function setUp()
{
$this->template_data = new Data;
}
public function testCanCreateInstance()
{
$this->assertInstanceOf('League\Plates\Template\Data', $this->template_data);
}
public function testAddData()
{
$this->template_data->add(array('name' => 'Jonathan'));
$data = $this->template_data->get();
$this->assertEquals($data['name'], 'Jonathan');
}
public function testAddDataWithTemplate()
{
$this->template_data->add(array('name' => 'Jonathan'), 'template');
$data = $this->template_data->get('template');
$this->assertEquals($data['name'], 'Jonathan');
}
public function testAddDataWithTemplates()
{
$this->template_data->add(array('name' => 'Jonathan'), array('template1', 'template2'));
$data = $this->template_data->get('template1');
$this->assertEquals($data['name'], 'Jonathan');
}
public function testAddDataWithInvalidTemplateFileType()
{
$this->setExpectedException('LogicException', 'The templates variable must be null, an array or a string, integer given.');
$this->template_data->add(array('name' => 'Jonathan'), 123);
}
}
|
<?php
namespace League\Plates\Template;
class DataTest extends \PHPUnit_Framework_TestCase
{
private $data;
public function setUp()
{
$this->data = new Data;
}
public function testCanCreateInstance()
{
$this->assertInstanceOf('League\Plates\Template\Data', $this->data);
}
public function testAddData()
{
$this->data->add(array('name' => 'Jonathan'));
$data = $this->data->get();
$this->assertEquals($data['name'], 'Jonathan');
}
public function testAddDataWithTemplate()
{
$this->data->add(array('name' => 'Jonathan'), 'template');
$data = $this->data->get('template');
$this->assertEquals($data['name'], 'Jonathan');
}
public function testAddDataWithTemplates()
{
$this->data->add(array('name' => 'Jonathan'), array('template1', 'template2'));
$data = $this->data->get('template1');
$this->assertEquals($data['name'], 'Jonathan');
}
public function testAddDataWithInvalidTemplateFileType()
{
$this->setExpectedException('LogicException', 'The templates variable must be null, an array or a string, integer given.');
$this->data->add(array('name' => 'Jonathan'), 123);
}
}
|
Make the is Mobile App smarter
It will now works even when there is not mobapp GET request on the next pages than the homepage containing the ?mobapp=1 request
|
<?php
/**
* @title Mobile App class for iOS/Android apps.
*
* @author Pierre-Henry Soria <hello@ph7cms.com>
* @copyright (c) 2015-2016, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
* @package PH7 / Framework / Mobile
*/
namespace PH7\Framework\Mobile;
defined('PH7') or exit('Restricted access');
use PH7\Framework\Mvc\Request\Http, PH7\Framework\Session\Session;
class MobApp
{
// Request name used in mobile apps
const VAR_NAME = 'mobapp';
/**
* Check if a mobile native app called the site.
*
* @return boolean
*/
final public static function is()
{
$oSession = new Session;
if ((new Http)->getExists(static::VAR_NAME)) {
$oSession->set(static::VAR_NAME, 1);
}
$bRet = $oSession->exists(static::VAR_NAME);
unset($oSession);
return $bRet;
}
}
|
<?php
/**
* @title Mobile App class for iOS/Android apps.
*
* @author Pierre-Henry Soria <hello@ph7cms.com>
* @copyright (c) 2015-2016, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
* @package PH7 / Framework / Mobile
*/
namespace PH7\Framework\Mobile;
defined('PH7') or exit('Restricted access');
use PH7\Framework\Mvc\Request\Http;
class MobApp
{
// Request name used in mobile apps
const REQ_NAME = 'mobapp';
/**
* Check if a mobile native app called the site.
*
* @return boolean
*/
final public static function is()
{
return (new Http)->getExists(static::REQ_NAME);
}
}
|
Fix for html escaped characters
|
import re
import requests
import logging
from base import BaseBot
from HTMLParser import HTMLParser
logger = logging.getLogger(__name__)
html_parser = HTMLParser()
CHUCK_API_URL = 'http://api.icndb.com'
CHUCK_REGEX = re.compile(r'^!chuck')
def random_chuck_fact():
try:
fact = requests.get('%s/jokes/random' % CHUCK_API_URL.rstrip('/')).json()
return html_parser.unescape(fact['value']['joke'])
except Exception as e:
logger.info('Error while retrieving Chuck Norris facts: %s' % e)
return None
class ChuckBot(BaseBot):
def __init__(self, connection):
super(ChuckBot, self).__init__(connection)
def handle(self, message):
if re.match(CHUCK_REGEX, message.text):
fact = random_chuck_fact()
if not fact:
response = "Can't find any facts :feelbad:"
else:
response = fact
self.connection.send_message(response, message.channel)
return True
return False
|
import re
import requests
import logging
from base import BaseBot
logger = logging.getLogger(__name__)
CHUCK_API_URL = 'http://api.icndb.com'
CHUCK_REGEX = re.compile(r'^!chuck')
def random_chuck_fact():
try:
fact = requests.get('%s/jokes/random' % CHUCK_API_URL.rstrip('/')).json()
return fact['value']['joke']
except Exception as e:
logger.info('Error while retrieving Chuck Norris facts: %s' % e)
return None
class ChuckBot(BaseBot):
def __init__(self, connection):
super(ChuckBot, self).__init__(connection)
def handle(self, message):
if re.match(CHUCK_REGEX, message.text):
fact = random_chuck_fact()
if not fact:
response = "Can't find any facts :feelbad:"
else:
response = fact
self.connection.send_message(response, message.channel)
return True
return False
|
Move dependencies to after exports line
This prevents an issue with circular dependencies.
|
/**
* Controller Object to dispatch actions to view/Contact and model/Contacts.
* @constructor
*/
var ContactsController = function() {
};
ContactsController.remove = function(id) {
ContactModel.remove(id);
ContactView.remove(id);
};
ContactsController.render = function(id, contact) {
var contactView = new ContactView(id, contact);
};
ContactsController.prototype = {
setup: function() {
var addContact = new AddContactForm();
},
/**
* @description Fetches all existing contacts from LocalStorage.
*/
fetchAll: function() {
var contacts = [];
var total = localStorage.length;
for (i = 0; i < total; i++) {
var contact = {};
var key = localStorage.key(i);
if (key !== 'debug') {
contact.key = key;
contact.value = JSON.parse(localStorage.getItem((i + 1).toString()));
contacts.push(contact);
}
}
return contacts;
},
/**
* @description Adds all existing contacts to table. Intended for use
* on startup.
*/
renderAll: function() {
var contacts = this.fetchAll();
contacts.forEach(function(currentValue) {
var contact = new ContactView(currentValue.key, currentValue.value);
});
}
};
module.exports = ContactsController;
// Keep requires after the exports to prevent cirular dependency issues
var ContactModel = require('../model/Contacts');
var ContactView = require('../view/Contact');
var AddContactForm = require('../view/AddContactForm');
|
var ContactModel = require('../model/Contacts');
var ContactView = require('../view/Contact');
var AddContactForm = require('../view/AddContactForm');
/**
* Controller Object to dispatch actions to view/Contact and model/Contacts.
* @constructor
*/
var ContactsController = function() {
};
ContactsController.remove = function(id) {
console.log('Controller Remove');
//ContactModel.remove(id);
//ContactView.remove(id);
};
ContactsController.render = function(id, contact) {
var contactView = new ContactView(id, contact);
};
ContactsController.prototype = {
setup: function() {
var addContact = new AddContactForm();
},
/**
* @description Fetches all existing contacts from LocalStorage.
*/
fetchAll: function() {
var contacts = [];
var total = localStorage.length;
for (i = 0; i < total; i++) {
var contact = {};
var key = localStorage.key(i);
if (key !== 'debug') {
contact.key = key;
contact.value = JSON.parse(localStorage.getItem((i + 1).toString()));
contacts.push(contact);
}
}
return contacts;
},
/**
* @description Adds all existing contacts to table. Intended for use
* on startup.
*/
renderAll: function() {
var contacts = this.fetchAll();
contacts.forEach(function(currentValue) {
var contact = new ContactView(currentValue.key, currentValue.value);
});
}
};
module.exports = ContactsController;
|
Fix loading bug in ok_test
|
from client import exceptions as ex
from client.sources.ok_test import concept
from client.sources.ok_test import doctest
from client.sources.ok_test import models
from client.sources.common import importing
import logging
import os
log = logging.getLogger(__name__)
SUITES = {
'doctest': doctest.DoctestSuite,
'concept': concept.ConceptSuite,
}
def load(file, parameter, args):
"""Loads an OK-style test from a specified filepath.
PARAMETERS:
file -- str; a filepath to a Python module containing OK-style
tests.
RETURNS:
Test
"""
if not os.path.isfile(file) or not file.endswith('.py'):
log.info('Cannot import {} as an OK test'.format(file))
raise ex.LoadingException('Cannot import {} as an OK test'.format(file))
test = importing.load_module(file).test
try:
return {file: models.OkTest(SUITES, args.verbose, args.interactive,
args.timeout, **test)}
except ex.SerializeException:
raise ex.LoadingException('Cannot load OK test {}'.format(file))
|
from client import exceptions as ex
from client.sources.ok_test import concept
from client.sources.ok_test import doctest
from client.sources.ok_test import models
from client.sources.common import importing
import logging
import os
log = logging.getLogger(__name__)
SUITES = {
'doctest': doctest.DoctestSuite,
'concept': concept.ConceptSuite,
}
def load(file, parameter, args):
"""Loads an OK-style test from a specified filepath.
PARAMETERS:
file -- str; a filepath to a Python module containing OK-style
tests.
RETURNS:
Test
"""
if not os.path.isfile(file) or not file.endswith('.py'):
log.info('Cannot import {} as an OK test'.format(file))
raise ex.LoadingException('Cannot import {} as an OK test'.format(file))
test = importing.load_module(file).test
try:
return models.OkTest(SUITES, args.verbose, args.interactive,
args.timeout, **test)
except ex.SerializeException:
raise ex.LoadingException('Cannot load OK test {}'.format(file))
|
Remove static access on instance.
|
/*
* MIT License
*
* Copyright (c) 2020 Jannis Weis
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package com.github.weisj.darklaf.settings;
import javax.swing.*;
public class ThemeSettingsMenuItem extends JMenuItem {
public ThemeSettingsMenuItem(final String text) {
super(text);
setIcon(ThemeSettings.getIcon());
addActionListener(e -> ThemeSettings.showSettingsDialog(this));
}
}
|
/*
* MIT License
*
* Copyright (c) 2020 Jannis Weis
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package com.github.weisj.darklaf.settings;
import java.awt.*;
import javax.swing.*;
public class ThemeSettingsMenuItem extends JMenuItem {
public ThemeSettingsMenuItem(final String text) {
super(text);
setIcon(ThemeSettings.getInstance().getIcon());
addActionListener(e -> ThemeSettings.showSettingsDialog(this));
}
}
|
Make the G-Cloud collector empty the data set
https://www.pivotaltracker.com/story/show/72073020
[Delivers #72073020]
|
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
from dshelpers import download_url
from performanceplatform.collector.gcloud.core import (
nuke_local_database, save_raw_data, aggregate_and_save,
push_aggregates)
from performanceplatform.collector.gcloud.sales_parser import (
get_latest_csv_url)
from performanceplatform.collector.write import DataSet
INDEX_URL = ('https://digitalmarketplace.blog.gov.uk'
'/sales-accreditation-information/')
def main(credentials, data_set_config, query, options, start_at, end_at,
filename=None):
nuke_local_database()
if filename is not None:
with open(filename, 'r') as f:
save_raw_data(f)
else:
save_raw_data(download_url(get_latest_csv_url(INDEX_URL)))
aggregate_and_save()
data_set = DataSet.from_config(data_set_config)
data_set.empty_data_set()
push_aggregates(data_set)
|
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
from dshelpers import download_url
from performanceplatform.collector.gcloud.core import (
nuke_local_database, save_raw_data, aggregate_and_save,
push_aggregates)
from performanceplatform.collector.gcloud.sales_parser import (
get_latest_csv_url)
from performanceplatform.collector.write import DataSet
INDEX_URL = ('https://digitalmarketplace.blog.gov.uk'
'/sales-accreditation-information/')
def main(credentials, data_set_config, query, options, start_at, end_at,
filename=None):
nuke_local_database()
if filename is not None:
with open(filename, 'r') as f:
save_raw_data(f)
else:
save_raw_data(download_url(get_latest_csv_url(INDEX_URL)))
aggregate_and_save()
data_set = DataSet.from_config(data_set_config)
push_aggregates(data_set)
|
Add endpoint handling to Token/Endpoint auth
This auth plugin was initially created before get_endpoint was
available. Implement the get_endpoint method so that we can use the
plugin with relative URLs.
Closes-Bug: #1323926
Change-Id: Ic868f509e708ad29faf86ec5ceeab2a9c98a24fc
|
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from keystoneclient.auth import base
class Token(base.BaseAuthPlugin):
"""A provider that will always use the given token and endpoint.
This is really only useful for testing and in certain CLI cases where you
have a known endpoint and admin token that you want to use.
"""
def __init__(self, endpoint, token):
# NOTE(jamielennox): endpoint is reserved for when plugins
# can be used to provide that information
self.endpoint = endpoint
self.token = token
def get_token(self, session):
return self.token
def get_endpoint(self, session, **kwargs):
"""Return the supplied endpoint.
Using this plugin the same endpoint is returned regardless of the
parameters passed to the plugin.
"""
return self.endpoint
|
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from keystoneclient.auth import base
class Token(base.BaseAuthPlugin):
"""A provider that will always use the given token and endpoint.
This is really only useful for testing and in certain CLI cases where you
have a known endpoint and admin token that you want to use.
"""
def __init__(self, endpoint, token):
# NOTE(jamielennox): endpoint is reserved for when plugins
# can be used to provide that information
self.endpoint = endpoint
self.token = token
def get_token(self, session):
return self.token
|
Enable building hybrid capsule/non-capsule packages (CNY-3271)
|
#
# Copyright (c) 2009 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/licenses/CPL-1.0.
#
# 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 Common Public License for
# full details.
#
import inspect
from conary.build import action, defaultrecipes
from conary.build.recipe import RECIPE_TYPE_CAPSULE
from conary.build.packagerecipe import BaseRequiresRecipe, AbstractPackageRecipe
class AbstractCapsuleRecipe(AbstractPackageRecipe):
internalAbstractBaseClass = 1
internalPolicyModules = ( 'packagepolicy', 'capsulepolicy' )
_recipeType = RECIPE_TYPE_CAPSULE
def __init__(self, *args, **kwargs):
klass = self._getParentClass('AbstractPackageRecipe')
klass.__init__(self, *args, **kwargs)
from conary.build import build
for name, item in build.__dict__.items():
if inspect.isclass(item) and issubclass(item, action.Action):
self._addBuildAction(name, item)
def loadSourceActions(self):
self._loadSourceActions(lambda item: item._packageAction is True)
exec defaultrecipes.CapsuleRecipe
|
#
# Copyright (c) 2009 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/licenses/CPL-1.0.
#
# 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 Common Public License for
# full details.
#
from conary.build import defaultrecipes
from conary.build.recipe import RECIPE_TYPE_CAPSULE
from conary.build.packagerecipe import BaseRequiresRecipe, AbstractPackageRecipe
class AbstractCapsuleRecipe(AbstractPackageRecipe):
internalAbstractBaseClass = 1
internalPolicyModules = ( 'packagepolicy', 'capsulepolicy' )
_recipeType = RECIPE_TYPE_CAPSULE
def __init__(self, *args, **kwargs):
klass = self._getParentClass('AbstractPackageRecipe')
klass.__init__(self, *args, **kwargs)
from conary.build import source
self._addSourceAction('source.addCapsule', source.addCapsule)
self._addSourceAction('source.addSource', source.addSource)
exec defaultrecipes.CapsuleRecipe
|
Print out phone number and message from twilio get requests
|
package main
import (
"fmt"
//"io"
//"io/ioutil"
"log"
"net/http"
"os"
//"strings"
)
func receive(w http.ResponseWriter, r *http.Request) {
wholeurl := r.URL.String()
body := r.URL.Query()["Body"]
phone := r.URL.Query()["From"]
fmt.Printf("wholeurl:\n%s\n\nPhone: %s\nBody: %s,\n\n", wholeurl, phone, body)
}
func main() {
// Read the port from the file.
//fileContents, err := ioutil.ReadFile("port.txt")
//if err != nil {
// log.Fatal(err)
//}
//port := strings.TrimSpace(string(fileContents))
if len(os.Args) != 2 {
log.Fatal("usage: server.go port")
}
port := ":" + os.Args[1]
// Start the server.
fmt.Printf("Starting TxtRoulette server on port %s...\n", port)
http.HandleFunc("/receive/", receive)
log.Fatal(http.ListenAndServe(port, nil))
}
|
package main
import (
"fmt"
"io"
//"io/ioutil"
"log"
"net/http"
"os"
//"strings"
)
func receive(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "Hello world!")
}
func main() {
// Read the port from the file.
//fileContents, err := ioutil.ReadFile("port.txt")
//if err != nil {
// log.Fatal(err)
//}
//port := strings.TrimSpace(string(fileContents))
if len(os.Args) != 2 {
log.Fatal("usage: server.go port")
}
port := ":" + os.Args[1]
// Start the server.
fmt.Printf("Starting TxtRoulette server on port %s...\n", port)
http.HandleFunc("/receive", receive)
log.Fatal(http.ListenAndServe(port, nil))
}
|
Use the right file object
|
package de.onyxbits.raccoon.io;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
/**
* A simple session log for recording the files that were downloaded. The log is
* meant to be used as an input for shellscripts, so the logformat is dead
* simple: every line contains the filename of one successfully downloded file.
*
* @author patrick
*
*/
public class DownloadLogger {
public static final String LOGCOMPLETE = "downloads-complete.txt";
private File completeLog;
/**
* Create a new logger
*
* @param logfile
* the file to log to.
*/
public DownloadLogger(Archive archive) {
completeLog = new File(new File(archive.getRoot(), Archive.LOGDIR), LOGCOMPLETE);
}
/**
* Clears the download log. This should be called when starting the session.
*/
public synchronized void clear() {
if (completeLog.exists()) {
completeLog.delete();
}
}
/**
* Log a completed download to the logfile
*
* @param file
* the file that was downloaded
* @throws IOException
* if writing fails.
*/
public synchronized void addEntry(File file) throws IOException {
completeLog.getParentFile().mkdirs();
FileWriter fw = new FileWriter(completeLog, true);
fw.write(completeLog.getAbsolutePath() + "\n");
fw.close();
}
}
|
package de.onyxbits.raccoon.io;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
/**
* A simple session log for recording the files that were downloaded. The log is
* meant to be used as an input for shellscripts, so the logformat is dead
* simple: every line contains the filename of one successfully downloded file.
*
* @author patrick
*
*/
public class DownloadLogger {
public static final String LOGCOMPLETE = "downloads-complete.txt";
private File completeLog;
/**
* Create a new logger
*
* @param logfile
* the file to log to.
*/
public DownloadLogger(Archive archive) {
completeLog = new File(new File(archive.getRoot(), Archive.LOGDIR), LOGCOMPLETE);
}
/**
* Clears the download log. This should be called when starting the session.
*/
public synchronized void clear() {
if (completeLog.exists()) {
completeLog.delete();
}
}
/**
* Log a completed download to the logfile
*
* @param file
* the file that was downloaded
* @throws IOException
* if writing fails.
*/
public synchronized void addEntry(File file) throws IOException {
completeLog.getParentFile().mkdirs();
FileWriter fw = new FileWriter(completeLog, true);
fw.write(file.getAbsolutePath() + "\n");
fw.close();
}
}
|
:lock: Use isAuthenticated() method in LoggedIn middleware
|
const helpers = {
/**
* Express middleware to determine if the user is logged in
* @param {Object} req
* @param {Object} res
* @param {Function} next
*/
loggedIn(req, res, next) {
if (!req.isAuthenticated() || req.user !== undefined) {
next();
} else {
res.json({ status: 401, redirect: '/admin/login' });
}
},
/**
* Converts a String to a slug
* @param {String} str
* @returns {String}
*/
slugify(str) {
return str
.toLowerCase()
.replace(/^\s+|\s+$/g, '') // Trim leading/trailing whitespace
.replace(/[-\s]+/g, '-') // Replace spaces with dashes
.replace(/[^a-z0-9-]/g, '') // Remove disallowed symbols
.replace(/--+/g, '-');
},
/**
* Reduces an array of objects to one object using the key value pair parameters
* @param {Array} arr
* @param {String} key
* @param {String} value
* @param {Object} start
* @returns {Object}
*/
reduceToObj(arr, key, value, start = {}) {
return arr
.reduce((prev, curr) =>
Object.assign({}, prev, { [curr[key]]: curr[value] }), start);
},
};
module.exports = helpers;
|
const helpers = {
/**
* Express middleware to determine if the user is logged in
* @param {Object} req
* @param {Object} res
* @param {Function} next
*/
loggedIn(req, res, next) {
if (req.user !== undefined) {
next();
} else {
res.json({ status: 401, redirect: '/admin/login' });
}
},
/**
* Converts a String to a slug
* @param {String} str
* @returns {String}
*/
slugify(str) {
return str
.toLowerCase()
.replace(/^\s+|\s+$/g, '') // Trim leading/trailing whitespace
.replace(/[-\s]+/g, '-') // Replace spaces with dashes
.replace(/[^a-z0-9-]/g, '') // Remove disallowed symbols
.replace(/--+/g, '-');
},
/**
* Reduces an array of objects to one object using the key value pair parameters
* @param {Array} arr
* @param {String} key
* @param {String} value
* @param {Object} start
* @returns {Object}
*/
reduceToObj(arr, key, value, start = {}) {
return arr
.reduce((prev, curr) =>
Object.assign({}, prev, { [curr[key]]: curr[value] }), start);
},
};
module.exports = helpers;
|
Fix server side to write properly
|
package cpw.mods.fml.common.launcher;
import cpw.mods.fml.relauncher.FMLLaunchHandler;
import net.minecraft.launchwrapper.LaunchClassLoader;
public class FMLServerTweaker extends FMLTweaker {
@Override
public String getLaunchTarget()
{
return "net.minecraft.server.MinecraftServer";
}
@Override
public void injectIntoClassLoader(LaunchClassLoader classLoader)
{
// The mojang packages are excluded so the log4j2 queue is correctly visible from
// the obfuscated and deobfuscated parts of the code. Without, the UI won't show anything
classLoader.addClassLoaderExclusion("com.mojang.");
classLoader.addTransformerExclusion("cpw.mods.fml.repackage.");
classLoader.addTransformerExclusion("cpw.mods.fml.relauncher.");
classLoader.addTransformerExclusion("cpw.mods.fml.common.asm.transformers.");
classLoader.addClassLoaderExclusion("LZMA.");
FMLLaunchHandler.configureForServerLaunch(classLoader, this);
FMLLaunchHandler.appendCoreMods();
}
}
|
package cpw.mods.fml.common.launcher;
import cpw.mods.fml.relauncher.FMLLaunchHandler;
import net.minecraft.launchwrapper.LaunchClassLoader;
public class FMLServerTweaker extends FMLTweaker {
@Override
public String getLaunchTarget()
{
return "net.minecraft.server.MinecraftServer";
}
@Override
public void injectIntoClassLoader(LaunchClassLoader classLoader)
{
classLoader.addClassLoaderExclusion("com.mojang.util.");
classLoader.addTransformerExclusion("cpw.mods.fml.repackage.");
classLoader.addTransformerExclusion("cpw.mods.fml.relauncher.");
classLoader.addTransformerExclusion("cpw.mods.fml.common.asm.transformers.");
classLoader.addClassLoaderExclusion("LZMA.");
FMLLaunchHandler.configureForServerLaunch(classLoader, this);
FMLLaunchHandler.appendCoreMods();
}
}
|
Fix reversed names in metrics
|
/**
*
*/
package gr.uoi.cs.daintiness.hecate.diff;
import gr.uoi.cs.daintiness.hecate.metrics.Metrics;
import gr.uoi.cs.daintiness.hecate.metrics.tables.TablesInfo;
import gr.uoi.cs.daintiness.hecate.transitions.TransitionList;
/**
* @author iskoulis
*
*/
public class DiffResult {
final public TransitionList tl;
final public Metrics met;
final public TablesInfo tInfo;
/**
*
*/
public DiffResult() {
this.tl = new TransitionList();
this.met = new Metrics();
this.tInfo = new TablesInfo();
}
public void setVersionNames(String oldVersion, String newVersion) {
this.tl.setVersionNames(oldVersion, newVersion);
this.met.setVersionNames(oldVersion, newVersion);
}
public void clear() {
this.tInfo.clear();
met.resetRevisions();
}
}
|
/**
*
*/
package gr.uoi.cs.daintiness.hecate.diff;
import gr.uoi.cs.daintiness.hecate.metrics.Metrics;
import gr.uoi.cs.daintiness.hecate.metrics.tables.TablesInfo;
import gr.uoi.cs.daintiness.hecate.transitions.TransitionList;
/**
* @author iskoulis
*
*/
public class DiffResult {
final public TransitionList tl;
final public Metrics met;
final public TablesInfo tInfo;
/**
*
*/
public DiffResult() {
this.tl = new TransitionList();
this.met = new Metrics();
this.tInfo = new TablesInfo();
}
public void setVersionNames(String newVersion, String oldVersion) {
this.tl.setVersionNames(oldVersion, newVersion);
this.met.setVersionNames(oldVersion, newVersion);
}
public void clear() {
this.tInfo.clear();
met.resetRevisions();
}
}
|
Make sure we close the socket
|
import socket
from hiss.handler.gntp.message import Response
class GNTPHandler():
def register(self, notifier, target, **kwargs):
pass
def notify(self, notification, target):
pass
def unregister(self, notifier, target):
pass
def send_request(request, target, wait_for_response=True):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(target.address)
s.sendall(request.marshal())
if wait_for_response:
response_data = bytearray()
while True:
data = s.recv(1024)
if not data:
break
response_data.extend(data)
response = Response()
response.unmarshal(response_data)
else:
response = None
s.close()
return response
|
import socket
from hiss.handler.gntp.message import Response
class GNTPHandler():
def register(self, notifier, target, **kwargs):
pass
def notify(self, notification, target):
pass
def unregister(self, notifier, target):
pass
def send_request(request, target, wait_for_response=True):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(target.address)
s.sendall(request.marshal())
if wait_for_response:
response_data = bytearray()
while True:
data = s.recv(1024)
if not data:
break
response_data.extend(data)
response = Response()
response.unmarshal(response_data)
return response
else:
response = None
s.close()
return response
|
Leverage util.format for printf-style logging
|
var _ = require('lodash')
var globFirst = require('./glob-first')
var log = require('../run/log')
var path = require('path')
var async = require('async')
var isExecutable = require('./is-executable')
module.exports = function (patterns, cb) {
globFirst(patterns, function (er, results) {
if (er) return cb(er)
async.map(results, function (result, cb) {
isExecutable(result, function (er, itIsExecutable) {
if (itIsExecutable) {
cb(er, path.resolve(result))
} else {
log(
'Warning: scripty - ignoring script "%s" because it' +
' was not executable. Run `chmod +x "%s" if you want' +
' scripty to run it.', result, result)
cb(er, undefined)
}
})
}, function (er, results) {
cb(er, _.compact(results))
})
})
}
|
var _ = require('lodash')
var globFirst = require('./glob-first')
var log = require('../run/log')
var path = require('path')
var async = require('async')
var isExecutable = require('./is-executable')
module.exports = function (patterns, cb) {
globFirst(patterns, function (er, results) {
if (er) return cb(er)
async.map(results, function (result, cb) {
isExecutable(result, function (er, itIsExecutable) {
if (itIsExecutable) {
cb(er, path.resolve(result))
} else {
log(
'Warning: scripty - ignoring script "' + result + '" because it' +
' was not executable. Run `chmod +x "' + result + '" if you want' +
' scripty to run it.'
)
cb(er, undefined)
}
})
}, function (er, results) {
cb(er, _.compact(results))
})
})
}
|
Fix ESLint error for no parenthesis for single params
|
exports.newGame = function newGame(gameId, opponentName, isStarting) {
return {
gameId,
opponentName,
isStarting,
};
};
exports.lengthOfRoom = function lengthOfRoom(io, roomName) {
const room = io.sockets.adapter.rooms[roomName];
if (room) {
return room.length;
}
return 0;
};
exports.clientsForRoom = function clientsForRoom(io, roomName) {
const room = io.sockets.adapter.rooms[roomName];
if (room) {
return Object.keys(room.sockets);
}
return [];
};
exports.isClientInRoom = function isClientInRoom(io, roomName, clientId) {
const clients = exports.clientsForRoom(io, roomName);
return clients.indexOf(clientId) !== -1;
};
/**
* Binds supplied io and socket as this to given function
* @param {Object} io the io object
* @param {Object} socket the socket object
* @return {Function} function that takes a function argument that will receive the socket binding
*/
exports.bindSocket = function bindSocket(io, socket) {
return functionHandler => functionHandler.bind({ io, socket });
};
|
exports.newGame = function newGame(gameId, opponentName, isStarting) {
return {
gameId,
opponentName,
isStarting,
};
};
exports.lengthOfRoom = function lengthOfRoom(io, roomName) {
const room = io.sockets.adapter.rooms[roomName];
if (room) {
return room.length;
}
return 0;
};
exports.clientsForRoom = function clientsForRoom(io, roomName) {
const room = io.sockets.adapter.rooms[roomName];
if (room) {
return Object.keys(room.sockets);
}
return [];
};
exports.isClientInRoom = function isClientInRoom(io, roomName, clientId) {
const clients = exports.clientsForRoom(io, roomName);
return clients.indexOf(clientId) !== -1;
};
/**
* Binds supplied io and socket as this to given function
* @param {Object} io the io object
* @param {Object} socket the socket object
* @return {Function} function that takes a function argument that will receive the socket binding
*/
exports.bindSocket = function bindSocket(io, socket) {
return (functionHandler) => functionHandler.bind({ io, socket });
};
|
Fix Space and comment issues.
|
var http = require('http');
var url = require('url');
var port = 8000;
var server = http.createServer(function (request, response){
try {
//go to http://127.0.0.1:8000/?req=Hello
console.log('Server Pinged');
response.writeHead(200, {"Content-Type": "text/plain"});
var req = checkURL(request);
var resp;
if(req === "Hello"){
resp = "World";
}
else{
resp = "Please Enter: Aaron, Monty or Hello";
}
response.write(resp);
response.end();
}
catch(e) {
response.writeHead(500, { 'content-type': 'text/plain' });
response.write('ERROR:' + e);
response.end('\n');
}
});
server.listen(port);
console.log('The server has run');
function checkURL(request){
var phrase = url.parse(request.url, true).query;
// this checks for a query with a property called 'req' and returns its value.
return phrase.req;
}
|
var http = require('http');
var url = require('url');
var port = 8000;
var server = http.createServer(function (request, response){
try {
//go to http://127.0.0.1:8000/?req=Monty
console.log('Server Pinged'); //Ping the server (will show in the cmd prompt)
//The below will be written to the Web Browser
response.writeHead(200, {"Content-Type": "text/plain"});
var req = checkURL(request); //Passes request into the checkURL function and stores output into the req variable
var resp;
if(req === "Aaron"){
resp = "Gavendo";
}
else if(req === "Monty"){
resp = "python";
}
else if(req === "Hello"){
resp = "World";
}
else{
resp = "Please Enter: Aaron, Monty or Hello";
}
response.write(resp); //Write the response on the web page.
response.end();
}
catch (e) {
response.writeHead(500, { 'content-type': 'text/plain' });
response.write('ERROR:' + e);
response.end('\n');
}
});
server.listen(port);
console.log('The server has run'); //This is for the cmd prompt. Runs once at the start.
function checkURL(request){
var phrase = url.parse(request.url, true).query;
// this checks for a query with a property called 'req' and returns its value.
return phrase.req;
}
|
Disable viewport calculation in case of server side render
|
import React from 'react';
import Helmet from 'react-helmet';
import styles from './styles';
function calculateViewportFromWindow() {
if (typeof window !== 'undefined') {
if (window.innerWidth >= 544) return 'sm';
if (window.innerWidth >= 768) return 'md';
if (window.innerWidth >= 992) return 'lg';
if (window.innerWidth >= 1200) return 'xl';
return'xs';
} else {
return null;
}
}
function renderAugmentedChildren(props) {
return React.Children.map(props.children, (child) => {
if (!child) return null;
return React.cloneElement(child, { viewport: props.viewport });
});
}
const LandingCanvas = (props) => {
const s = styles(props);
let {
viewport
} = props;
viewport = viewport || calculateViewportFromWindow();
return (
<div style={ s.wrapper }>
<Helmet
link={[
{ rel: 'stylesheet', href: 'https://fonts.googleapis.com/css?family=Lato' },
{ rel: 'stylesheet', href: 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css' }
]}
/>
{ renderAugmentedChildren(props) }
</div>
);
}
export default LandingCanvas;
|
import React from 'react';
import Helmet from 'react-helmet';
import styles from './styles';
function calculateViewportFromWindow() {
if (window.innerWidth >= 544) return 'sm';
if (window.innerWidth >= 768) return 'md';
if (window.innerWidth >= 992) return 'lg';
if (window.innerWidth >= 1200) return 'xl';
return'xs';
}
function renderAugmentedChildren(props) {
return React.Children.map(props.children, (child) => {
if (!child) return null;
return React.cloneElement(child, { viewport: props.viewport });
});
}
const LandingCanvas = (props) => {
const s = styles(props);
let {
viewport
} = props;
viewport = viewport || calculateViewportFromWindow();
return (
<div style={ s.wrapper }>
<Helmet
link={[
{ rel: 'stylesheet', href: 'https://fonts.googleapis.com/css?family=Lato' },
{ rel: 'stylesheet', href: 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css' }
]}
/>
{ renderAugmentedChildren(props) }
</div>
);
}
export default LandingCanvas;
|
Prepend sign in button to dashboard.html
|
document.body.prepend(dynamicButton);
function createClassroom() {
var auth2 = gapi.auth2.getAuthInstance();
var name = "";
var email = "";
if (auth2.isSignedIn.get()) {
var name = auth2.currentUser.get().getBasicProfile().getName();
var email = auth2.currentUser.get().getBasicProfile().getEmail();
}
var subject = document.querySelector('#subject').value;
var classroomData = JSON.stringify({ "nickname": name, "userId": email, "subject": subject });
fetch("/dashboard-handler", {method: "POST", body: classroomData}).then((resp) => {
if (resp.ok){
console.log("Classroom Created!");
} else {
console.log("Error has occured");
}
});
}
|
function createClassroom() {
var auth2 = gapi.auth2.getAuthInstance();
var name = "";
var email = "";
if (auth2.isSignedIn.get()) {
var name = auth2.currentUser.get().getBasicProfile().getName();
var email = auth2.currentUser.get().getBasicProfile().getEmail();
}
var subject = document.querySelector('#subject').value;
var classroomData = JSON.stringify({ "nickname": name, "userId": email, "subject": subject });
fetch("/dashboard-handler", {method: "POST", body: classroomData}).then((resp) => {
if (resp.ok){
console.log("Classroom Created!");
} else {
console.log("Error has occured");
}
});
}
|
Add a new domain to the whitelist
|
IRG.constants = (function(){
var approvedDomains = function(){
return ["imgur.com", "flickr.com", "cdn.diycozyhome.com", "pbs.twimg.com", "msnbc.com",
"fbcdn-sphotos-f-a.akamaihd.net", "flic.kr", "instagram.com", "deviantart.com",
"s-media-cache-ak0.pinimg.com", "gfycat.com", "gifbeam.com", "staticflickr.com", "imgflip.com",
"upload.wikimedia.org", "livememe.com", "tumblr.com", "wikipedia.org", "archive.is", "imgrush.com",
"deviantart.net"];
};
var messages = {
error: {
aProblem : "There's been a problem!",
noImagesFound: "No images were found."
},
info: {
enterSubreddits: "Please enter your subreddits."
}
};
return{
approvedDomains: approvedDomains(),
messages: messages
};
})();
IRG.config = (function(){
})();
|
IRG.constants = (function(){
var approvedDomains = function(){
return ["imgur.com", "flickr.com", "cdn.diycozyhome.com", "pbs.twimg.com", "msnbc.com",
"fbcdn-sphotos-f-a.akamaihd.net", "flic.kr", "instagram.com", "deviantart.com",
"s-media-cache-ak0.pinimg.com", "gfycat.com", "gifbeam.com", "staticflickr.com", "imgflip.com",
"upload.wikimedia.org", "livememe.com", "tumblr.com", "wikipedia.org", "archive.is", "imgrush.com"];
};
var messages = {
error: {
aProblem : "There's been a problem!",
noImagesFound: "No images were found."
},
info: {
enterSubreddits: "Please enter your subreddits."
}
};
return{
approvedDomains: approvedDomains(),
messages: messages
};
})();
IRG.config = (function(){
})();
|
Fix typo: licence to license
|
import os
import re
from setuptools import setup
v = open(os.path.join(os.path.dirname(__file__), 'pynuodb', '__init__.py'))
VERSION = re.compile(r".*__version__ = '(.*?)'", re.S).match(v.read()).group(1)
v.close()
readme = os.path.join(os.path.dirname(__file__), 'README.rst')
setup(
name='pynuodb',
version=VERSION,
author='NuoDB',
author_email='info@nuodb.com',
description='NuoDB Python driver',
keywords='nuodb scalable cloud database',
packages=['pynuodb'],
package_dir={'pynuodb': 'pynuodb'},
url='https://github.com/nuodb/nuodb-python',
license='BSD License',
long_description=open(readme).read(),
install_requires=['pytz'],
)
|
import os
import re
from setuptools import setup
v = open(os.path.join(os.path.dirname(__file__), 'pynuodb', '__init__.py'))
VERSION = re.compile(r".*__version__ = '(.*?)'", re.S).match(v.read()).group(1)
v.close()
readme = os.path.join(os.path.dirname(__file__), 'README.rst')
setup(
name='pynuodb',
version=VERSION,
author='NuoDB',
author_email='info@nuodb.com',
description='NuoDB Python driver',
keywords='nuodb scalable cloud database',
packages=['pynuodb'],
package_dir={'pynuodb': 'pynuodb'},
url='https://github.com/nuodb/nuodb-python',
license='BSD Licence',
long_description=open(readme).read(),
install_requires=['pytz'],
)
|
Support Sort Order For TEXT Index
|
#!/bin/env python
#
# Copyright 2010 bit.ly
#
# 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.
"""
AsyncMongo is an asynchronous library for accessing mongo
http://github.com/bitly/asyncmongo
"""
try:
import bson
except ImportError:
raise ImportError("bson library not installed. Install pymongo >= 1.9 https://github.com/mongodb/mongo-python-driver")
# also update in setup.py
version = "1.3"
version_info = (1, 3)
ASCENDING = 1
"""Ascending sort order."""
DESCENDING = -1
"""Descending sort order."""
GEO2D = "2d"
"""Index specifier for a 2-dimensional `geospatial index`"""
TEXT = { $meta: "textScore" }
"""TEXT Index sort order."""
from errors import (Error, InterfaceError, AuthenticationError, DatabaseError, RSConnectionError,
DataError, IntegrityError, ProgrammingError, NotSupportedError)
from client import Client
|
#!/bin/env python
#
# Copyright 2010 bit.ly
#
# 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.
"""
AsyncMongo is an asynchronous library for accessing mongo
http://github.com/bitly/asyncmongo
"""
try:
import bson
except ImportError:
raise ImportError("bson library not installed. Install pymongo >= 1.9 https://github.com/mongodb/mongo-python-driver")
# also update in setup.py
version = "1.3"
version_info = (1, 3)
ASCENDING = 1
"""Ascending sort order."""
DESCENDING = -1
"""Descending sort order."""
GEO2D = "2d"
"""Index specifier for a 2-dimensional `geospatial index`"""
TEXT = '{ $meta: "textScore" }'
"""TEXT Index sort order."""
from errors import (Error, InterfaceError, AuthenticationError, DatabaseError, RSConnectionError,
DataError, IntegrityError, ProgrammingError, NotSupportedError)
from client import Client
|
Print a message when there's no ticket in db
|
<?php
namespace Djebbz\TicketBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Djebbz\TicketBundle\Model\TicketQuery;
class DefaultController extends Controller
{
public function indexAction()
{
return $this->render(
'DjebbzTicketBundle:Default:index.html.twig',
array('content' => 'Test content')
);
}
public function showAllTicketAction()
{
$tickets = TicketQuery::create()
->find();
if (!$tickets) {
throw $this->createNotFoundException(
'No tickets found.'
);
}
$message = '';
if (0 === count($tickets)) {
$message = 'Sorry, no tickets at all. Be the first to create one !';
}
return $this->render(
'DjebbzTicketBundle:Default:showAll.html.twig',
array(
'tickets' => $tickets,
'message' => $message,
)
);
}
}
|
<?php
namespace Djebbz\TicketBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Djebbz\TicketBundle\Model\TicketQuery;
class DefaultController extends Controller
{
public function indexAction()
{
return $this->render(
'DjebbzTicketBundle:Default:index.html.twig',
array('content' => 'Test content')
);
}
public function showAllTicketAction()
{
$tickets = TicketQuery::create()
->find();
if (!$tickets) {
throw $this->createNotFoundException(
'Sorry, no tickets found. You can create one !'
);
}
return $this->render(
'DjebbzTicketBundle:Default:showAll.html.twig',
array('tickets' => $tickets)
);
}
}
|
Add ability to render custom scripts in header
|
<?php
final class InternalPage implements Page, Linkable {
private $_header;
private $_title;
private $_filename;
private $_content;
private $_strapline;
public function __construct($title, $filename, PageContent $content, $strapline = '') {
$this->_header = new Header();
$this->_title = $title;
$this->_filename = $filename;
$this->_content = $content;
$this->_strapline = $strapline;
}
public function filename() {
return $this->_filename;
}
public function title() {
return $this->_title;
}
public function href($classes = '') {
return Link::internal($this->_title, $this->_filename)->withClasses($classes);
}
private function _renderContent() {
$this->_content->render($this);
}
public function render(Navigation $navigation) {
require 'template/page.phtml';
}
public function strapline() {
return $this->_strapline;
}
public function addScript($filename) {
$this->_header->addScript($filename);
}
}
|
<?php
final class InternalPage implements Page, Linkable {
private $_header;
private $_title;
private $_filename;
private $_content;
private $_strapline;
public function __construct($title, $filename, PageContent $content, $strapline = '') {
$this->_header = new Header();
$this->_title = $title;
$this->_filename = $filename;
$this->_content = $content;
$this->_strapline = $strapline;
}
public function filename() {
return $this->_filename;
}
public function title() {
return $this->_title;
}
public function href($classes = '') {
return Link::internal($this->_title, $this->_filename)->withClasses($classes);
}
private function _renderContent() {
$this->_content->render($this);
}
public function render(Navigation $navigation) {
require 'template/page.phtml';
}
public function strapline() {
return $this->_strapline;
}
}
|
Return all jobs for testing purposes
|
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
// Remove this after changes.
use App\User;
Route::get('/', function (){
return view('index');
});
Route::get('/support', function (){
return view('support');
})->name('support');
Route::get('/contact', function (){
return view('contact');
})->name('contact');
Auth::routes();
Route::get('/home', 'HomeController@index')->name('home');
Route::get('/profile', 'ProfileController@index')->name('profile');
Route::post('/delete', 'Auth\DeleteController@delete')->name('delete');
/* Example - Return all jobs in JSON format. */
Route::get('/all-jobs', function (){
return Job::all();
});
|
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
// Remove this after changes.
use App\User;
Route::get('/', function (){
return view('index');
});
Route::get('/support', function (){
return view('support');
})->name('support');
Route::get('/contact', function (){
return view('contact');
})->name('contact');
Auth::routes();
Route::get('/home', 'HomeController@index')->name('home');
Route::get('/profile', 'ProfileController@index')->name('profile');
Route::post('/delete', 'Auth\DeleteController@delete')->name('delete');
/* Example - Return all models in JSON format. */
Route::get('/matches', function (){
/* Obviously, we'll do this with Jobs. */
return User::all();
});
|
Set secret for creating and verifying jwt
|
'use strict';
const jwt = require('jsonwebtoken');
const dotenv = require('dotenv');
const secret = process.env.SECRET;
const auth = (req, res, next) => {
// Get the token for request
const token = req.body.token || req.headers['x-access-token'];
if (token) {
// TODO: reimplement secret for the application
jwt.verify(token, secret, (err, decoded) => {
if (err) {
return res.status(403).json({
success: false,
message: 'Invalid token'
});
} else {
req.decoded = decoded;
next();
}
});
} else {
return res.status(403).send({
success: false,
message: 'Token not provided'
});
}
};
module.exports = auth;
|
'use strict';
const jwt = require('jsonwebtoken');
const auth = (req, res, next) => {
// Get the token for request
const token = req.body.token || req.headers['x-access-token'];
if (token) {
// TODO: reimplement secret for the application
jwt.verify(token, 'superSecret', (err, decoded) => {
if (err) {
return res.status(403).json({
success: false,
message: 'Invalid token'
});
} else {
req.decoded = decoded;
next();
}
});
} else {
return res.status(403).send({
success: false,
message: 'Token not provided'
});
}
};
module.exports = auth;
|
Exit with error code `1` instead of `-1`
`-1` comes from Cobra docs...
|
// Cozy Cloud is a personal platform as a service with a focus on data.
// Cozy Cloud can be seen as 4 layers, from inside to outside:
//
// 1. A place to keep your personal data
//
// 2. A core API to handle the data
//
// 3. Your web apps, and also the mobile & desktop clients
//
// 4. A coherent User Experience
//
// It's also a set of values: Simple, Versatile, Yours. These values mean a lot
// for Cozy Cloud in all aspects. From an architectural point, it declines to:
//
// - Simple to deploy and understand, not built as a galaxy of optimized
// microservices managed by kubernetes that only experts can debug.
//
// - Versatile, can be hosted on a Raspberry Pi for geeks to massive scale on
// multiple servers by specialized hosting. Users can install apps.
//
// - Yours, you own your data and you control it. If you want to take back your
// data to go elsewhere, you can.
package main
import (
"fmt"
"os"
"github.com/cozy/cozy-stack/cmd"
)
func main() {
if err := cmd.RootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
|
// Cozy Cloud is a personal platform as a service with a focus on data.
// Cozy Cloud can be seen as 4 layers, from inside to outside:
//
// 1. A place to keep your personal data
//
// 2. A core API to handle the data
//
// 3. Your web apps, and also the mobile & desktop clients
//
// 4. A coherent User Experience
//
// It's also a set of values: Simple, Versatile, Yours. These values mean a lot
// for Cozy Cloud in all aspects. From an architectural point, it declines to:
//
// - Simple to deploy and understand, not built as a galaxy of optimized
// microservices managed by kubernetes that only experts can debug.
//
// - Versatile, can be hosted on a Raspberry Pi for geeks to massive scale on
// multiple servers by specialized hosting. Users can install apps.
//
// - Yours, you own your data and you control it. If you want to take back your
// data to go elsewhere, you can.
package main
import (
"fmt"
"os"
"github.com/cozy/cozy-stack/cmd"
)
func main() {
if err := cmd.RootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(-1)
}
}
|
Move reload doc before get query
|
# Copyright (c) 2017, Frappe and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
def execute():
frappe.reload_doc("stock", "doctype", "item_barcode")
items_barcode = frappe.get_all('Item', ['name', 'barcode'], { 'barcode': ('!=', '') })
frappe.reload_doc("stock", "doctype", "item")
for item in items_barcode:
barcode = item.barcode.strip()
if barcode and '<' not in barcode:
try:
frappe.get_doc({
'idx': 0,
'doctype': 'Item Barcode',
'barcode': barcode,
'parenttype': 'Item',
'parent': item.name,
'parentfield': 'barcodes'
}).insert()
except frappe.DuplicateEntryError:
continue
|
# Copyright (c) 2017, Frappe and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
def execute():
items_barcode = frappe.get_all('Item', ['name', 'barcode'], { 'barcode': ('!=', '') })
frappe.reload_doc("stock", "doctype", "item")
frappe.reload_doc("stock", "doctype", "item_barcode")
for item in items_barcode:
barcode = item.barcode.strip()
if barcode and '<' not in barcode:
try:
frappe.get_doc({
'idx': 0,
'doctype': 'Item Barcode',
'barcode': barcode,
'parenttype': 'Item',
'parent': item.name,
'parentfield': 'barcodes'
}).insert()
except frappe.DuplicateEntryError:
continue
|
Update cumulative flow chart, add average
|
'use strict';
var utils = require('../utils');
function createColumnsObj(lists) {
var columns = {};
for(var list in lists) {
lists[list].forEach(function(column) {
columns[column.name] = { duration: 0, cards: 0 };
});
}
return columns;
}
exports.cumulativeFlow = function(cards, lists) {
var columns = createColumnsObj(lists);
cards.forEach(function(card) {
var listName = utils.searchList(card.idList, lists);
if (listName === 'done') {
card.time.listTime.forEach(function(step) {
var listStep = utils.searchList(step.list.id, lists);
if (listStep !== 'done' && columns[step.list.name]) {
columns[step.list.name].duration += step.duration;
columns[step.list.name].cards ++;
}
});
}
});
var cumulativeFlow = [];
for (var column in columns) {
var current = {};
var average = columns[column].duration / columns[column].cards;
var duration = utils.getHumanReadableTime(average);
if (columns[column]) {
current = {
name: column,
data: [ duration.time ],
time: duration.format
};
cumulativeFlow.push(current);
}
}
return cumulativeFlow;
};
|
'use strict';
var utils = require('../utils');
function createColumnsObj(lists) {
var columns = {};
for(var list in lists) {
lists[list].forEach(function(column) {
columns[column.name] = 0;
});
}
return columns;
}
exports.cumulativeFlow = function(cards, lists) {
var columns = createColumnsObj(lists);
// TODO: Get Average
cards.forEach(function(card) {
var listName = utils.searchList(card.idList, lists);
if (listName === 'done') {
card.time.listTime.forEach(function(step) {
var listStep = utils.searchList(step.list.id, lists);
if (listStep !== 'done') {
columns[step.list.name] += step.duration;
}
});
}
});
var cumulativeFlow = [];
for (var column in columns) {
var current = {};
var duration = utils.getHumanReadableTime(columns[column]);
if (columns[column]) {
current = {
name: column,
data: [duration.time],
time: duration.format
};
cumulativeFlow.push(current);
}
}
return cumulativeFlow;
};
|
Test for DSU on Python
|
parent=[]
size=[]
def initialize(n):
for i in range(0,n+1):
parent.append(i)
size.append(1)
def find(x):
if parent[x] == x:
return x
else:
return find(parent[x])
def join(a,b):
p_a = find(a)
p_b = find(b)
if p_a != p_b:
if size[p_a] < size[p_b]:
parent[p_a] = p_b
size[p_b] += size[p_a]
else:
parent[p_b] = p_a
size[p_a] += size[p_b]
''' Main Program Starts Here '''
def main():
n=5
initialize(n)
join(1,2)
assert(find(2) == 1)
assert(find(3) == 3)
join(2,3)
assert(find(3) == 1)
assert(find(5) == 5)
join(4,5)
assert(find(5) == 4)
join(3,4)
assert(find(5) == 1)
if __name__ == '__main__':
main()
|
parent=[]
size=[]
def initialize(n):
for i in range(0,n+1):
parent.append(i)
size.append(1)
def find(x):
if parent[x] == x:
return x
else:
return find(parent[x])
def join(a,b):
p_a = find(a)
p_b = find(b)
if p_a != p_b:
if size[p_a] < size[p_b]:
parent[p_a] = p_b
size[p_b] += size[p_a]
else:
parent[p_b] = p_a
size[p_a] += size[p_b]
''' Main Program Starts Here '''
n=5
initialize(n)
join(1,2)
join(2,3)
join(4,5)
print(find(3))
|
Format Code Fights knapsack light problem
|
#!/usr/local/bin/python
# Code Fights Knapsack Problem
def knapsackLight(value1, weight1, value2, weight2, maxW):
if weight1 + weight2 <= maxW:
return value1 + value2
else:
return max([v for v, w in zip((value1, value2), (weight1, weight2))
if w <= maxW] + [0])
def main():
tests = [
[10, 5, 6, 4, 8, 10],
[]
]
for t in tests:
res = knapsackLight(t[0], t[1], t[2], t[3], t[4])
ans = t[5]
if ans == res:
print("PASSED: knapsackLight({}, {}, {}, {}, {}) returned {}"
.format(t[0], t[1], t[2], t[3], t[4], res))
else:
print(("FAILED: knapsackLight({}, {}, {}, {}, {}) returned {},"
"answer: {}")
.format(t[0], t[1], t[2], t[3], t[4], res, ans))
if __name__ == '__main__':
main()
|
#!/usr/local/bin/python
# Code Fights Knapsack Problem
def knapsackLight(value1, weight1, value2, weight2, maxW):
if weight1 + weight2 <= maxW:
return value1 + value2
else:
return max([v for v, w in zip((value1, value2), (weight1, weight2))
if w <= maxW] + [0])
def main():
tests = [
[]
]
for t in tests:
res = knapsackLight(t[0], t[1], t[2])
ans = t[3]
if ans == res:
print("PASSED: knapsackLight({}, {}, {}) returned {}"
.format(t[0], t[1], t[2], res))
else:
print(("FAILED: knapsackLight({}, {}, {}) returned {},"
"answer: {}").format(t[0], t[1], t[2], res, ans))
if __name__ == '__main__':
main()
|
Remove dankmemes subreddit in fetchContent
|
const getTop = require('./../../api/reddit-api').getTop;
const mySubreddits = [
'nottheonion',
'videos',
'funny',
'gifs',
'pics',
'gaming',
'aww',
'programmerhumor',
'crappydesign',
'upliftingnews',
'mildyinteresting',
'food'
];
function getRandomNumber(max){
return Math.floor(Math.random() * max);
}
function getRandomSubreddit(x = 3) {
let subredditList = [];
for (let i = 0; i < x ; i++) {
let randomNum = getRandomNumber(mySubreddits.length);
while (subredditList.includes(mySubreddits[randomNum])) {
randomNum = getRandomNumber(mySubreddits.length);
}
subredditList.push(mySubreddits[randomNum]);
}
return subredditList;
}
const fetchTopContents = async() => {
let list = getRandomSubreddit();
let getTopPromise = [];
let topContents = [];
for (let subreddit of list) {
getTopPromise.push(getTop(subreddit));
}
let contentRes = await Promise.all(getTopPromise);
for (let content of contentRes) {
topContents.push(content[getRandomNumber(content.length)]);
}
return topContents;
};
module.exports = fetchTopContents;
|
const getTop = require('./../../api/reddit-api').getTop;
const mySubreddits = [
'nottheonion',
'videos',
'funny',
'gifs',
'pics',
'gaming',
'aww',
'dankmemes',
'programmerhumor',
'crappydesign',
'upliftingnews',
'mildyinteresting',
'food'
];
function getRandomNumber(max){
return Math.floor(Math.random() * max);
}
function getRandomSubreddit(x = 3) {
let subredditList = [];
for (let i = 0; i < x ; i++) {
let randomNum = getRandomNumber(mySubreddits.length);
while (subredditList.includes(mySubreddits[randomNum])) {
randomNum = getRandomNumber(mySubreddits.length);
}
subredditList.push(mySubreddits[randomNum]);
}
return subredditList;
}
const fetchTopContents = async() => {
let list = getRandomSubreddit();
let getTopPromise = [];
let topContents = [];
for (let subreddit of list) {
getTopPromise.push(getTop(subreddit));
}
let contentRes = await Promise.all(getTopPromise);
for (let content of contentRes) {
topContents.push(content[getRandomNumber(content.length)]);
}
return topContents;
};
module.exports = fetchTopContents;
|
Add scope variable for current nav tab
|
angular.module('controllers', [])
.controller('NavCtrl', function ($scope, $state) {
$scope.state = $state.current.name
})
.controller('HomeCtrl', function ($scope, json) {
var data = json.data
var width = 200
var max = 5
var resizeTimer
$scope.resolution = 0
var size = function (callback) {
var number = Math.round($(window).width() / width)
if (number > max) number = max
$scope.resolution = number
if (arguments.length == 1) callback()
}
$scope.getColumns = function() {
return new Array($scope.resolution);
}
$scope.chunk = function (column, resolution) {
var round = -1
return data.slice(0).filter(function (x, i, a) {
round++
if (round >= resolution) round = 0
if (round == column) return true
})
}
size()
$(window).on('resize', function(e) {
clearTimeout(resizeTimer)
resizeTimer = setTimeout(size(function () {
$scope.$apply()
}), 250)
})
})
|
angular.module('controllers', [])
.controller('NavCtrl', function ($scope) {
})
.controller('HomeCtrl', function ($scope, json) {
var data = json.data
var width = 200
var max = 5
var resizeTimer
$scope.resolution = 0
var size = function (callback) {
var number = Math.round($(window).width() / width)
if (number > max) number = max
$scope.resolution = number
if (arguments.length == 1) callback()
}
$scope.getColumns = function() {
return new Array($scope.resolution);
}
$scope.chunk = function (column, resolution) {
var round = -1
return data.slice(0).filter(function (x, i, a) {
round++
if (round >= resolution) round = 0
if (round == column) return true
})
}
size()
$(window).on('resize', function(e) {
clearTimeout(resizeTimer)
resizeTimer = setTimeout(size(function () {
$scope.$apply()
}), 250)
})
})
|
Improve deserializer by normalizing ember models.
|
const emberModelType = function(model) {
var constructor = model.constructor.toString();
var match = constructor.match(/model:(.+):/);
if (!match || !match[1]) {throw `No model constructor found for ${constructor}`;}
return match[1];
};
const deserializeFromEmber = function(o, depth = 10) {
if(o && o.toJSON) {
const type = emberModelType(o);
return o.store && o.store.normalize ?
o.store.normalize(type, o.toJSON({includeId:true})) :
o.toJSON();
} else if (Array.isArray(o)) {
return o.reduce((acc, item) => {
acc.push(deserializeFromEmber(item, depth - 1));
return acc;
}, []);
} else if(o && o.then) {
return o.toString();
} else if (o instanceof Object) {
return Object.keys(o).reduce((acc, key) => {
var value = o.get ? o.get(key) : o[key];
acc[key] = depth > 0 ? deserializeFromEmber(value, depth - 1) : value;
return acc;
}, {});
} else {
return o;
}
};
export default deserializeFromEmber;
|
const deserializeFromEmber = function(o, depth = 10) {
if(o && o.toJSON) {
var constructor = o.get && o.get('constructor').toString();
return constructor ?
{'_constructor': constructor, json: o.toJSON({includeId:true})} :
o.toJSON();
} else if (Array.isArray(o)) {
return o.reduce((acc, item) => {
acc.push(deserializeFromEmber(item, depth - 1));
return acc;
}, []);
} else if(o && o.then) {
return o.toString();
} else if (o instanceof Object) {
return Object.keys(o).reduce((acc, key) => {
var value = o.get ? o.get(key) : o[key];
acc[key] = depth > 0 ? deserializeFromEmber(value, depth - 1) : value;
return acc;
}, {});
} else {
return o;
}
};
export default deserializeFromEmber;
|
Change website URL in Docker Safari test
|
/*
* (C) Copyright 2017 Boni Garcia (https://bonigarcia.github.io/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package io.github.bonigarcia.seljup.test.docker;
import static io.github.bonigarcia.seljup.BrowserType.SAFARI;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.openqa.selenium.WebDriver;
import io.github.bonigarcia.seljup.DockerBrowser;
import io.github.bonigarcia.seljup.SeleniumJupiter;
@ExtendWith(SeleniumJupiter.class)
class DockerSafariTest {
@Test
void testSafari(@DockerBrowser(type = SAFARI) WebDriver driver) {
driver.get("https://bonigarcia.dev/selenium-webdriver-java/");
assertThat(driver.getTitle()).contains("Selenium WebDriver");
}
}
|
/*
* (C) Copyright 2017 Boni Garcia (https://bonigarcia.github.io/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package io.github.bonigarcia.seljup.test.docker;
import static io.github.bonigarcia.seljup.BrowserType.SAFARI;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.openqa.selenium.WebDriver;
import io.github.bonigarcia.seljup.DockerBrowser;
import io.github.bonigarcia.seljup.SeleniumJupiter;
@ExtendWith(SeleniumJupiter.class)
class DockerSafariTest {
@Test
void testSafari(@DockerBrowser(type = SAFARI) WebDriver driver) {
driver.get("https://github.com/bonigarcia/selenium-webdriver-java");
assertThat(driver.getTitle()).contains("Selenium WebDriver");
}
}
|
Print task SID in output
|
# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
# Create a new task named 'tell_a_joke'
# Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list
task = client.preview.understand \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks \
.create(unique_name='tell-a-joke')
# Provide actions for the new task
joke_actions = {
'actions': [
{'say': 'I was going to look for my missing watch, but I could never find the time.'}
]
}
# Update the tell-a-joke task to use this 'say' action.
client.preview.understand \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks(task.sid) \
.task_actions().update(joke_actions)
print(task.sid)
|
# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
# Create a new task named 'tell_a_joke'
# Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list
task = client.preview.understand \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks \
.create(unique_name='tell-a-joke')
# Provide actions for the new task
joke_actions = {
'actions': [
{'say': 'I was going to look for my missing watch, but I could never find the time.'}
]
}
# Update the tell-a-joke task to use this 'say' action.
client.preview.understand \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks(task.sid) \
.task_actions().update(joke_actions)
print(intent.sid)
|
Fix typo when loading the SASL Handshake protocol
|
const requests = {
Produce: require('./produce'),
Fetch: {},
Offsets: {},
Metadata: require('./metadata'),
LeaderAndIsr: {},
StopReplica: {},
UpdateMetadata: {},
ControlledShutdown: {},
OffsetCommit: {},
OffsetFetch: {},
GroupCoordinator: {},
JoinGroup: {},
Heartbeat: {},
LeaveGroup: {},
SyncGroup: {},
DescribeGroups: {},
ListGroups: {},
SaslHandshake: require('./saslHandshake'),
ApiVersions: require('./apiVersions'),
CreateTopics: {},
DeleteTopics: {},
}
const lookup = versions => (apiKey, definition) => {
const version = versions[apiKey]
const bestImplementedVersion = Math.max.apply(this, definition.versions)
const bestSupportedVersion = Math.min(bestImplementedVersion, version.maxVersion)
return definition.protocol({ version: bestSupportedVersion })
}
module.exports = {
requests,
lookup,
}
|
const requests = {
Produce: require('./produce'),
Fetch: {},
Offsets: {},
Metadata: require('./metadata'),
LeaderAndIsr: {},
StopReplica: {},
UpdateMetadata: {},
ControlledShutdown: {},
OffsetCommit: {},
OffsetFetch: {},
GroupCoordinator: {},
JoinGroup: {},
Heartbeat: {},
LeaveGroup: {},
SyncGroup: {},
DescribeGroups: {},
ListGroups: {},
SaslHandshake: require('./saslhandshake'),
ApiVersions: require('./apiVersions'),
CreateTopics: {},
DeleteTopics: {},
}
const lookup = versions => (apiKey, definition) => {
const version = versions[apiKey]
const bestImplementedVersion = Math.max.apply(this, definition.versions)
const bestSupportedVersion = Math.min(bestImplementedVersion, version.maxVersion)
return definition.protocol({ version: bestSupportedVersion })
}
module.exports = {
requests,
lookup,
}
|
Read long description from README.
|
from distutils.core import setup
from os import path
from jeni import __version__
CLASSIFIERS = [
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Utilities',
'Topic :: Software Development :: Libraries :: Python Modules']
with open(path.join(path.dirname(__file__), 'README.txt')) as fd:
long_description = '\n' + fd.read()
setup(
name='jeni',
version=__version__,
url='https://github.com/rduplain/jeni-python',
license='BSD',
author='Ron DuPlain',
author_email='ron.duplain@gmail.com',
description='dependency aggregation',
long_description=long_description,
py_modules=['jeni'],
requires=[],
classifiers=CLASSIFIERS)
|
from distutils.core import setup
from jeni import __version__
CLASSIFIERS = [
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Utilities',
'Topic :: Software Development :: Libraries :: Python Modules']
setup(
name='jeni',
version=__version__,
url='https://github.com/rduplain/jeni-python',
license='BSD',
author='Ron DuPlain',
author_email='ron.duplain@gmail.com',
description='dependency aggregation',
py_modules=['jeni'],
requires=[],
classifiers=CLASSIFIERS)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.