text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Increment version number for updated pypi package | from setuptools import setup, find_packages
import os
version = '0.1.2'
LONG_DESCRIPTION = """
===============
django-helpdesk
===============
This is a Django-powered helpdesk ticket tracker, designed to
plug into an existing Django website and provide you with
internal (or, perhaps, external) helpdesk management.
"""
setup(
name='django-helpdesk',
version=version,
description="Django-powered ticket tracker for your helpdesk",
long_description=LONG_DESCRIPTION,
classifiers=[
"Programming Language :: Python",
"Topic :: Software Development :: Libraries :: Python Modules",
"Framework :: Django",
"Environment :: Web Environment",
"Operating System :: OS Independent",
"Intended Audience :: Customer Service",
"License :: OSI Approved :: BSD License",
"Natural Language :: English",
"Topic :: Office/Business",
"Topic :: Software Development :: Bug Tracking",
],
keywords=['django', 'helpdesk', 'tickets', 'incidents', 'cases'],
author='Ross Poulton',
author_email='ross@rossp.org',
url='http://github.com/rossp/django-helpdesk',
license='BSD',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=['setuptools'],
)
| from setuptools import setup, find_packages
import os
version = '0.1.1'
LONG_DESCRIPTION = """
===============
django-helpdesk
===============
This is a Django-powered helpdesk ticket tracker, designed to
plug into an existing Django website and provide you with
internal (or, perhaps, external) helpdesk management.
"""
setup(
name='django-helpdesk',
version=version,
description="Django-powered ticket tracker for your helpdesk",
long_description=LONG_DESCRIPTION,
classifiers=[
"Programming Language :: Python",
"Topic :: Software Development :: Libraries :: Python Modules",
"Framework :: Django",
"Environment :: Web Environment",
"Operating System :: OS Independent",
"Intended Audience :: Customer Service",
"License :: OSI Approved :: BSD License",
"Natural Language :: English",
"Topic :: Office/Business",
"Topic :: Software Development :: Bug Tracking",
],
keywords=['django', 'helpdesk', 'tickets', 'incidents', 'cases'],
author='Ross Poulton',
author_email='ross@rossp.org',
url='http://github.com/rossp/django-helpdesk',
license='BSD',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=['setuptools'],
)
|
Check the controller variable rather than argument | HighFidelity.PodcastNewController = Ember.ObjectController.extend({
isAdding: false,
rssURL: '',
actions: {
create: function(url) {
if (url) {
this.set('rssURL', url);
}
if (!this.get('rssURL') || !this.get('rssURL').length) {
return;
}
// If the URL entered doesn't have a protocol attached, make
// sure one is added so we don't get an error (#43).
if (!this.get('rssURL').match(/^http[s]?:\/\//i)) {
this.set('rssURL', 'http://' + this.get('rssURL'));
}
this.set('isAdding', true);
HighFidelity.Podcast.createFromController(this, this.get('rssURL'));
}
}
});
| HighFidelity.PodcastNewController = Ember.ObjectController.extend({
isAdding: false,
rssURL: '',
actions: {
create: function(url) {
if (url) {
if (!url.match(/^http[s]?:\/\//i)) {
url = 'http://' + url;
}
this.set('rssURL', url);
}
if (!this.get('rssURL') || !this.get('rssURL').length) {
return;
}
this.set('isAdding', true);
HighFidelity.Podcast.createFromController(this, this.get('rssURL'));
}
}
});
|
Optimize memory consumption of Amp\ByteStream\pipe | <?php
namespace Amp\ByteStream;
use Amp\Promise;
use function Amp\call;
// @codeCoverageIgnoreStart
if (\strlen('…') !== 3) {
throw new \Error(
'The mbstring.func_overload ini setting is enabled. It must be disabled to use the stream package.'
);
} // @codeCoverageIgnoreEnd
/**
* @param \Amp\ByteStream\InputStream $source
* @param \Amp\ByteStream\OutputStream $destination
*
* @return \Amp\Promise
*/
function pipe(InputStream $source, OutputStream $destination): Promise {
return call(function () use ($source, $destination): \Generator {
$written = 0;
while (($chunk = yield $source->read()) !== null) {
$written += \strlen($chunk);
$writePromise = $destination->write($chunk);
$chunk = null; // free memory
yield $writePromise;
}
return $written;
});
}
| <?php
namespace Amp\ByteStream;
use Amp\Promise;
use function Amp\call;
// @codeCoverageIgnoreStart
if (\strlen('…') !== 3) {
throw new \Error(
'The mbstring.func_overload ini setting is enabled. It must be disabled to use the stream package.'
);
} // @codeCoverageIgnoreEnd
/**
* @param \Amp\ByteStream\InputStream $source
* @param \Amp\ByteStream\OutputStream $destination
*
* @return \Amp\Promise
*/
function pipe(InputStream $source, OutputStream $destination): Promise {
return call(function () use ($source, $destination): \Generator {
$written = 0;
while (($chunk = yield $source->read()) !== null) {
$written += \strlen($chunk);
yield $destination->write($chunk);
}
return $written;
});
}
|
Fix for not showing all reports on backslash | Session.setDefault('searchBy', 'Navn');
Session.setDefault('searchQuery', '');
Template.Search.events({
'click .dropdown-menu li': function(event, tmpl) {
var chosenAttribute = $(event.currentTarget).text();
Session.set('searchBy', chosenAttribute);
Session.set('query', {});
Session.set('searchQuery', '');
},
'keyup [type="text"]': function(event, template) {
//escape regex
var value = event.target.value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
var field = attToField(Session.get('searchBy'));
var query = {};
//if number, use equals operator
if(!isNaN(parseInt(value))) {
query[field] = parseInt(value);
}
//if string, use contains operator with regex
else {
query[field] = { $regex: value, $options: 'i' };
}
//if the searchbox is empty we have to reset the query
if(value == null || value == "")
query = {};
//this triggers iron router to load the report subscription again
Session.set('query', query);
Session.set('searchQuery', value);
}
});
| Session.setDefault('searchBy', 'Navn');
Session.setDefault('searchQuery', '');
Template.Search.events({
'click .dropdown-menu li': function(event, tmpl) {
var chosenAttribute = $(event.currentTarget).text();
Session.set('searchBy', chosenAttribute);
Session.set('query', {});
Session.set('searchQuery', '');
},
'keyup [type="text"]': function(event, template) {
//escape regex
var value = event.target.value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
var field = attToField(Session.get('searchBy'));
var query = {};
//if number, use equals operator
if(!isNaN(parseInt(value))) {
query[field] = parseInt(value);
}
//if string, use contains operator with regex
else {
query[field] = { $regex: value, $options: 'i' };
}
//this triggers iron router to load the report subscription again
Session.set('query', query);
Session.set('searchQuery', value);
}
});
|
Add back css for JLab plugin. | /* Copyright 2015 Bloomberg Finance L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.
*/
var bqplot = require('bqplot');
require("bqplot/css/bqplot.css");
var jupyterlab_widgets = require('@jupyterlab/nbwidgets');
/**
* The widget manager provider.
*/
module.exports.default = {
id: 'jupyter.extensions.bqplot',
requires: [jupyterlab_widgets.INBWidgetExtension],
activate: function(app, widgets) {
widgets.registerWidget({
name: 'bqplot',
version: bqplot.version,
exports: bqplot
});
},
autoStart: true
};
| /* Copyright 2015 Bloomberg Finance L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.
*/
var bqplot = require('bqplot');
var jupyterlab_widgets = require('@jupyterlab/nbwidgets');
/**
* The widget manager provider.
*/
module.exports.default = {
id: 'jupyter.extensions.bqplot',
requires: [jupyterlab_widgets.INBWidgetExtension],
activate: function(app, widgets) {
widgets.registerWidget({
name: 'bqplot',
version: bqplot.version,
exports: bqplot
});
},
autoStart: true
};
|
Use parentWindow instead of createWindow() in these tests. | "use strict";
var jsdom = require("../..").jsdom;
exports["should put errors in the window.document.errors array"] = function (t) {
var window = jsdom("<!DOCTYPE html><html><body>Hi</body></html>").parentWindow;
window.console.log("foo");
window.console.info("bar");
window.console.warn("baz");
window.console.error("qux");
t.deepEqual(window.document.errors, [{ type: "error", message: "qux", data: null }]);
t.done();
};
exports["should send errors to the correct window when multiple are in play (GH-658)"] = function (t) {
var window1 = jsdom("<!DOCTYPE html><html><body>Hi</body></html>").parentWindow;
var window2 = jsdom("<!DOCTYPE html><html><body>Hi</body></html>").parentWindow;
window1.console.error("foo");
window2.console.error("bar");
t.notEqual(window1.console, window2.console);
t.deepEqual(window1.document.errors, [{ type: "error", message: "foo", data: null }]);
t.deepEqual(window2.document.errors, [{ type: "error", message: "bar", data: null }]);
t.done();
};
| "use strict";
var jsdom = require("../..").jsdom;
exports["should put errors in the window.document.errors array"] = function (t) {
var window = jsdom("<!DOCTYPE html><html><body>Hi</body></html>").createWindow();
window.console.log("foo");
window.console.info("bar");
window.console.warn("baz");
window.console.error("qux");
t.deepEqual(window.document.errors, [{ type: "error", message: "qux", data: null }]);
t.done();
};
exports["should send errors to the correct window when multiple are in play (GH-658)"] = function (t) {
var window1 = jsdom("<!DOCTYPE html><html><body>Hi</body></html>").createWindow();
var window2 = jsdom("<!DOCTYPE html><html><body>Hi</body></html>").createWindow();
window1.console.error("foo");
window2.console.error("bar");
t.notEqual(window1.console, window2.console);
t.deepEqual(window1.document.errors, [{ type: "error", message: "foo", data: null }]);
t.deepEqual(window2.document.errors, [{ type: "error", message: "bar", data: null }]);
t.done();
};
|
BENCH: Make the pad benchmark pagefault in setup | """Benchmarks for `numpy.lib`."""
from __future__ import absolute_import, division, print_function
from .common import Benchmark
import numpy as np
class Pad(Benchmark):
"""Benchmarks for `numpy.pad`."""
param_names = ["shape", "pad_width", "mode"]
params = [
[(1000,),
(10, 100),
(10, 10, 10),
# 50 * 512 * 512 = 13 million points = 46 MB. should be a good
# out of cache describing a typical usecase
(50, 512, 512)],
[1,
3,
(0, 5)],
["constant",
"edge", "linear_ramp",
# mean/median/minimum/maximum all use the same code path
"mean",
# reflect/symmetric share alot of the code path
"reflect",
"wrap"],
]
def setup(self, shape, pad_width, mode):
# Make sure to fill the array to make the OS page fault
# in the setup phase and not the timed phase
self.array = np.full(shape, fill_value=1)
def time_pad(self, shape, pad_width, mode):
np.pad(self.array, pad_width, mode)
| """Benchmarks for `numpy.lib`."""
from __future__ import absolute_import, division, print_function
from .common import Benchmark
import numpy as np
class Pad(Benchmark):
"""Benchmarks for `numpy.pad`."""
param_names = ["shape", "pad_width", "mode"]
params = [
[(1000,), (10, 100), (10, 10, 10)],
[1, 3, (0, 5)],
["constant", "edge", "linear_ramp", "mean", "reflect", "wrap"],
]
def setup(self, shape, pad_width, mode):
# avoid np.zeros or np.empty's lazy allocation.
# np.full causes pagefaults to occur during setup
# instead of during the benchmark
self.array = np.full(shape, 0)
def time_pad(self, shape, pad_width, mode):
np.pad(self.array, pad_width, mode)
|
Use var declaration with `for...in` loop
If you do not include a var (or let) then `param` used by for...in will
be consider undefined:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in | import BaseStore from 'stores/BaseStore';
import SizeCollection from 'collections/SizeCollection';
let SizeStore = BaseStore.extend({
collection: SizeCollection,
queryParams: {
page_size: 100
}
});
SizeStore.prototype.filterWhereGreaterThanOrEqualTo = function(params) {
let results = [],
shouldAdd;
this.models.each(function(model) {
shouldAdd = true;
for (var param in params) {
if (model.get(param) < params[param]) {
shouldAdd = false;
}
}
if (shouldAdd) {
results.push(model);
}
});
return results;
}
let store = new SizeStore();
export default store;
| import BaseStore from 'stores/BaseStore';
import SizeCollection from 'collections/SizeCollection';
let SizeStore = BaseStore.extend({
collection: SizeCollection,
queryParams: {
page_size: 100
}
});
SizeStore.prototype.filterWhereGreaterThanOrEqualTo = function(params) {
let results = [],
shouldAdd;
this.models.each(function(model) {
shouldAdd = true;
for (param in params) {
if (model.get(param) < params[param]) {
shouldAdd = false;
}
}
if (shouldAdd) {
results.push(model);
}
});
return results;
}
let store = new SizeStore();
export default store;
|
Remove the modules repo from the source command | package heufybot.modules;
import java.util.List;
public class Source extends Module
{
public Source(String server)
{
super(server);
this.authType = AuthType.Anyone;
this.apiVersion = 60;
this.triggerTypes = new TriggerType[] { TriggerType.Message };
this.trigger = "^" + commandPrefix + "(source)$";
}
@Override
public void processEvent(String source, String message, String triggerUser, List<String> params)
{
bot.getServer(server).cmdPRIVMSG(source, "https://github.com/Heufneutje/RE_HeufyBot");
}
public String getHelp(String message)
{
return "Commands: " + commandPrefix + "source | Provides a link to the bot's source code.";
}
@Override
public void onLoad()
{
}
@Override
public void onUnload()
{
}
}
| package heufybot.modules;
import java.util.List;
public class Source extends Module
{
public Source(String server)
{
super(server);
this.authType = AuthType.Anyone;
this.apiVersion = 60;
this.triggerTypes = new TriggerType[] { TriggerType.Message };
this.trigger = "^" + commandPrefix + "(source)$";
}
@Override
public void processEvent(String source, String message, String triggerUser, List<String> params)
{
bot.getServer(server).cmdPRIVMSG(source, "https://github.com/Heufneutje/RE_HeufyBot/ | https://github" +
".com/Heufneutje/RE_HeufyBot-AdditionalModules");
}
public String getHelp(String message)
{
return "Commands: " + commandPrefix + "source | Provides a link to the bot's source code.";
}
@Override
public void onLoad()
{
}
@Override
public void onUnload()
{
}
}
|
Change to run with PowerMockRunner | // Copyright 2019 Google LLC
//
// 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
//
// https://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.sps;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@SuppressStaticInitializationFor({"com.google.sps.Firebase"})
public final class FirebaseTest {
@Test
public void userLoggedIn() throws IOException {
boolean result = Firebase.isUserLoggedIn("test");
assertEquals(true, result);
}
@Test
public void userLoggedInEmpty() throws IOException {
boolean result = Firebase.isUserLoggedIn("");
assertEquals(false, result);
}
}
| // Copyright 2019 Google LLC
//
// 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
//
// https://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.sps;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;
@RunWith(JUnit4.class)
@SuppressStaticInitializationFor({"com.google.sps.Firebase"})
public final class FirebaseTest {
@Test
public void userLoggedIn() throws IOException {
boolean result = Firebase.isUserLoggedIn("test");
assertEquals(true, result);
}
@Test
public void userLoggedInEmpty() throws IOException {
boolean result = Firebase.isUserLoggedIn("");
assertEquals(false, result);
}
}
|
Rename constant for enabling app | /**
* App constants
*/
export default {
CHANGE_EVENT: 'CHANGE_EVENT',
SWITCH_VIEW: 'SWITCH_VIEW',
GET_CONFIGURATION: 'GET_CONFIGURATION',
SAVE_CONFIGURATION: 'SAVE_CONFIGURATION',
ADD_FIELD: 'ADD_FIELD',
REMOVE_FIELD: 'REMOVE_FIELD',
ADD_INPUT_VALUE: 'ADD_INPUT_VALUE',
ADD_IGNORED_STYLESHEET: 'ADD_IGNORED_STYLESHEET',
TOGGLE_ENABLE: 'TOGGLE_ENABLE',
SET_AUTO_UPDATE: 'SET_AUTO_UPDATE',
SET_UPDATE_FREQUENCY: 'SET_UPDATE_FREQUENCY',
APPLY_CONFIGURATION: 'APPLY_CONFIGURATION',
GET_ORIGINAL_STYLESHEETS: 'GET_ORIGINAL_STYLESHEETS'
}
| /**
* App constants
*/
export default {
CHANGE_EVENT: 'CHANGE_EVENT',
SWITCH_VIEW: 'SWITCH_VIEW',
GET_CONFIGURATION: 'GET_CONFIGURATION',
SAVE_CONFIGURATION: 'SAVE_CONFIGURATION',
ADD_FIELD: 'ADD_FIELD',
REMOVE_FIELD: 'REMOVE_FIELD',
ADD_INPUT_VALUE: 'ADD_INPUT_VALUE',
ADD_IGNORED_STYLESHEET: 'ADD_IGNORED_STYLESHEET',
SET_ENABLE: 'SET_ENABLE',
SET_AUTO_UPDATE: 'SET_AUTO_UPDATE',
SET_UPDATE_FREQUENCY: 'SET_UPDATE_FREQUENCY',
APPLY_CONFIGURATION: 'APPLY_CONFIGURATION',
GET_ORIGINAL_STYLESHEETS: 'GET_ORIGINAL_STYLESHEETS'
}
|
Add created_at DateTimeField to Twitter example | import json
from urllib2 import urlopen
import micromodels
class TwitterUser(micromodels.Model):
id = micromodels.IntegerField()
screen_name = micromodels.CharField()
name = micromodels.CharField()
description = micromodels.CharField()
def get_profile_url(self):
return 'http://twitter.com/%s' % self.screen_name
class Tweet(micromodels.Model):
id = micromodels.IntegerField()
text = micromodels.CharField()
created_at = micromodels.DateTimeField(format="%a %b %d %H:%M:%S +0000 %Y")
user = micromodels.ModelField(TwitterUser)
json_data = urlopen('http://api.twitter.com/1/statuses/show/20.json').read()
tweet = Tweet(json.loads(json_data))
print "Tweet was posted by %s (%s) on a %s" % (
tweet.user.name,
tweet.user.get_profile_url(),
tweet.created_at.strftime("%A")
)
| import json
from urllib2 import urlopen
import micromodels
class TwitterUser(micromodels.Model):
id = micromodels.IntegerField()
screen_name = micromodels.CharField()
name = micromodels.CharField()
description = micromodels.CharField()
def get_profile_url(self):
return 'http://twitter.com/%s' % self.screen_name
class Tweet(micromodels.Model):
id = micromodels.IntegerField()
text = micromodels.CharField()
user = micromodels.ModelField(TwitterUser)
json_data = urlopen('http://api.twitter.com/1/statuses/show/20.json').read()
tweet = Tweet(json.loads(json_data))
print "Tweet was posted by %s (%s)" % (tweet.user.name, tweet.user.get_profile_url())
|
Fix name for md5 test | <?php
/**
* This file is part of the Imbo package
*
* (c) Christer Edvartsen <cogo@starzinger.net>
*
* For the full copyright and license information, please view the LICENSE file that was
* distributed with this source code.
*/
namespace ImboUnitTest\Image\Identifier\Generator;
use Imbo\Image\Identifier\Generator\Md5 as Md5Generator,
ImagickException;
/**
* @covers Imbo\Image\Identifier\Generator\Md5
* @group unit
*/
class Md5Test extends \PHPUnit_Framework_TestCase {
public function testGeneratesCorrectMd5ForBlob() {
$image = $this->getMock('Imbo\Model\Image');
$image->expects($this->any())->method('getBlob')->will($this->returnValue('foobar'));
$generator = new Md5Generator();
// Make sure it generates the same MD5 every time
for ($i = 0; $i < 15; $i++) {
$imageIdentifier = $generator->generate($image);
$this->assertSame(md5('foobar'), $imageIdentifier);
}
}
}
| <?php
/**
* This file is part of the Imbo package
*
* (c) Christer Edvartsen <cogo@starzinger.net>
*
* For the full copyright and license information, please view the LICENSE file that was
* distributed with this source code.
*/
namespace ImboUnitTest\Image\Identifier\Generator;
use Imbo\Image\Identifier\Generator\Md5 as Md5Generator,
ImagickException;
/**
* @covers Imbo\Image\Identifier\Generator\Md5
* @group unit
*/
class Md5Test extends \PHPUnit_Framework_TestCase {
public function testGeneratesUniqueUuidV4() {
$image = $this->getMock('Imbo\Model\Image');
$image->expects($this->any())->method('getBlob')->will($this->returnValue('foobar'));
$generator = new Md5Generator();
// Make sure it generates the same MD5 every time
for ($i = 0; $i < 15; $i++) {
$imageIdentifier = $generator->generate($image);
$this->assertSame(md5('foobar'), $imageIdentifier);
}
}
}
|
Upgrade Localstack image to 0.12.6 for SQS too | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.test.infra.aws2.services;
public class AWSSQSLocalContainerService extends AWSLocalContainerService {
public AWSSQSLocalContainerService() {
super("localstack/localstack:0.12.6", Service.SQS);
}
}
| /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.test.infra.aws2.services;
public class AWSSQSLocalContainerService extends AWSLocalContainerService {
public AWSSQSLocalContainerService() {
super("localstack/localstack:0.12.5", Service.SQS);
}
}
|
Fix for templates in es6 | angular.module('ladda-lw', ['ngAnimate']).directive('ladda', function laddaDirective() {
return {
restrict: 'A',
scope: {
ladda: '=',
},
compile: (element, attrs) => {
const lLoading = attrs.ladda;
element.addClass('ladda-lw');
const textWrap = angular.element(`
<div class="ladda-lw__text"
ng-class="{'ladda-lw__text--up': ${lLoading}}">
</div>
`);
textWrap.append(element.contents());
element.append(textWrap);
const loadingWrap = angular.element(`<div class="ladda-lw__loading-wrap"></div>`);
const loading = angular.element(`
<div class="ladda-lw__loading"
ng-class="{'ladda-lw__loading--up': ${lLoading}}">
</div>
`);
loadingWrap.append(loading);
element.append(loadingWrap);
return function link(scope, iElement) {
scope.$watch('ladda', function laddaWatch(l) {
iElement.attr('disabled', l ? 'disabled' : false);
});
};
},
};
});
| angular.module('ladda-lw', ['ngAnimate']).directive('ladda', function laddaDirective() {
return {
restrict: 'A',
scope: {
ladda: '=',
},
compile: (element, attrs) => {
const lLoading = attrs.ladda;
element.addClass('ladda-lw');
const textWrap = angular.element(`
<div class="ladda-lw__text"
ng-class="{\'ladda-lw__text--up\': ' + lLoading + '}">
</div>
`);
textWrap.append(element.contents());
element.append(textWrap);
const loadingWrap = angular.element('<div class="ladda-lw__loading-wrap"></div>');
const loading = angular.element('<div class="ladda-lw__loading" ng-class="{\'ladda-lw__loading--up\': ' + lLoading + '}"></div>');
loadingWrap.append(loading);
element.append(loadingWrap);
return function link(scope, iElement) {
scope.$watch('ladda', function laddaWatch(l) {
iElement.attr('disabled', l ? 'disabled' : false);
});
};
},
};
});
|
Set better code indentation (more readable) | <?php
/**
* @author Pierre-Henry Soria <ph7software@gmail.com>
* @copyright (c) 2012-2017, 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 / App / System / Module / User / Inc / Class
*/
namespace PH7;
use PH7\Framework\Cookie\Cookie;
use PH7\Framework\Mvc\Router\Uri;
use PH7\Framework\Session\Session;
use PH7\Framework\Url\Header;
class User extends UserCore
{
/**
* Logout function for users.
*
* @return void
*/
public function logout()
{
(new Session)->destroy();
$oCookie = new Cookie; // If "Remember Me" checkbox has been checked
$aRememberMeCookies = ['member_remember', 'member_id'];
if ($oCookie->exists($aRememberMeCookies)) {
$oCookie->remove($aRememberMeCookies);
}
Header::redirect(
Uri::get('user','main','soon'),
t('You are now logged out. Hope to see you again very soon!')
);
}
}
| <?php
/**
* @author Pierre-Henry Soria <ph7software@gmail.com>
* @copyright (c) 2012-2017, 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 / App / System / Module / User / Inc / Class
*/
namespace PH7;
use PH7\Framework\Cookie\Cookie;
use PH7\Framework\Mvc\Router\Uri;
use PH7\Framework\Session\Session;
use PH7\Framework\Url\Header;
class User extends UserCore
{
/**
* Logout function for users.
*
* @return void
*/
public function logout()
{
(new Session)->destroy();
$oCookie = new Cookie; // If "Remember Me" checkbox has been checked
$aRememberMeCookies = ['member_remember', 'member_id'];
if ($oCookie->exists($aRememberMeCookies)) {
$oCookie->remove($aRememberMeCookies);
}
Header::redirect(Uri::get('user','main','soon'), t('You are now logged out. Hope to see you again very soon!'));
}
}
|
Update <Text> tests so they are not as particular about browser differences | import ReactDOM from 'react-dom';
import React from 'react';
import { shallow, render } from 'enzyme';
import { expect } from 'chai';
import { Text } from 'recharts';
describe('<Text />', () => {
it('Does not wrap long text if enough width', () => {
const wrapper = shallow(
<Text width={200}>This is really long text</Text>
);
expect(wrapper.instance().state.wordsByLines.length).to.equal(1);
});
it('Wraps long text if not enough width', () => {
const wrapper = shallow(
<Text width={100}>This is really long text</Text>
);
expect(wrapper.instance().state.wordsByLines.length).to.equal(2);
});
it('Wraps long text if styled and not enough room', () => {
const wrapper = shallow(
<Text width={200} style={{ fontSize: '2em' }}>This is really long text</Text>
);
expect(wrapper.instance().state.wordsByLines.length).to.equal(2);
});
it('Does not perform word length calculation if width or fit props not set', () => {
const wrapper = shallow(
<Text>This is really long text</Text>
);
expect(wrapper.instance().state.wordsByLines.length).to.equal(1);
expect(wrapper.instance().state.wordsByLines[0].width).to.equal(undefined);
});
});
| import ReactDOM from 'react-dom';
import React from 'react';
import { shallow, render } from 'enzyme';
import { expect } from 'chai';
import { Text } from 'recharts';
describe('<Text />', () => {
it('Does not wrap long text if enough width', () => {
const wrapper = shallow(
<Text width={144}>This is really long text</Text>
);
expect(wrapper.instance().state.wordsByLines.length).to.equal(1);
});
it('Wraps long text if not enough width', () => {
const wrapper = shallow(
<Text width={143}>This is really long text</Text>
);
expect(wrapper.instance().state.wordsByLines.length).to.equal(2);
});
it('Wraps long text if styled and not enough room', () => {
const wrapper = shallow(
<Text width={144} style={{ fontWeight: 900 }}>This is really long text</Text>
);
expect(wrapper.instance().state.wordsByLines.length).to.equal(2);
});
it('Does not perform word length calculation if width or fit props not set', () => {
const wrapper = shallow(
<Text>This is really long text</Text>
);
expect(wrapper.instance().state.wordsByLines.length).to.equal(1);
expect(wrapper.instance().state.wordsByLines[0].width).to.equal(undefined);
});
});
|
Fix for chaos security warning CVE-2019-1010083 | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='Flask-RESTful',
version='0.2.5',
url='https://www.github.com/twilio/flask-restful/',
author='Kyle Conroy',
author_email='help@twilio.com',
description='Simple framework for creating REST APIs',
packages=find_packages(),
zip_safe=False,
include_package_data=True,
platforms='any',
test_suite = 'nose.collector',
#setup_requires=[
# 'nose==1.3.1',
# 'mock==1.0.1',
# 'six==1.5.2',
# 'blinker==1.3',
#],
install_requires=[
'Flask==1.0',
],
# Install these with "pip install -e '.[paging]'" or '.[docs]'
extras_require={
'paging': 'pycrypto>=2.6',
'docs': 'sphinx',
}
)
| #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='Flask-RESTful',
version='0.2.5',
url='https://www.github.com/twilio/flask-restful/',
author='Kyle Conroy',
author_email='help@twilio.com',
description='Simple framework for creating REST APIs',
packages=find_packages(),
zip_safe=False,
include_package_data=True,
platforms='any',
test_suite = 'nose.collector',
#setup_requires=[
# 'nose==1.3.1',
# 'mock==1.0.1',
# 'six==1.5.2',
# 'blinker==1.3',
#],
install_requires=[
'Flask==0.12.3',
],
# Install these with "pip install -e '.[paging]'" or '.[docs]'
extras_require={
'paging': 'pycrypto>=2.6',
'docs': 'sphinx',
}
)
|
Add Pause keycode for androidtv remote | if (navigator.userAgent.indexOf('Android') >= 0) {
log = console.log.bind(console)
log("Android detected")
exports.core.vendor = "google"
exports.core.device = 2
exports.core.os = "android"
exports.core.keyCodes = {
4: 'Back',
13: 'Select',
27: 'Back',
37: 'Left',
32: 'Space',
38: 'Up',
39: 'Right',
40: 'Down',
48: '0',
49: '1',
50: '2',
51: '3',
52: '4',
53: '5',
54: '6',
55: '7',
56: '8',
57: '9',
179: 'Pause',
112: 'Red',
113: 'Green',
114: 'Yellow',
115: 'Blue'
}
if (window.cordova) {
document.addEventListener("backbutton", function(e) {
var event = new KeyboardEvent("keydown", { bubbles : true });
Object.defineProperty(event, 'keyCode', { get : function() { return 27; } })
document.dispatchEvent(event);
}, false);
} else {
log("'cordova' not defined. 'Back' button will be unhandable. It looks like you forget to include 'cordova.js'")
}
log("Android initialized")
}
| if (navigator.userAgent.indexOf('Android') >= 0) {
log = console.log.bind(console)
log("Android detected")
exports.core.vendor = "google"
exports.core.device = 2
exports.core.os = "android"
exports.core.keyCodes = {
4: 'Back',
13: 'Select',
27: 'Back',
37: 'Left',
32: 'Space',
38: 'Up',
39: 'Right',
40: 'Down',
48: '0',
49: '1',
50: '2',
51: '3',
52: '4',
53: '5',
54: '6',
55: '7',
56: '8',
57: '9',
112: 'Red',
113: 'Green',
114: 'Yellow',
115: 'Blue'
}
if (window.cordova) {
document.addEventListener("backbutton", function(e) {
var event = new KeyboardEvent("keydown", { bubbles : true });
Object.defineProperty(event, 'keyCode', { get : function() { return 27; } })
document.dispatchEvent(event);
}, false);
} else {
log("'cordova' not defined. 'Back' button will be unhandable. It looks like you forget to include 'cordova.js'")
}
log("Android initialized")
}
|
Use logback to print job messages | package org.daisy.maven.xproc.pipeline;
import com.google.common.eventbus.Subscribe;
import org.daisy.common.messaging.Message;
import org.daisy.pipeline.event.EventBusProvider;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Component
public class MessageEventListener {
@Reference(
name = "EventBusProvider",
unbind = "-",
service = EventBusProvider.class,
cardinality = ReferenceCardinality.MANDATORY,
policy = ReferencePolicy.STATIC
)
public void setEventBusProvider(EventBusProvider provider) {
provider.get().register(this);
}
@Subscribe
public synchronized void handleMessage(Message message) {
String m = message.getText();
switch (message.getLevel()) {
case TRACE:
logger.trace(m);
break;
case DEBUG:
logger.debug(m);
break;
case INFO:
logger.info(m);
break;
case WARNING:
logger.warn(m);
break;
case ERROR:
logger.error(m);
break; }
}
private static final Logger logger = LoggerFactory.getLogger(MessageEventListener.class);
}
| package org.daisy.maven.xproc.pipeline;
import com.google.common.eventbus.Subscribe;
import org.daisy.common.messaging.Message;
import org.daisy.pipeline.event.EventBusProvider;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
@Component
public class MessageEventListener {
@Reference(
name = "EventBusProvider",
unbind = "-",
service = EventBusProvider.class,
cardinality = ReferenceCardinality.MANDATORY,
policy = ReferencePolicy.STATIC
)
public void setEventBusProvider(EventBusProvider provider) {
provider.get().register(this);
}
@Subscribe
public synchronized void handleMessage(Message message) {
System.out.printf("[%s] %s\n", message.getLevel(), message.getText());
}
}
|
Add support for escaping placeholders. | var syntax = /\{\{([\w\-]+)\}\}/g;
var syntaxCleanup = /((?:[\r\n])*)\{\{([\w\-]+)\}\}((?:[\r\n])*)/g;
var syntaxUnescape = /\\\{\\\{([\w\-]+)\\\}\\\}/g;
module.exports = function (template, replacements, cleanup) {
var interpolated;
if (cleanup) {
interpolated = template.replace(syntaxCleanup, function (match, leadingSpaces, prop, trailingSpaces) {
var replacement = (prop in replacements) ? replacements[prop] : '{{' + match + '}}';
return leadingSpaces.length ? replacement + trailingSpaces : leadingSpaces + replacement;
});
} else {
interpolated = template.replace(syntax, function (match, prop) {
return (prop in replacements) ? replacements[prop] : match;
});
}
// Escaped chars should be unescaped
return interpolated.replace(syntaxUnescape, '{{$1}}');
};
module.exports.syntax = syntax;
module.exports.syntaxCleanup = syntaxCleanup;
module.exports.syntaxUnescape = syntaxUnescape; | var syntax = /\{\{([\w\-]+)\}\}/g;
var syntaxCleanup = /((?:[\r\n])*)\{\{([\w\-]+)\}\}((?:[\r\n])*)/g;
module.exports = function (template, replacements, cleanup) {
if (cleanup) {
return template.replace(syntaxCleanup, function (match, leadingSpaces, prop, trailingSpaces) {
var replacement = (prop in replacements) ? replacements[prop] : '{{' + match + '}}';
return leadingSpaces.length ? replacement + trailingSpaces : leadingSpaces + replacement;
});
}
return template.replace(syntax, function (match, prop) {
return (prop in replacements) ? replacements[prop] : match;
});
};
module.exports.syntax = syntax;
module.exports.syntaxCleanup = syntaxCleanup; |
Add CDI annotation to allow scan it | package org.gluu.service.util;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;
/**
* Created by eugeniuparvan on 12/22/16.
*
* @author Yuriy Movchan
*/
@ApplicationScoped
public class PageService {
private static final DateFormat CURRENT_DATE_TIME_FORMATTER = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a");
public String getRootUrlByRequest(HttpServletRequest request) {
String url = request.getRequestURL().toString();
return url.substring(0, url.length() - request.getRequestURI().length());
}
public String getCurrentDateTime() {
return CURRENT_DATE_TIME_FORMATTER.format(new Date());
}
}
| package org.gluu.service.util;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.ejb.Stateless;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;
/**
* Created by eugeniuparvan on 12/22/16.
*
* @author Yuriy Movchan
*/
@Stateless
@Named
public class PageService {
private static final DateFormat CURRENT_DATE_TIME_FORMATTER = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a");
public String getRootUrlByRequest(HttpServletRequest request) {
String url = request.getRequestURL().toString();
return url.substring(0, url.length() - request.getRequestURI().length());
}
public String getCurrentDateTime() {
return CURRENT_DATE_TIME_FORMATTER.format(new Date());
}
}
|
REVERT remove application id validation | import handlers.events as events
APPLICATION_ID = "amzn1.ask.skill.dd677950-cade-4805-b1f1-ce2e3a3569f0"
def lambda_handler(event, context):
# Make sure only this Alexa skill can use this function
if event['session']['application']['applicationId'] != APPLICATION_ID:
raise ValueError("Invalid Application ID")
if event['session']['new']:
events.on_session_started({'requestId': event['request']['requestId']},
event['session'])
request_type = event['request']['type']
if request_type == "LaunchRequest":
return events.on_launch(event['request'], event['session'])
elif request_type == "IntentRequest":
return events.on_intent(event['request'], event['session'])
elif request_type == "SessionEndedRequest":
return events.on_session_ended(event['request'], event['session'])
| import handlers.events as events
APPLICATION_ID = "amzn1.ask.skill.dd677950-cade-4805-b1f1-ce2e3a3569f0"
def lambda_handler(event, context):
if event['session']['new']:
events.on_session_started({'requestId': event['request']['requestId']},
event['session'])
request_type = event['request']['type']
if request_type == "LaunchRequest":
return events.on_launch(event['request'], event['session'])
elif request_type == "IntentRequest":
return events.on_intent(event['request'], event['session'])
elif request_type == "SessionEndedRequest":
return events.on_session_ended(event['request'], event['session'])
|
Make the `—yes/y` arg set all confirmations to yes | <?php
namespace Pantheon\Terminus\Commands;
use Pantheon\Terminus\Config;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use Psr\Log\LoggerInterface;
use Robo\Contract\IOAwareInterface;
use Robo\Contract\ConfigAwareInterface;
use Robo\Common\ConfigAwareTrait;
use Robo\Common\IO;
use Symfony\Component\Console\Question\ConfirmationQuestion;
use Terminus\Models\Auth;
abstract class TerminusCommand implements IOAwareInterface, LoggerAwareInterface, ConfigAwareInterface
{
use LoggerAwareTrait;
use ConfigAwareTrait;
use IO;
/**
* TerminusCommand constructor
*/
public function __construct()
{
}
/**
* Returns a logger object for use
*
* @return LoggerInterface
*/
protected function log()
{
return $this->logger;
}
/**
* @param $question
* @return string
*/
protected function confirm($question)
{
if ($this->input()->hasParameterOption(['--yes', '-y'])) {
return true;
}
return $this->doAsk(new ConfirmationQuestion($this->formatQuestion($question . ' (y/n)'), false));
}
}
| <?php
namespace Pantheon\Terminus\Commands;
use Pantheon\Terminus\Config;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use Psr\Log\LoggerInterface;
use Robo\Contract\IOAwareInterface;
use Robo\Contract\ConfigAwareInterface;
use Robo\Common\ConfigAwareTrait;
use Robo\Common\IO;
use Terminus\Models\Auth;
abstract class TerminusCommand implements IOAwareInterface, LoggerAwareInterface, ConfigAwareInterface
{
use LoggerAwareTrait;
use ConfigAwareTrait;
use IO;
/**
* TerminusCommand constructor
*/
public function __construct()
{
}
/**
* Returns a logger object for use
*
* @return LoggerInterface
*/
protected function log()
{
return $this->logger;
}
}
|
Check slower endpoints during promotion | import os
import pytest
import requests
@pytest.fixture
def url():
return os.getenv("SITE", "http://localhost:5000")
def test_get_templates(expect, url):
response = requests.get(f"{url}/templates")
expect(response.status_code) == 200
def test_post_images(expect, url):
params = {"template_key": "iw", "text_lines": ["test", "deployment"]}
response = requests.post(f"{url}/images", json=params)
expect(response.status_code) == 201
expect(response.json()["url"]).endswith("/images/iw/test/deployment.png")
def test_get_samples(expect, url):
response = requests.get(f"{url}/samples")
expect(response.status_code) == 200
def test_get_image(expect, url):
response = requests.get(f"{url}/images/iw/tests_code/in_production.jpg")
expect(response.status_code) == 200
expect(response.headers["Content-Type"]) == "image/jpeg"
def test_get_image_custom(expect, url):
response = requests.get(
f"{url}/images/custom/test.png"
"?alt=https://www.gstatic.com/webp/gallery/1.jpg"
)
expect(response.status_code) == 200
expect(response.headers["Content-Type"]) == "image/png"
| import os
import pytest
import requests
@pytest.fixture
def url():
return os.getenv("SITE", "http://localhost:5000")
def test_post_images(expect, url):
params = {"template_key": "iw", "text_lines": ["test", "deployment"]}
response = requests.post(f"{url}/images", json=params)
expect(response.status_code) == 201
expect(response.json()["url"]).endswith("/images/iw/test/deployment.png")
def test_get_image(expect, url):
response = requests.get(f"{url}/images/iw/tests_code/in_production.jpg")
expect(response.status_code) == 200
expect(response.headers["Content-Type"]) == "image/jpeg"
def test_get_image_custom(expect, url):
response = requests.get(
f"{url}/images/custom/test.png"
"?alt=https://www.gstatic.com/webp/gallery/1.jpg"
)
expect(response.status_code) == 200
expect(response.headers["Content-Type"]) == "image/png"
|
Use the Blinkt! library set_all rather than to loop on 8 pixels. | #!/usr/bin/env python
# Blue Dot Blinkt Colour Picker
# 02/06/2017
# David Glaude
from bluedot import BlueDot
import colorsys
import time
import blinkt
last_time = time.time()
def setall(r,g,b):
# for x in range(blinkt.NUM_PIXELS):
# blinkt.set_pixel(x, r, g, b)
blinkt.set_all(r, g, b)
blinkt.show()
def move(pos):
h=((pos.angle+180) % 360) / 360
s=pos.distance
v=1.0
r, g, b = [int(c*255) for c in colorsys.hsv_to_rgb(h, s, v)]
setall(r,g,b)
def rmove(pos):
global last_time
current_time=time.time()
delta = current_time-last_time
last_time = current_time
if (delta<0.3) :
setall(0,0,0)
blinkt.set_brightness(0.1)
blinkt.set_clear_on_exit()
bd = BlueDot()
bd.wait_for_press()
bd.when_pressed = move
bd.when_moved = move
bd.when_released = rmove
while True:
time.sleep(1)
| #!/usr/bin/env python
# Blue Dot Blinkt Colour Picker
# 02/06/2017
# David Glaude
from bluedot import BlueDot
import colorsys
import time
import blinkt
last_time = time.time()
def setall(r,g,b):
for x in range(blinkt.NUM_PIXELS):
blinkt.set_pixel(x, r, g, b)
blinkt.show()
def move(pos):
h=((pos.angle+180) % 360) / 360
s=pos.distance
v=1.0
r, g, b = [int(c*255) for c in colorsys.hsv_to_rgb(h, s, v)]
setall(r,g,b)
def rmove(pos):
global last_time
current_time=time.time()
delta = current_time-last_time
last_time = current_time
if (delta<0.3) :
setall(0,0,0)
blinkt.set_brightness(0.1)
blinkt.set_clear_on_exit()
bd = BlueDot()
bd.wait_for_press()
bd.when_pressed = move
bd.when_moved = move
bd.when_released = rmove
while True:
time.sleep(1)
|
Use super() and self within the Cipher and Caesar classes | import math
import secrets
from string import ascii_lowercase
class Cipher(object):
def __init__(self, key=None):
if not key:
key = self._random_key()
if not key.isalpha() or not key.islower():
raise ValueError("Key must consist only of lowercase letters")
self.key = key
self._key = [ord(k)-97 for k in key]
def encode(self, s):
key = self._key * math.ceil(len(s)/len(self._key))
chars = [c for c in s.lower() if c in ascii_lowercase]
return "".join(self._shift(c, k) for c, k in zip(chars, key))
def decode(self, s):
key = self._key * math.ceil(len(s)/len(self._key))
chars = [c for c in s.lower() if c in ascii_lowercase]
return "".join(self._shift(c, -k) for c, k in zip(chars, key))
@staticmethod
def _shift(char, key):
return chr(97 + ((ord(char) - 97 + key) % 26))
@staticmethod
def _random_key(length=256):
return "".join(secrets.choice(ascii_lowercase) for _ in range(length))
class Caesar(Cipher):
def __init__(self):
super().__init__("d")
| import math
import secrets
from string import ascii_lowercase
class Cipher(object):
def __init__(self, key=None):
if not key:
key = Cipher._random_key()
if not key.isalpha() or not key.islower():
raise ValueError("Key must consist only of lowercase letters")
self.key = key
self._key = [ord(k)-97 for k in key]
def encode(self, s):
key = self._key * math.ceil(len(s)/len(self._key))
chars = [c for c in s.lower() if c in ascii_lowercase]
return "".join(Cipher._shift(c, k) for c, k in zip(chars, key))
def decode(self, s):
key = self._key * math.ceil(len(s)/len(self._key))
chars = [c for c in s.lower() if c in ascii_lowercase]
return "".join(Cipher._shift(c, -k) for c, k in zip(chars, key))
@staticmethod
def _shift(char, key):
return chr(97 + ((ord(char) - 97 + key) % 26))
@staticmethod
def _random_key(length=256):
return "".join(secrets.choice(ascii_lowercase) for _ in range(length))
class Caesar(Cipher):
def __init__(self):
Cipher.__init__(self, "d")
|
Fix tfx-bsl error due to pyarrow package version requirement.
Change-Id: Ice7d39ccb0be84b36482c93b7de4b113fb1e7f82 | # Lint as: python3
# Copyright 2020 Google LLC.
#
# 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 setuptools import find_packages
from setuptools import setup
REQUIRED_PACKAGES = [
"apache-beam[gcp] >= 2.22.0",
"pandas >= 1.0.4",
"tensorflow_transform >= 0.22",
"Pillow >= 7.1.2",
"coverage >= 5.1",
"ipython >= 7.15.0",
"nose >= 1.3.7",
"pylint >= 2.5.3",
"fire >= 0.3.1",
"tensorflow >= 2.2.0",
"gcsfs >= 0.6.2",
"pyarrow < 0.17",
]
setup(
name='tfrutil',
version='0.1',
install_requires=REQUIRED_PACKAGES,
packages=find_packages(),
include_package_data=True,
description='TFRUtil creates TensorFlow Records easily.'
)
| # Lint as: python3
# Copyright 2020 Google LLC.
#
# 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 setuptools import find_packages
from setuptools import setup
REQUIRED_PACKAGES = [
"apache-beam[gcp] >= 2.22.0",
"pandas >= 1.0.4",
"tensorflow_transform >= 0.22",
"Pillow >= 7.1.2",
"coverage >= 5.1",
"ipython >= 7.15.0",
"nose >= 1.3.7",
"pylint >= 2.5.3",
"fire >= 0.3.1",
"tensorflow >= 2.2.0",
"gcsfs >= 0.6.2"
]
setup(
name='tfrutil',
version='0.1',
install_requires=REQUIRED_PACKAGES,
packages=find_packages(),
include_package_data=True,
description='TFRUtil creates TensorFlow Records easily.'
)
|
Add property decorator to getters | from configparser import ConfigParser
from driver import BTRFSDriver
class Node:
"""
# Dummy config example
[bk1-z3.presslabs.net]
ssd = True
"""
def __init__(self, context):
self._conf_path = context['node']['conf_path']
self._driver = BTRFSDriver(context['volume_path'])
self._name, self._labels = '', {}
config = ConfigParser()
config.read(self._conf_path)
try:
self._name = config.sections()[0]
for label, value in config[self._name].iteritems():
self._labels[label] = value
except IndexError:
pass
def get_subvolumes(self):
return self._driver.get_all()
@property
def name(self):
return self._name
@property
def labels(self):
return self._labels
| from configparser import ConfigParser
from driver import BTRFSDriver
class Node:
"""
# Dummy config example
[bk1-z3.presslabs.net]
ssd = True
"""
def __init__(self, context):
self._conf_path = context['node']['conf_path']
self._driver = BTRFSDriver(context['volume_path'])
self._name, self._labels = '', {}
config = ConfigParser()
config.read(self._conf_path)
try:
self._name = config.sections()[0]
for label, value in config[self._name].iteritems():
self._labels[label] = value
except IndexError:
pass
def get_subvolumes(self):
return self._driver.get_all()
def name(self):
return self._name
def labels(self):
return self._labels
|
Use single hot observable as timed event stream. | (function(){
var timer = Rx.Observable.interval(100).publish()
timer.connect()
// todo: remove depsu to elementBottomIsAlmostVisible
var nextPage = function(elem) {
var e = ($.isFunction(elem)) ? elem() : elem
return timer.where(function() { return elementBottomIsAlmostVisible(e, 100) })
}
var pager = function(ajaxSearch, page, next) {
return ajaxSearch(page).selectMany(function(res) {
if (res.length === 0) {
_.map(["#content-spinner-content", "#content-spinner-latest"], function(elem) { $(elem).html("Ei enempää suorituksia") })
return rx.empty()
} else {
return rx.returnValue(res).concat(next.take(1).selectMany(function() { return pager(ajaxSearch, page+1, next) }))
}
})
}
var Pager = function() {}
Pager.prototype.create = function(ajaxQuery, elem) { return pager(ajaxQuery, 1, nextPage(elem)) }
OnTrail.pager = new Pager()
Rx.Observable.prototype.scrollWith = function(action, element, visibleElem) {
return this.distinctUntilChanged().doAction(function() { element.html("") })
.selectArgs(function() {
var partialAppliedArgs = [action].concat(_.argsToArray(arguments))
return OnTrail.pager.create(_.partial.apply(_.partial, partialAppliedArgs), visibleElem || element)
}).switchLatest()
}
})() | (function(){
// todo: remove depsu to elementBottomIsAlmostVisible
var nextPage = function(elem) {
var e = ($.isFunction(elem)) ? elem() : elem
return Rx.Observable.interval(200).where(function() { return elementBottomIsAlmostVisible(e, 100) })
}
var pager = function(ajaxSearch, page, next) {
return ajaxSearch(page).selectMany(function(res) {
if (res.length === 0) {
_.map(["#content-spinner-content", "#content-spinner-latest"], function(elem) { $(elem).html("Ei enempää suorituksia") })
return rx.empty()
} else {
return rx.returnValue(res).concat(next.take(1).selectMany(function() { return pager(ajaxSearch, page+1, next) }))
}
})
}
var Pager = function() {}
Pager.prototype.create = function(ajaxQuery, elem) { return pager(ajaxQuery, 1, nextPage(elem)) }
OnTrail.pager = new Pager()
Rx.Observable.prototype.scrollWith = function(action, element, visibleElem) {
return this.distinctUntilChanged().doAction(function() { element.html("") })
.selectArgs(function() {
var partialAppliedArgs = [action].concat(_.argsToArray(arguments))
return OnTrail.pager.create(_.partial.apply(_.partial, partialAppliedArgs), visibleElem || element)
}).switchLatest()
}
})() |
Remove extra newlines added during editing | from cs251tk.student import remove
from cs251tk.student import clone_student
from cs251tk.student import stash
from cs251tk.student import pull
from cs251tk.student import checkout_date
from cs251tk.student import record
from cs251tk.student import reset
from cs251tk.student import analyze
def process_student(
student,
*,
assignments,
basedir,
clean,
date,
debug,
interact,
no_check,
no_update,
specs,
stogit_url
):
if clean:
remove(student)
clone_student(student, baseurl=stogit_url)
try:
stash(student, no_update=no_update)
pull(student, no_update=no_update)
checkout_date(student, date=date)
recordings = record(student, specs=specs, to_record=assignments, basedir=basedir, debug=debug, interact=interact)
analysis = analyze(student, specs, check_for_branches=not no_check)
if date:
reset(student)
return analysis, recordings
except Exception as err:
if debug:
raise err
return {'username': student, 'error': err}, []
| from cs251tk.student import remove
from cs251tk.student import clone_student
from cs251tk.student import stash
from cs251tk.student import pull
from cs251tk.student import checkout_date
from cs251tk.student import record
from cs251tk.student import reset
from cs251tk.student import analyze
def process_student(
student,
*,
assignments,
basedir,
clean,
date,
debug,
interact,
no_check,
no_update,
specs,
stogit_url
):
if clean:
remove(student)
clone_student(student, baseurl=stogit_url)
try:
stash(student, no_update=no_update)
pull(student, no_update=no_update)
checkout_date(student, date=date)
recordings = record(student, specs=specs, to_record=assignments, basedir=basedir, debug=debug, interact=interact)
analysis = analyze(student, specs, check_for_branches=not no_check)
if date:
reset(student)
return analysis, recordings
except Exception as err:
if debug:
raise err
return {'username': student, 'error': err}, []
|
Update with reference to global nav partial | var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var cssstats = require('cssstats')
var module = require('tachyons-images/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-images/tachyons-images.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)
var srcCSS = fs.readFileSync('./src/_images.css', 'utf8')
var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8')
var template = fs.readFileSync('./templates/docs/images/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
moduleVersion: module.version,
moduleSize: moduleSize,
moduleObj: moduleObj,
srcCSS: srcCSS,
navDocs: navDocs
})
fs.writeFileSync('./docs/general/images/index.html', html)
| var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var cssstats = require('cssstats')
var module = require('tachyons-images/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-images/tachyons-images.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)
var srcCSS = fs.readFileSync('./src/_images.css', 'utf8')
var template = fs.readFileSync('./templates/docs/images/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
moduleVersion: module.version,
moduleSize: moduleSize,
moduleObj: moduleObj,
srcCSS: srcCSS
})
fs.writeFileSync('./docs/general/images/index.html', html)
|
Add infos about MAP file | # csv2map.py -- Convert .csv into a .map format
# Description of MAP format: http://pngu.mgh.harvard.edu/~purcell/plink/data.shtml#map
#
# jean-daniel.granet@mines-paristech.fr
import sys
import argparse
def main():
parser = argparse.ArgumentParser(description='Convert .csv to .map')
parser.add_argument('csv', help="""CSV file to convert. Fields are : Index,Illumina_SNP_Name,Alternative_SNP_Name,Chromosome,Build36_Position,Build37_Position,new_rsname,Strand,TopAlleles,ForwardAlleles,DesignAlleles
""")
parser.add_argument('map', help='MAP file to create. Fields will be : num chromosome (1-22, X, Y or 0 if unplaced), snp identifier, Genetic distance (morgans) = 0, Base-pair position (bp units)')
args = parser.parse_args()
# read the csv file and convert it into a MAP file
with open(args.csv, 'r') as fdr:
with open(args.map, 'w') as fdw:
for line in fdr:
line_split = line.split(',')
fdw.write("%s\n" % "\n".join(["%s %s 0 %s" % (line_split[3], line_split[2], line_split[5])]))
fdw.close()
fdr.close()
if __name__ == "__main__":
main()
| # csv2map.py -- Convert .csv into a .map format
# Description of MAP format: http://pngu.mgh.harvard.edu/~purcell/plink/data.shtml#map
#
# jean-daniel.granet@mines-paristech.fr
import sys
import argparse
def main():
parser = argparse.ArgumentParser(description='Convert .csv to .map')
parser.add_argument('csv', help="""CSV file to convert. Fields are : Index,Illumina_SNP_Name,Alternative_SNP_Name,Chromosome,Build36_Position,Build37_Position,new_rsname,Strand,TopAlleles,ForwardAlleles,DesignAlleles
""")
parser.add_argument('map', help='MAP file to create')
args = parser.parse_args()
# read the csv file and convert it into a MAP file
with open(args.csv, 'r') as fdr:
with open(args.map, 'w') as fdw:
for line in fdr:
line_split = line.split(',')
fdw.write("%s\n" % "\n".join(["%s %s 0 %s" % (line_split[3], line_split[2], line_split[5])]))
fdw.close()
fdr.close()
if __name__ == "__main__":
main()
|
Fix unit test after adding separate baseline/proteomics filtering | package uk.ac.ebi.atlas.search.analyticsindex.baseline;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.web.client.RestTemplate;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
@RunWith(MockitoJUnitRunner.class)
public class BaselineAnalyticsSearchDaoTest {
private static final String SOLR_BASE_URL = "http://TEST";
private static final String JSON_FACET = "{}";
@Mock
private RestTemplate restTemplate;
private final BaselineAnalyticsSearchDao subject = new BaselineAnalyticsSearchDao(restTemplate, SOLR_BASE_URL, JSON_FACET);
@Test
public void buildQueryParameters() {
assertThat(subject.buildQueryParameters("identifierSearch:ENSG00000126549", 0.5, 0), is("query?q=identifierSearch:ENSG00000126549&rows=0&omitHeader=true&fq=(experimentType:rnaseq_mrna_baseline%20AND%20expressionLevel:%5B0.5%20TO%20*%5D)%20OR%20(experimentType:proteomics_baseline%20AND%20expressionLevel:%5B0%20TO%20*%5D)"));
}
} | package uk.ac.ebi.atlas.search.analyticsindex.baseline;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.web.client.RestTemplate;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
@RunWith(MockitoJUnitRunner.class)
public class BaselineAnalyticsSearchDaoTest {
private static final String SOLR_BASE_URL = "http://TEST";
private static final String JSON_FACET = "{}";
@Mock
private RestTemplate restTemplate;
private final BaselineAnalyticsSearchDao subject = new BaselineAnalyticsSearchDao(restTemplate, SOLR_BASE_URL, JSON_FACET);
@Test
public void buildQueryParameters() {
assertThat(subject.buildQueryParameters("identifierSearch:ENSG00000126549", 0.5, 0), is("query?q=identifierSearch:ENSG00000126549&rows=0&omitHeader=true&fq=expressionLevel:%5B0.5%20TO%20*%5D"));
}
} |
Use util instead of sys in example.
Make sure the example Jerk script continues to work in future node.js
releases. The node.js `sys` library has been a pointer to `util` since
0.3 and has now been removed completely in the node.js development
branch. | var jerk = require( '../lib/jerk' ), util = require('util');
var options =
{ server: 'localhost'
, port: 6667
, nick: 'Bot9121'
, channels: [ '#jerkbot' ]
};
jerk( function( j ) {
j.watch_for( 'soup', function( message ) {
message.say( message.user + ': soup is good food!' )
});
j.watch_for( /^(.+) are silly$/, function( message ) {
message.say( message.user + ': ' + message.match_data[1] + ' are NOT SILLY. Don\'t joke!' )
});
j.user_join(function(message) {
message.say(message.user + ": Hey, welcome!");
});
j.user_leave(function(message) {
util.puts("User: " + message.user + " has left");
});
}).connect( options );
| var jerk = require( '../lib/jerk' ), sys=require('sys');
var options =
{ server: 'localhost'
, port: 6667
, nick: 'Bot9121'
, channels: [ '#jerkbot' ]
};
jerk( function( j ) {
j.watch_for( 'soup', function( message ) {
message.say( message.user + ': soup is good food!' )
});
j.watch_for( /^(.+) are silly$/, function( message ) {
message.say( message.user + ': ' + message.match_data[1] + ' are NOT SILLY. Don\'t joke!' )
});
j.user_join(function(message) {
message.say(message.user + ": Hey, welcome!");
});
j.user_leave(function(message) {
sys.puts("User: " + message.user + " has left");
});
}).connect( options );
|
Use final URL (i.e. URL after redirects) when storing cookies. | var denodeify = require('es6-denodeify')(Promise)
var tough = require('tough-cookie')
module.exports = function fetchCookieDecorator (fetch, jar) {
fetch = fetch || window.fetch
jar = jar || new tough.CookieJar()
var getCookieString = denodeify(jar.getCookieString.bind(jar))
var setCookie = denodeify(jar.setCookie.bind(jar))
return function fetchCookie (url, opts) {
opts = opts || {}
return getCookieString(url)
.then(function (cookie) {
return fetch(url, Object.assign(opts, {
headers: Object.assign(opts.headers || {}, { cookie: cookie })
}))
})
.then(function (res) {
var cookies = res.headers.getAll('set-cookie')
if (!cookies.length) {
return res
}
return Promise.all(cookies.map(function (cookie) {
return setCookie(cookie, res.url)
})).then(function () {
return res
})
})
}
}
| var denodeify = require('es6-denodeify')(Promise)
var tough = require('tough-cookie')
module.exports = function fetchCookieDecorator (fetch, jar) {
fetch = fetch || window.fetch
jar = jar || new tough.CookieJar()
var getCookieString = denodeify(jar.getCookieString.bind(jar))
var setCookie = denodeify(jar.setCookie.bind(jar))
return function fetchCookie (url, opts) {
opts = opts || {}
return getCookieString(url)
.then(function (cookie) {
return fetch(url, Object.assign(opts, {
headers: Object.assign(opts.headers || {}, { cookie: cookie })
}))
})
.then(function (res) {
var cookies = res.headers.getAll('set-cookie')
if (!cookies.length) {
return res
}
return Promise.all(cookies.map(function (cookie) {
return setCookie(cookie, url)
})).then(function () {
return res
})
})
}
}
|
Refactor beer availability to use template tags. | <section>
<?php
$beer_post_id = get_the_ID();
if ( $inventory = dabc_get_inventory( $beer_post_id ) ) :
$store_numbers = array_keys( $inventory );
?>
<h3>Store Availability</h3>
<p>Last Updated: <?php dabc_the_inventory_last_updated(); ?></p>
<table>
<thead>
<tr>
<th>Store</th>
<th>Address</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<?php $stores = dabc_query_stores_by_number( $store_numbers ); ?>
<?php while ( $stores->have_posts() ) : ?>
<?php $stores->the_post(); ?>
<?php $store_post_id = get_the_ID(); ?>
<?php $store_number = dabc_get_store_number( $store_post_id ); ?>
<tr>
<td>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</td>
<td>
<?php dabc_the_store_address( $store_post_id ); ?>
</td>
<td><?php dabc_the_quantity_for_store( $store_number, $beer_post_id ); ?></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
<?php endif; ?>
</section> | <section>
<?php
$inventory = get_post_meta(get_the_ID(), 'dabc-store-inventory', true);
if ( $inventory['inventory'] ) :
$store_numbers = array_keys( $inventory['inventory'] );
?>
<h3>Store Availability</h3>
<p>Last Updated: <?php echo $inventory['last_updated']; ?></p>
<table>
<thead>
<tr>
<th>Store</th>
<th>Address</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<?php $stores = dabc_query_stores_by_number( $store_numbers ); ?>
<?php while ( $stores->have_posts() ) : ?>
<?php $stores->the_post(); ?>
<?php $store_post_id = get_the_ID(); ?>
<?php $store_number = dabc_get_store_number( $store_post_id ); ?>
<tr>
<td>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</td>
<td>
<?php dabc_the_store_address( $store_post_id ); ?>
</td>
<td><?php echo $inventory['inventory'][$store_number]; ?></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
<?php endif; ?>
</section> |
Return specific user-defined control, not proxy | from sf.lib.orderedattrdict import OrderedAttrDict
class Controller(object):
def __init__(self, module, name):
self.module = module
self.name = name
@property
def ctl(self):
c = self.module.controllers[self.name]
if hasattr(self.module, 'user_defined') and c.number >= 6:
c = self.module.user_defined[c.number - 6]
return c
@property
def value(self):
return getattr(self.module, self.name)
@value.setter
def value(self, value):
setattr(self.module, self.name, value)
class Group(OrderedAttrDict):
def __setitem__(self, key, value, **kwargs):
if isinstance(value, tuple) and len(value) == 2:
module, name = value
value = Controller(module, name)
elif not isinstance(value, (Controller, Group)):
raise ValueError(
'Value must be a 2-tuple, Controller instance, '
'or Group instance'
)
super().__setitem__(key, value, **kwargs)
__all__ = [
'Controller',
'Group',
]
| from sf.lib.orderedattrdict import OrderedAttrDict
class Controller(object):
def __init__(self, module, name):
self.module = module
self.name = name
@property
def ctl(self):
return self.module.controllers[self.name]
@property
def value(self):
return getattr(self.module, self.name)
@value.setter
def value(self, value):
setattr(self.module, self.name, value)
class Group(OrderedAttrDict):
def __setitem__(self, key, value, **kwargs):
if isinstance(value, tuple) and len(value) == 2:
module, name = value
value = Controller(module, name)
elif not isinstance(value, (Controller, Group)):
raise ValueError(
'Value must be a 2-tuple, Controller instance, '
'or Group instance'
)
super().__setitem__(key, value, **kwargs)
__all__ = [
'Controller',
'Group',
]
|
Add named anchor to benchmark text explainer | //general ContactManager app code (defining regions, the start handler, etc.):
var HospitalCheckup = new Marionette.Application();
HospitalCheckup.navigate = function(route, options){
options || (options = {});
Backbone.history.navigate(route, options);
};
HospitalCheckup.getCurrentRoute = function(){
return Backbone.history.fragment
};
HospitalCheckup.on("before:start", function(){
var RegionContainer = Marionette.LayoutView.extend({
el: "#app-container",
regions: {
header: "#header-region",
main: "#main-region"
}
});
HospitalCheckup.regions = new RegionContainer();
});
HospitalCheckup.on("start", function(){
window.localStorage.clear(); //we want fresh data which we will persist during this session
if(Backbone.history){
Backbone.history.start();
/*if(this.getCurrentRoute() === ""){
HospitalCheckup.trigger("infections:list");
}*/
}
$(document).on('click', 'a[href^="#benchmark"]', function (e) { //TODO this doesn't belong here
e.preventDefault();
element = document.getElementById("benchmark")
element.scrollIntoView(true); //parameter = "alignToTop"
});
});
| //general ContactManager app code (defining regions, the start handler, etc.):
var HospitalCheckup = new Marionette.Application();
HospitalCheckup.navigate = function(route, options){
options || (options = {});
Backbone.history.navigate(route, options);
};
HospitalCheckup.getCurrentRoute = function(){
return Backbone.history.fragment
};
HospitalCheckup.on("before:start", function(){
var RegionContainer = Marionette.LayoutView.extend({
el: "#app-container",
regions: {
header: "#header-region",
main: "#main-region"
}
});
HospitalCheckup.regions = new RegionContainer();
});
HospitalCheckup.on("start", function(){
window.localStorage.clear(); //we want fresh data which we will persist during this session
if(Backbone.history){
Backbone.history.start();
/*if(this.getCurrentRoute() === ""){
HospitalCheckup.trigger("infections:list");
}*/
}
});
|
Use keypress instead of keydown | /*
* jquery.submitOnEnter v1.0.1
*
* Copyright (c) 2012 Thibaut Courouble
* http://thibaut.me
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*/
(function($) {
'use strict';
function submitOnEnter(event) {
if (event.which === 13 && !event.altKey && !event.shiftKey && !event.ctrlKey && !event.metaKey) {
event.preventDefault();
event.stopPropagation();
(event.delegateTarget.nodeName === 'FORM' ?
$(event.delegateTarget) :
(event.currentTarget.nodeName === 'FORM') ?
$(event.currentTarget) :
$(event.currentTarget).closest('form')
).not(':has(input[type=submit]:disabled)')
.not(':has(button[type=submit]:disabled)')
.submit();
}
}
$.fn.submitOnEnter = function(selector) {
return this.off('.submitOnEnter').on('keypress.submitOnEnter', selector, submitOnEnter);
};
})(jQuery);
| /*
* jquery.submitOnEnter v1.0.1
*
* Copyright (c) 2012 Thibaut Courouble
* http://thibaut.me
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*/
(function($) {
'use strict';
function submitOnEnter(event) {
if (event.which === 13 && !event.altKey && !event.shiftKey && !event.ctrlKey && !event.metaKey) {
event.preventDefault();
event.stopPropagation();
(event.delegateTarget.nodeName === 'FORM' ?
$(event.delegateTarget) :
(event.currentTarget.nodeName === 'FORM') ?
$(event.currentTarget) :
$(event.currentTarget).closest('form')
).not(':has(input[type=submit]:disabled)')
.not(':has(button[type=submit]:disabled)')
.submit();
}
}
$.fn.submitOnEnter = function(selector) {
return this.off('.submitOnEnter').on('keydown.submitOnEnter', selector, submitOnEnter);
};
})(jQuery);
|
Use the threaded version for NN visualization. | package samples;
import hex.*;
import javax.swing.JFrame;
public class NeuralNetViz extends NeuralNetMnist {
public static void main(String[] args) throws Exception {
Class job = Class.forName(Thread.currentThread().getStackTrace()[1].getClassName());
samples.launchers.CloudLocal.launch(job, 1);
}
protected void startTraining(Layer[] ls) {
//_trainer = new Trainer.MapReduce(ls, 0, self());
_trainer = new Trainer.Threaded(ls, 0, self());
// Basic visualization of images and weights
JFrame frame = new JFrame("H2O");
frame.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
MnistCanvas canvas = new MnistCanvas(_trainer);
frame.setContentPane(canvas.init());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
//preTrain(ls);
_trainer.start();
}
}
| package samples;
import hex.*;
import javax.swing.JFrame;
public class NeuralNetViz extends NeuralNetMnist {
public static void main(String[] args) throws Exception {
Class job = Class.forName(Thread.currentThread().getStackTrace()[1].getClassName());
samples.launchers.CloudLocal.launch(job, 1);
}
protected void startTraining(Layer[] ls) {
_trainer = new Trainer.MapReduce(ls, 0, self());
//_trainer = new Trainer.Direct(ls);
// Basic visualization of images and weights
JFrame frame = new JFrame("H2O");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MnistCanvas canvas = new MnistCanvas(_trainer);
frame.setContentPane(canvas.init());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
//preTrain(ls);
_trainer.start();
}
}
|
Fix artisan factory make command issue | <?php
declare(strict_types=1);
namespace Cortex\Foundation\Console\Commands;
use Illuminate\Console\ConfirmableTrait;
use Cortex\Foundation\Traits\ConsoleMakeModuleCommand;
use Illuminate\Database\Console\Factories\FactoryMakeCommand as BaseFactoryMakeCommand;
class FactoryMakeCommand extends BaseFactoryMakeCommand
{
use ConfirmableTrait;
use ConsoleMakeModuleCommand;
/**
* Get the destination class path.
*
* @param string $name
*
* @throws \Exception
*
* @return string
*/
protected function getPath($name): string
{
$name = str_replace_first($this->rootNamespace(), $this->moduleName().DIRECTORY_SEPARATOR.'database'.DIRECTORY_SEPARATOR.'factories', $name);
if (! $this->files->exists($path = $this->laravel['path'].DIRECTORY_SEPARATOR.$this->moduleName().DIRECTORY_SEPARATOR)) {
throw new \Exception("Invalid path: {$path}");
}
return $this->laravel['path'].DIRECTORY_SEPARATOR.str_replace('\\', DIRECTORY_SEPARATOR, $name).'.php';
}
}
| <?php
declare(strict_types=1);
namespace Cortex\Foundation\Console\Commands;
use Illuminate\Console\ConfirmableTrait;
use Cortex\Foundation\Traits\ConsoleMakeModuleCommand;
use Illuminate\Database\Console\Factories\FactoryMakeCommand as BaseFactoryMakeCommand;
class FactoryMakeCommand extends BaseFactoryMakeCommand
{
use ConfirmableTrait;
use ConsoleMakeModuleCommand;
/**
* Get the destination class path.
*
* @param string $name
*
* @throws \Exception
*
* @return string
*/
protected function getPath($name): string
{
$name = str_replace_first($this->rootNamespace(), $this->moduleName().DIRECTORY_SEPARATOR.'database'.DIRECTORY_SEPARATOR.'factories', $name);
if (! $this->files->exists($path = $this->laravel['path'].DIRECTORY_SEPARATOR.$this->moduleName().DIRECTORY_SEPARATOR.'database'.DIRECTORY_SEPARATOR.'factories')) {
throw new \Exception("Invalid path: {$path}");
}
return $this->laravel['path'].DIRECTORY_SEPARATOR.str_replace('\\', DIRECTORY_SEPARATOR, $name).'.php';
}
}
|
Include basic_auth_token in gobierto plans factories header | import axios from "axios";
const baseUrl = location.origin;
const endPoint = `${baseUrl}/api/v1/plans`;
const token = window.gobiertoAPI.token.length == 0 && window.gobiertoAPI.basic_auth_token ? window.gobiertoAPI.basic_auth_token : window.gobiertoAPI.token
const headers = {
"Content-type": "application/json",
Authorization: token
};
// Plans-endpoint factory to get/post/put/delete API data
export const PlansFactoryMixin = {
locale: I18n.locale,
methods: {
getPlan(id, params) {
const qs = new URLSearchParams({ locale: this.$options.locale, ...params })
return axios.get(`${endPoint}/${id}?${qs.toString()}`, { headers })
},
getProjects(id, params) {
const qs = new URLSearchParams({ locale: this.$options.locale, ...params })
return axios.get(`${endPoint}/${id}/projects?${qs.toString()}`, { headers })
},
getMeta(id, params) {
const qs = new URLSearchParams({ locale: this.$options.locale, ...params })
return axios.get(`${endPoint}/${id}/meta?${qs.toString()}`, { headers })
}
}
};
| import axios from "axios";
const baseUrl = location.origin;
const endPoint = `${baseUrl}/api/v1/plans`;
const headers = {
"Content-type": "application/json",
Authorization: window.gobiertoAPI.token
};
// Plans-endpoint factory to get/post/put/delete API data
export const PlansFactoryMixin = {
locale: I18n.locale,
methods: {
getPlan(id, params) {
const qs = new URLSearchParams({ locale: this.$options.locale, ...params })
return axios.get(`${endPoint}/${id}?${qs.toString()}`, { headers })
},
getProjects(id, params) {
const qs = new URLSearchParams({ locale: this.$options.locale, ...params })
return axios.get(`${endPoint}/${id}/projects?${qs.toString()}`, { headers })
},
getMeta(id, params) {
const qs = new URLSearchParams({ locale: this.$options.locale, ...params })
return axios.get(`${endPoint}/${id}/meta?${qs.toString()}`, { headers })
}
}
};
|
Return trait names according to a search term | <?php
namespace ajax\listing;
use \PDO as PDO;
/**
* Web Service.
* Returns Trait informatio
*/
class Traits extends \WebService {
/**
* @param $querydata[]
* @returns array of traits
*/
public function execute($querydata) {
global $db;
$search = "%%";
if(in_array('search', array_keys($querydata))){
$search = "%".$querydata['search']."%";
}
$query_get_traits = <<<EOF
SELECT name, tci.type_cvterm_id FROM (SELECT DISTINCT type_cvterm_id FROM trait_entry) AS tci, trait_cvterm WHERE tci.type_cvterm_id=trait_cvterm.trait_cvterm_id AND name LIKE :search;
EOF;
$stm_get_traits = $db->prepare($query_get_traits);
$stm_get_traits->bindValue('search', $search);
$stm_get_traits->execute();
$data = array();
while ($row = $stm_get_traits->fetch(PDO::FETCH_ASSOC)) {
$result = array();
$result['name'] = $row['name'];
$data[] = $result;
}
return $data;
}
}
?>
| <?php
namespace ajax\listing;
use \PDO as PDO;
/**
* Web Service.
* Returns Trait informatio
*/
class Traits extends \WebService {
/**
* @param $querydata[]
* @returns array of traits
*/
public function execute($querydata) {
global $db;
$data = array();
$search = "%%";
if(in_array('search', array_keys($querydata))){
$search = "%".$querydata['search']."%";
}
$query_get_traits = <<<EOF
SELECT name, tci.type_cvterm_id FROM (SELECT DISTINCT type_cvterm_id FROM trait_entry) AS tci, trait_cvterm WHERE tci.type_cvterm_id=trait_cvterm.trait_cvterm_id;
EOF;
$stm_get_traits = $db->prepare($query_get_traits);
$stm_get_traits->execute();
while ($row = $stm_get_traits->fetch(PDO::FETCH_ASSOC)) {
$result=array();
$result['name']=$row['name'];
$data[]=$result;
}
return data;
}
}
?>
|
Fix windows name pipeline issue | 'use strict';
const path = require('path');
const os = require('os');
exports.toNumber = function(x) { return (x = Number(x)) >= 0 ? x : false; };
exports.getSocketPath = function(channel)
{
let pipePath = path.resolve(os.tmpdir(), `.fast.mq.${channel}`);
// use windows named pipe
if (process.platform === 'win32')
{
pipePath = pipePath.replace(/^\//, '');
pipePath = pipePath.replace(/\//g, '-');
pipePath = `\\\\.\\pipe\\${pipePath}`;
}
return pipePath;
};
const pid = (process && process.pid) ? process.pid : 0;
function uuid()
{
var time = Date.now();
var last = uuid.last || time;
uuid.last = time > last ? (pid + time) : (pid + last + 1);
return uuid.last;
}
exports.uuid = uuid;
| 'use strict';
const path = require('path');
const os = require('os');
exports.toNumber = function(x) { return (x = Number(x)) >= 0 ? x : false; };
exports.getSocketPath = function(channel)
{
let pipePath = path.resolve(os.tmpdir(), `.fast.mq.${channel}`);
// use windows named pipe
if (process.platform === 'win32')
{
pipePath = path.replace(/^\//, '');
pipePath = path.replace(/\//g, '-');
pipePath = `\\\\.\\pipe\\${pipePath}`;
}
return pipePath;
};
const pid = (process && process.pid) ? process.pid : 0;
function uuid()
{
var time = Date.now();
var last = uuid.last || time;
uuid.last = time > last ? (pid + time) : (pid + last + 1);
return uuid.last;
}
exports.uuid = uuid;
|
Exit correctly on test errors | const gulp = require('gulp');
const jshint = require('gulp-jshint');
const mocha = require('gulp-mocha');
const istanbul = require('gulp-istanbul');
gulp.task('lint', function() {
return gulp.src('./lib/**/*.js')
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(jshint.reporter('fail'));
});
gulp.task('pre-test', () => {
return gulp.src(['./lib/**/*.js'])
.pipe(istanbul())
.pipe(istanbul.hookRequire());
})
gulp.task('test', ['pre-test'], () => {
return gulp.src('./test/**/*.js')
.pipe(mocha({reporter: 'spec' }))
// Ugly hack because the mocha plugin doesn't properly exit with an exit code on test failures
.on('error', (err) => { process.exit(1) })
.pipe(istanbul.writeReports())
.pipe(istanbul.enforceThresholds({ thresholds: { global: 90 } }));
});
gulp.task('default', ['lint', 'test']); | const gulp = require('gulp');
const jshint = require('gulp-jshint');
const mocha = require('gulp-mocha');
const istanbul = require('gulp-istanbul');
gulp.task('lint', function() {
return gulp.src('./lib/**/*.js')
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(jshint.reporter('fail'));
});
gulp.task('pre-test', () => {
return gulp.src(['./lib/**/*.js'])
.pipe(istanbul())
.pipe(istanbul.hookRequire());
})
gulp.task('test', ['pre-test'], () => {
return gulp.src('./test/**/*.js')
.pipe(mocha({reporter: 'spec' }))
.pipe(istanbul.writeReports())
.pipe(istanbul.enforceThresholds({ thresholds: { global: 90 } }));
});
gulp.task('default', ['lint', 'test']); |
Move licenses into better scope | 'use strict';
var fs = require('fs');
var path = require('path');
var dir = require('node-dir');
var q = require('q');
var findLicenses = function () {
var deferred = q.defer();
var modulesDir = path.join(process.cwd(), 'node_modules');
dir.files(modulesDir, function (err, files) {
var licenses = [];
files.forEach(function (file) {
if (/license/gi.test(file)) {
var currPath = file.split(path.sep);
var currModule = currPath[currPath.lastIndexOf('node_modules') + 1];
licenses.push({
'module': currModule,
'license': file
});
}
});
deferred.resolve(licenses);
});
return deferred.promise;
};
findLicenses().then(function (data) {
console.log(data);
});
| 'use strict';
var fs = require('fs');
var path = require('path');
var dir = require('node-dir');
var q = require('q');
var findLicenses = function () {
var licenses = [];
var deferred = q.defer();
var modulesDir = path.join(process.cwd(), 'node_modules');
dir.files(modulesDir, function (err, files) {
files.forEach(function (file) {
if (/license/gi.test(file)) {
var currPath = file.split(path.sep);
var currModule = currPath[currPath.lastIndexOf('node_modules') + 1];
licenses.push({
'module': currModule,
'license': file
});
}
});
deferred.resolve(licenses);
});
return deferred.promise;
};
findLicenses().then(function (data) {
console.log(data);
});
|
Use on() instead of delegate().
delegate() is deprecated. | Zepto(function($) {
prettyPrint();
var $frameContainer = $('.frames-container');
var $container = $('.details-container');
var $activeLine = $frameContainer.find('.frame.active');
var $activeFrame = $container.find('.frame-code.active');
var headerHeight = $('header').height();
var highlightCurrentLine = function() {
// Highlight the active and neighboring lines for this frame:
var activeLineNumber = +($activeLine.find('.frame-line').text());
var $lines = $activeFrame.find('.linenums li');
var firstLine = +($lines.first().val());
$($lines[activeLineNumber - firstLine - 1]).addClass('current');
$($lines[activeLineNumber - firstLine]).addClass('current active');
$($lines[activeLineNumber - firstLine + 1]).addClass('current');
}
// Highlight the active for the first frame:
highlightCurrentLine();
$frameContainer.on('click', '.frame', function() {
var $this = $(this);
var id = /frame\-line\-([\d]*)/.exec($this.attr('id'))[1];
var $codeFrame = $('#frame-code-' + id);
if ($codeFrame) {
$activeLine.removeClass('active');
$activeFrame.removeClass('active');
$this.addClass('active');
$codeFrame.addClass('active');
$activeLine = $this;
$activeFrame = $codeFrame;
highlightCurrentLine();
$container.scrollTop(headerHeight);
}
});
});
| Zepto(function($) {
prettyPrint();
var $frameContainer = $('.frames-container');
var $container = $('.details-container');
var $activeLine = $frameContainer.find('.frame.active');
var $activeFrame = $container.find('.frame-code.active');
var headerHeight = $('header').height();
var highlightCurrentLine = function() {
// Highlight the active and neighboring lines for this frame:
var activeLineNumber = +($activeLine.find('.frame-line').text());
var $lines = $activeFrame.find('.linenums li');
var firstLine = +($lines.first().val());
$($lines[activeLineNumber - firstLine - 1]).addClass('current');
$($lines[activeLineNumber - firstLine]).addClass('current active');
$($lines[activeLineNumber - firstLine + 1]).addClass('current');
}
// Highlight the active for the first frame:
highlightCurrentLine();
$frameContainer.delegate('.frame', 'click', function() {
var $this = $(this);
var id = /frame\-line\-([\d]*)/.exec($this.attr('id'))[1];
var $codeFrame = $('#frame-code-' + id);
if ($codeFrame) {
$activeLine.removeClass('active');
$activeFrame.removeClass('active');
$this.addClass('active');
$codeFrame.addClass('active');
$activeLine = $this;
$activeFrame = $codeFrame;
highlightCurrentLine();
$container.scrollTop(headerHeight);
}
});
});
|
Update code for pkg/xattr v0.2.0 | // +build !openbsd
// +build !windows
package restic
import (
"restic/errors"
"syscall"
"github.com/pkg/xattr"
)
// Getxattr retrieves extended attribute data associated with path.
func Getxattr(path, name string) ([]byte, error) {
b, e := xattr.Get(path, name)
if err, ok := e.(*xattr.Error); ok && err.Err == syscall.ENOTSUP {
return nil, nil
}
return b, errors.Wrap(e, "Getxattr")
}
// Listxattr retrieves a list of names of extended attributes associated with the
// given path in the file system.
func Listxattr(path string) ([]string, error) {
s, e := xattr.List(path)
if err, ok := e.(*xattr.Error); ok && err.Err == syscall.ENOTSUP {
return nil, nil
}
return s, errors.Wrap(e, "Listxattr")
}
// Setxattr associates name and data together as an attribute of path.
func Setxattr(path, name string, data []byte) error {
e := xattr.Set(path, name, data)
if err, ok := e.(*xattr.Error); ok && err.Err == syscall.ENOTSUP {
return nil
}
return errors.Wrap(e, "Setxattr")
}
| // +build !openbsd
// +build !windows
package restic
import (
"restic/errors"
"syscall"
"github.com/pkg/xattr"
)
// Getxattr retrieves extended attribute data associated with path.
func Getxattr(path, name string) ([]byte, error) {
b, e := xattr.Getxattr(path, name)
if err, ok := e.(*xattr.XAttrError); ok && err.Err == syscall.ENOTSUP {
return nil, nil
}
return b, errors.Wrap(e, "Getxattr")
}
// Listxattr retrieves a list of names of extended attributes associated with the
// given path in the file system.
func Listxattr(path string) ([]string, error) {
s, e := xattr.Listxattr(path)
if err, ok := e.(*xattr.XAttrError); ok && err.Err == syscall.ENOTSUP {
return nil, nil
}
return s, errors.Wrap(e, "Listxattr")
}
// Setxattr associates name and data together as an attribute of path.
func Setxattr(path, name string, data []byte) error {
e := xattr.Setxattr(path, name, data)
if err, ok := e.(*xattr.XAttrError); ok && err.Err == syscall.ENOTSUP {
return nil
}
return errors.Wrap(e, "Setxattr")
}
|
Fix type in method name | package com.bookbase.app.utils;
import android.arch.persistence.room.TypeConverter;
import com.bookbase.app.mainscreen.HomeScreen;
import com.bookbase.app.database.AppDatabase;
import com.bookbase.app.model.entity.Author;
import com.bookbase.app.model.entity.Genre;
import java.sql.Date;
import java.util.Calendar;
public class Converters {
private static AppDatabase db = AppDatabase.getDatabase(HomeScreen.getContext());
@TypeConverter
public static Long dateToLong(Date date){
return date == null ? null : date.getTime();
}
@TypeConverter
public static Calendar toCalendar(String date){
// TODO: Complete implementation.
return Calendar.getInstance();
}
@TypeConverter
public static String calendarToString(Calendar calendar){
// TODO: Finish implementation.
return "";
}
@TypeConverter
public static int authorAsId(Author author){
return author.getAuthorId();
}
@TypeConverter
public static Author intToAuthor(int id){
return db.authorDao().getAuthorById(id);
}
@TypeConverter
public static int genreAsId(Genre genre){
return genre.getGenreId();
}
@TypeConverter
public static Genre intToGenre(int id){
return db.genreDao().getGenreById(id);
}
}
| package com.bookbase.app.utils;
import android.arch.persistence.room.TypeConverter;
import com.bookbase.app.mainscreen.HomeScreen;
import com.bookbase.app.database.AppDatabase;
import com.bookbase.app.model.entity.Author;
import com.bookbase.app.model.entity.Genre;
import java.sql.Date;
import java.util.Calendar;
public class Converters {
private static AppDatabase db = AppDatabase.getDatabase(HomeScreen.getContext());
@TypeConverter
public static Long dateToLong(Date date){
return date == null ? null : date.getTime();
}
@TypeConverter
public static Calendar toCalendar(String date){
// TODO: Complete implementation.
return Calendar.getInstance();
}
@TypeConverter
public static String calendarToLong(Calendar calendar){
// TODO: Finish implementation.
return "";
}
@TypeConverter
public static int authorAsId(Author author){
return author.getAuthorId();
}
@TypeConverter
public static Author intToAuthor(int id){
return db.authorDao().getAuthorById(id);
}
@TypeConverter
public static int genreAsId(Genre genre){
return genre.getGenreId();
}
@TypeConverter
public static Genre intToGenre(int id){
return db.genreDao().getGenreById(id);
}
}
|
Add `id_in` to request search | <?php
/**
* Hosting Plugin for HiPanel
*
* @link https://github.com/hiqdev/hipanel-module-hosting
* @package hipanel-module-hosting
* @license BSD-3-Clause
* @copyright Copyright (c) 2015-2019, HiQDev (http://hiqdev.com/)
*/
/**
* @see http://hiqdev.com/hipanel-module-hosting
* @license http://hiqdev.com/hipanel-module-hosting/license
* @copyright Copyright (c) 2015 HiQDev
*/
namespace hipanel\modules\hosting\models;
use hipanel\base\SearchModelTrait;
use hipanel\helpers\ArrayHelper;
class RequestSearch extends Request
{
use SearchModelTrait {
searchAttributes as defaultSearchAttributes;
}
public function rules()
{
return ArrayHelper::merge(parent::rules(), [
[['ids'], 'safe', 'on' => ['search']],
[['id_in'], 'safe'],
]);
}
}
| <?php
/**
* Hosting Plugin for HiPanel
*
* @link https://github.com/hiqdev/hipanel-module-hosting
* @package hipanel-module-hosting
* @license BSD-3-Clause
* @copyright Copyright (c) 2015-2019, HiQDev (http://hiqdev.com/)
*/
/**
* @see http://hiqdev.com/hipanel-module-hosting
* @license http://hiqdev.com/hipanel-module-hosting/license
* @copyright Copyright (c) 2015 HiQDev
*/
namespace hipanel\modules\hosting\models;
use hipanel\base\SearchModelTrait;
use hipanel\helpers\ArrayHelper;
class RequestSearch extends Request
{
use SearchModelTrait {
searchAttributes as defaultSearchAttributes;
}
public function rules()
{
return ArrayHelper::merge(parent::rules(), [
[['ids'], 'safe', 'on' => ['search']],
]);
}
}
|
title: Clean up logic a bit in getTitleBackgroundColor.
Hopefully this makes it easier to see what's happening. | /* @flow */
import { createSelector } from 'reselect';
import type { Narrow, Selector } from '../types';
import { getSubscriptions } from '../directSelectors';
import { isStreamOrTopicNarrow } from '../utils/narrow';
import { NULL_SUBSCRIPTION } from '../nullObjects';
export const DEFAULT_TITLE_BACKGROUND_COLOR = 'transparent';
/**
* Background color to use for the app bar in narrow `narrow`.
*
* If `narrow` is a stream or topic narrow, this is based on the stream color.
* Otherwise, it takes a default value.
*/
export const getTitleBackgroundColor = (narrow?: Narrow): Selector<string> =>
createSelector(getSubscriptions, subscriptions => {
if (!narrow || !isStreamOrTopicNarrow(narrow)) {
return DEFAULT_TITLE_BACKGROUND_COLOR;
}
const streamName = narrow[0].operand;
return (subscriptions.find(sub => streamName === sub.name) || NULL_SUBSCRIPTION).color;
});
| /* @flow */
import { createSelector } from 'reselect';
import type { Narrow, Selector } from '../types';
import { getSubscriptions } from '../directSelectors';
import { isStreamOrTopicNarrow } from '../utils/narrow';
import { NULL_SUBSCRIPTION } from '../nullObjects';
export const DEFAULT_TITLE_BACKGROUND_COLOR = 'transparent';
/**
* Background color to use for the app bar in narrow `narrow`.
*
* If `narrow` is a stream or topic narrow, this is based on the stream color.
* Otherwise, it takes a default value.
*/
export const getTitleBackgroundColor = (narrow?: Narrow): Selector<string> =>
createSelector(
getSubscriptions,
subscriptions =>
isStreamOrTopicNarrow(narrow)
? (
subscriptions.find(sub => Array.isArray(narrow) && narrow[0].operand === sub.name)
|| NULL_SUBSCRIPTION
).color
: DEFAULT_TITLE_BACKGROUND_COLOR,
);
|
Load new apiUrl module in ac module base | var config = require('./config'),
rest = require('./rest'),
apiUrl = require('./apiUrl'),
projects = require('./projects');
module.exports.init = function () {
/**
* Load config variables as environment variables
*/
for (envVar in config) {
if (config.hasOwnProperty(envVar)) {
process.env[envVar] = config[envVar];
}
}
/**
* If the app is in testing mode, then set the api url
* and api key from the defined testing api url and key
*/
if (config['ENVIRONMENT'] === 'testing') {
process.env['API_URL'] = config['TESTING_API_URL'];
process.env['API_KEY'] = config['TESTING_API_KEY'];
}
return {
'apiUrl': apiUrl,
'projects': projects.projects,
'project': projects.project
};
};
| var config = require('./config'),
rest = require('./rest'),
projects = require('./projects');
module.exports.init = function () {
/**
* Load config variables as environment variables
*/
for (envVar in config) {
if (config.hasOwnProperty(envVar)) {
process.env[envVar] = config[envVar];
}
}
/**
* If the app is in testing mode, then set the api url
* and api key from the defined testing api url and key
*/
if (config['ENVIRONMENT'] === 'testing') {
process.env['API_URL'] = config['TESTING_API_URL'];
process.env['API_KEY'] = config['TESTING_API_KEY'];
}
return {
'projects': projects.projects,
'project': projects.project
};
};
|
Make the ImageView to be of the specific type
Change-Id: I51ced26ea0b654457919d915e322d91eb211f781 | package org.wikimedia.commons.contributions;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import org.wikimedia.commons.MediaWikiImageView;
import org.wikimedia.commons.R;
class ContributionViewHolder {
final MediaWikiImageView imageView;
final TextView titleView;
final TextView stateView;
final TextView seqNumView;
final ProgressBar progressView;
String url;
ContributionViewHolder(View parent) {
imageView = (MediaWikiImageView) parent.findViewById(R.id.contributionImage);
titleView = (TextView)parent.findViewById(R.id.contributionTitle);
stateView = (TextView)parent.findViewById(R.id.contributionState);
seqNumView = (TextView)parent.findViewById(R.id.contributionSequenceNumber);
progressView = (ProgressBar)parent.findViewById(R.id.contributionProgress);
}
}
| package org.wikimedia.commons.contributions;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import org.wikimedia.commons.R;
class ContributionViewHolder {
final ImageView imageView;
final TextView titleView;
final TextView stateView;
final TextView seqNumView;
final ProgressBar progressView;
String url;
ContributionViewHolder(View parent) {
imageView = (ImageView)parent.findViewById(R.id.contributionImage);
titleView = (TextView)parent.findViewById(R.id.contributionTitle);
stateView = (TextView)parent.findViewById(R.id.contributionState);
seqNumView = (TextView)parent.findViewById(R.id.contributionSequenceNumber);
progressView = (ProgressBar)parent.findViewById(R.id.contributionProgress);
}
}
|
Test fix - variable not defined | <?php
namespace NodeRED\Test;
use GuzzleHttp\Psr7\Response;
use NodeRED\OAuth;
use NodeRED\OAuthToken;
class OAuthTest extends \PHPUnit_Framework_TestCase
{
const MOCK_URL = 'https://MOCK/';
public function testGetToken()
{
$successJson = '{"access_token": "A_SECRET_TOKEN","expires_in":604800,"token_type": "Bearer"}';
$response = new Response(200, ['Content-Type' => 'application/json'], $successJson);
$instance = InstanceFactory::getMock([$response]);
$oAuth = new OAuth($instance);
$token = $oAuth->getToken('foo', 'bar');
$this->assertInstanceOf(OAuthToken::class, $token);
}
}
| <?php
namespace NodeRED\Test;
use GuzzleHttp\Psr7\Response;
use NodeRED\OAuth;
use NodeRED\OAuthToken;
class OAuthTest extends \PHPUnit_Framework_TestCase
{
const MOCK_URL = 'https://MOCK/';
public function testGetToken()
{
$successJson = '{"access_token": "A_SECRET_TOKEN","expires_in":604800,"token_type": "Bearer"}';
$response = new Response(200, ['Content-Type' => 'application/json'], $successJson);
$instance = InstanceFactory::getMock([$response]);
$oAuth = new OAuth($instance);
$token = $oAuth->getToken($username, $password);
$this->assertInstanceOf(OAuthToken::class, $token);
}
}
|
Improve wiring in sample app | /*
* Copyright 2012 Robert Burrell Donkin robertburrelldonkin.name
*
* 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 name.robertburrelldonkin.template4couchdb;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App
{
public static void main( String[] args )
{
ApplicationContext context = load();
@SuppressWarnings("unchecked")
CouchDBTemplate<String> template = context.getBean(CouchDBTemplate.class);
System.out.println(template.version(new StringDocumentMapper()));
}
public static ApplicationContext load() {
return new ClassPathXmlApplicationContext("couchdb-context.xml");
}
}
| /*
* Copyright 2012 Robert Burrell Donkin robertburrelldonkin.name
*
* 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 name.robertburrelldonkin.template4couchdb;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App
{
public static void main( String[] args )
{
ApplicationContext context = load();
CouchDBTemplate template = context.getBean(CouchDBTemplate.class);
System.out.println(template.version(new StringDocumentMapper()));
}
public static ApplicationContext load() {
return new ClassPathXmlApplicationContext("couchdb-context.xml");
}
}
|
Change forum title for demo | import Ember from 'ember';
export default Ember.Controller.extend({
// The title of the forum.
// TODO: Preload this value in the index.html payload from Laravel config.
forumTitle: 'Flarum Demo Forum',
// The title of the current page. This should be set as appropriate in
// controllers/views.
pageTitle: '',
// When either the forum title or the page title changes, we want to
// refresh the document's title.
updateTitle: function() {
var parts = [this.get('forumTitle')];
var pageTitle = this.get('pageTitle');
if (pageTitle) {
parts.unshift(pageTitle);
}
document.title = parts.join(' - ');
}.observes('pageTitle', 'forumTitle'),
// Whether or not a pane is currently pinned to the side of the interface.
panePinned: false,
searchQuery: '',
searchActive: false,
actions: {
search: function(query) {
this.transitionToRoute('index', {queryParams: {searchQuery: query, sort: query ? 'relevance' : 'recent'}});
}
}
});
| import Ember from 'ember';
export default Ember.Controller.extend({
// The title of the forum.
// TODO: Preload this value in the index.html payload from Laravel config.
forumTitle: 'Ninetech Support Forum',
// The title of the current page. This should be set as appropriate in
// controllers/views.
pageTitle: '',
// When either the forum title or the page title changes, we want to
// refresh the document's title.
updateTitle: function() {
var parts = [this.get('forumTitle')];
var pageTitle = this.get('pageTitle');
if (pageTitle) {
parts.unshift(pageTitle);
}
document.title = parts.join(' - ');
}.observes('pageTitle', 'forumTitle'),
// Whether or not a pane is currently pinned to the side of the interface.
panePinned: false,
searchQuery: '',
searchActive: false,
actions: {
search: function(query) {
this.transitionToRoute('index', {queryParams: {searchQuery: query, sort: query ? 'relevance' : 'recent'}});
}
}
});
|
Add informational message when running server | let http = require('http');
let url = require('url');
let fs = require('fs');
http.createServer(function (req, res) {
let q = url.parse(req.url, true);
let filename = "app/." + q.pathname;
fs.readFile(filename, function (err, data) {
if (err) {
res.writeHead(404, {'Content-Type': 'text/html'});
return res.end("404 Not Found");
}
let mimeType = 'text/html';
if (filename.endsWith(".css")) {
mimeType = "text/css";
} else if (filename.endsWith(".js")) {
mimeType = "application/javascript";
}
res.writeHead(200, {'Content-Type': mimeType});
res.write(data);
return res.end();
});
}).listen(8080);
console.log("Web server is running...");
console.log("URL to access the app: http://localhost:8080/app.html"); | let http = require('http');
let url = require('url');
let fs = require('fs');
http.createServer(function (req, res) {
let q = url.parse(req.url, true);
let filename = "app/." + q.pathname;
fs.readFile(filename, function (err, data) {
if (err) {
res.writeHead(404, {'Content-Type': 'text/html'});
return res.end("404 Not Found");
}
let mimeType = 'text/html';
if (filename.endsWith(".css")) {
mimeType = "text/css";
} else if (filename.endsWith(".js")) {
mimeType = "application/javascript";
}
res.writeHead(200, {'Content-Type': mimeType});
res.write(data);
return res.end();
});
}).listen(8080); |
Update loader config for test. | <?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2013, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link http://www.phptesting.org/
*/
// Let PHP take a guess as to the default timezone, if the user hasn't set one:
date_default_timezone_set(@date_default_timezone_get());
// Load Composer autoloader:
require_once(dirname(__DIR__) . '/vendor/autoload.php');
// If the PHPCI config file is not where we expect it, try looking in
// env for an alternative config path.
$configFile = dirname(__FILE__) . '/../PHPCI/config.yml';
if (!file_exists($configFile)) {
$configEnv = getenv('phpci_config_file');
if (!empty($configEnv)) {
$configFile = $configEnv;
}
}
// Load configuration if present:
$conf = array();
$conf['b8']['app']['namespace'] = 'PHPCI';
$conf['b8']['app']['default_controller'] = 'Home';
$conf['b8']['view']['path'] = dirname(__DIR__) . '/PHPCI/View/';
$config = new b8\Config($conf);
if (file_exists($configFile)) {
$config->loadYaml($configFile);
}
require_once(dirname(__DIR__) . '/vars.php');
\PHPCI\Helper\Lang::init($config);
| <?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2013, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link http://www.phptesting.org/
*/
// Let PHP take a guess as to the default timezone, if the user hasn't set one:
date_default_timezone_set(@date_default_timezone_get());
// Load Composer autoloader:
require_once(dirname(__DIR__) . '/vendor/autoload.php');
// Load configuration if present:
$conf = array();
$conf['b8']['app']['namespace'] = 'PHPCI';
$conf['b8']['app']['default_controller'] = 'Home';
$conf['b8']['view']['path'] = dirname(__DIR__) . '/../PHPCI/View/';
// If the PHPCI config file is not where we expect it, try looking in
// env for an alternative config path.
$configFile = dirname(__FILE__) . '/../PHPCI/config.yml';
if (!file_exists($configFile)) {
$configEnv = getenv('phpci_config_file');
if (!empty($configEnv)) {
$configFile = $configEnv;
}
}
$config = new b8\Config($conf);
if (file_exists($configFile)) {
$config->loadYaml($configFile);
}
require_once(dirname(__DIR__) . '/vars.php');
\PHPCI\Helper\Lang::init($config);
|
Add a context manager for PDF plot. | """
* Copyright (c) 2016. Mingyu Gao
* All rights reserved.
*
"""
from contextlib import contextmanager
import matplotlib.backends.backend_pdf
from .format import paper_plot
def plot_setup(name, figsize=None, fontsize=9):
""" Setup a PDF page for plot.
name: PDF file name. If not ending with .pdf, will automatically append.
figsize: dimension of the plot in inches, should be an array of length two.
fontsize: fontsize for legends and labels.
"""
paper_plot(fontsize)
if not name.endswith('.pdf'):
name += '.pdf'
pdfpage = matplotlib.backends.backend_pdf.PdfPages(name)
fig = matplotlib.pyplot.figure(figsize=figsize)
return pdfpage, fig
def plot_teardown(pdfpage):
""" Tear down a PDF page after plotting.
pdfpage: PDF page.
"""
pdfpage.savefig()
pdfpage.close()
@contextmanager
def plot_open(name, figsize=None, fontsize=9):
""" Open a context of PDF page for plot, used for the `with` statement.
name: PDF file name. If not ending with .pdf, will automatically append.
figsize: dimension of the plot in inches, should be an array of length two.
fontsize: fontsize for legends and labels.
"""
pdfpage, fig = plot_setup(name, figsize=figsize, fontsize=fontsize)
yield fig
plot_teardown(pdfpage)
| """
* Copyright (c) 2016. Mingyu Gao
* All rights reserved.
*
"""
import matplotlib.backends.backend_pdf
from .format import paper_plot
def plot_setup(name, dims, fontsize=9):
""" Setup a PDF page for plot.
name: PDF file name. If not ending with .pdf, will automatically append.
dims: dimension of the plot in inches, should be an array of length two.
fontsize: fontsize for legends and labels.
"""
paper_plot(fontsize)
if not name.endswith('.pdf'):
name += '.pdf'
pdfpage = matplotlib.backends.backend_pdf.PdfPages(name)
fig = matplotlib.pyplot.figure(figsize=dims)
return pdfpage, fig
def plot_teardown(pdfpage):
""" Tear down a PDF page after plotting.
pdfpage: PDF page.
"""
pdfpage.savefig()
pdfpage.close()
|
Fix remove event listener in OutsideClickHandler | /**
* Outside click document
*/
import React from 'react';
export default class OutsideClickHandler extends React.Component {
static propTypes = {
onOutsideClick: React.PropTypes.func
};
componentDidMount() {
document.addEventListener('click', this.handleDocumentClick, false);
}
componentWillUnmount() {
document.removeEventListener('click', this.handleDocumentClick, false);
}
handleDocumentClick = (event) => {
if (this.props.onOutsideClick === null) {
return;
}
return this.props.onOutsideClick(event);
}
handleMyClick = (event) => {
event.stopPropagation();
event.nativeEvent.stopImmediatePropagation();
}
render() {
return (
<div onClick={this.handleMyClick}>
{this.props.children}
</div>
);
}
}
| /**
* Outside click document
*/
import React from 'react';
export default class OutsideClickHandler extends React.Component {
static propTypes = {
onOutsideClick: React.PropTypes.func
};
componentDidMount() {
document.addEventListener('click', this.handleDocumentClick.bind(this), false);
}
componentWillUnmount() {
document.removeEventListener('click', this.handleDocumentClick.bind(this), false);
}
handleDocumentClick(event) {
if (this.props.onOutsideClick !== null) {
return this.props.onOutsideClick(event);
}
}
handleMyClick(event) {
event.stopPropagation();
event.nativeEvent.stopImmediatePropagation();
}
render() {
return (
<div onClick={this.handleMyClick.bind(this)}>
{this.props.children}
</div>
);
}
}
|
Convert to POST, clean formatting | var sys = require('sys'),
http = require('http'),
base64 = require('./vendor/base64');
// Command line args
var USERNAME = process.ARGV[2];
var PASSWORD = process.ARGV[3];
var SERVER = process.ARGV[4];
if (!USERNAME || !PASSWORD || !SERVER)
return sys.puts("Usage: node server.js <twitter_username> <twitter_password> " +
"<master server>");
var auth = base64.encode(USERNAME + ':' + PASSWORD);
// Connection to Twitter's streaming API
var twitter = http.createClient(80, "stream.twitter.com");
var request = twitter.request("POST", "/1/statuses/filter.json",
{'host': 'stream.twitter.com',
'Authorization': auth,
'Content-Type': 'application/x-www-form-urlencoded'});
request.addListener('response', function (response) {
sys.puts('STATUS: ' + response.statusCode);
response.setBodyEncoding("utf8");
response.addListener("data", function (chunk) {
// Send response to all connected clients
sys.puts('--------------------------------------------');
sys.puts(chunk);
});
});
request.write("track=Bieber");
request.end();
| var sys = require('sys');
var http = require('http');
var base64 = require('./vendor/base64');
// Command line args
var USERNAME = process.ARGV[2];
var PASSWORD = process.ARGV[3];
var SERVER = process.ARGV[4];
if (!USERNAME || !PASSWORD || !SERVER)
return sys.puts("Usage: node server.js <twitter_username> <twitter_password> " +
"<master server>");
var auth = base64.encode(USERNAME + ':' + PASSWORD);
// Connection to Twitter's streaming API
var twitter = http.createClient(80, "stream.twitter.com");
var request = twitter.request("GET", "/1/statuses/filter.json?track=Bieber",
{'host': 'stream.twitter.com',
'Authorization': auth });
request.addListener('response', function (response) {
sys.puts('STATUS: ' + response.statusCode);
response.setBodyEncoding("utf8");
response.addListener("data", function (chunk) {
// Send response to all connected clients
sys.puts(chunk);
});
});
request.end();
|
Make footnote textarea expand upon focus | var updatePreviewTarget = function(data, status) {
$('.spinner').hide();
$('#preview-target').html(data);
renderLatexExpressions();
}
var renderLatexExpressions = function() {
$('.latex-container').each(
function(index) {
katex.render(
this.textContent,
this,
{ displayMode: $(this).data('displaymode') == 'block' }
);
}
);
}
var main = function() {
$('div code').each(function(i, block) {
hljs.highlightBlock(block);
});
$('button#preview').click(
function() {
$('#preview-target').html('');
$('.spinner').show();
$('h1.preview').text($('input[name=title]').val())
$.post('/note_preview', {text: $('#note-txt').val()}, updatePreviewTarget);
}
);
renderLatexExpressions();
$("textarea[name='footnotes']").focusin(function(){
$(this).height($(this).height() + 300);
}).focusout(function(){
$(this).height($(this).height() - 300);
});
};
function searchRedirect(event, searchpage) {
var term = (arguments.length == 2) ? document.getElementById('mainsearch').value : document.getElementById('searchbox').value;
window.location = '/search/' + term + '/';
event.preventDefault(event);
}
$(main);
| var updatePreviewTarget = function(data, status) {
$('.spinner').hide();
$('#preview-target').html(data);
renderLatexExpressions();
}
var renderLatexExpressions = function() {
$('.latex-container').each(
function(index) {
katex.render(
this.textContent,
this,
{ displayMode: $(this).data('displaymode') == 'block' }
);
}
);
}
var main = function() {
$('div code').each(function(i, block) {
hljs.highlightBlock(block);
});
$('button#preview').click(
function() {
$('#preview-target').html('');
$('.spinner').show();
$('h1.preview').text($('input[name=title]').val())
$.post('/note_preview', {text: $('#note-txt').val()}, updatePreviewTarget);
}
);
renderLatexExpressions();
};
function searchRedirect(event, searchpage) {
var term = (arguments.length == 2) ? document.getElementById('mainsearch').value : document.getElementById('searchbox').value;
window.location = '/search/' + term + '/';
event.preventDefault(event);
}
$(main);
|
Remove unnecessary BaseText from popover | import React from 'react';
import PropTypes from 'prop-types';
import Popover from './Popover';
import OverlayPropTypes from '../../utils/OverlayPropTypes';
import useOverlay from '../../hooks/useOverlay';
export default function injectPopover(Component) {
const propTypes = {
tooltip: PropTypes.shape({
title: PropTypes.string,
content: PropTypes.string.isRequired,
...OverlayPropTypes,
}),
};
function OverlayPopover(props) {
const {
popover: {
title,
content,
delay,
trigger = 'click',
placement = 'right',
fallbackPlacement,
},
...elementProps
} = props;
const target = <Component {...elementProps} />;
const template = (
<Popover>
{title && <Popover.Header>{title}</Popover.Header>}
<Popover.Body>{content}</Popover.Body>
</Popover>
);
return useOverlay(target, template, {
delay,
trigger,
placement,
fallbackPlacement,
});
}
OverlayPopover.displayName = 'Overlay(Popover)';
OverlayPopover.propTypes = propTypes;
return OverlayPopover;
}
| import React from 'react';
import PropTypes from 'prop-types';
import Popover from './Popover';
import BaseText from '../../utils/rnw-compat/BaseText';
import OverlayPropTypes from '../../utils/OverlayPropTypes';
import useOverlay from '../../hooks/useOverlay';
export default function injectPopover(Component) {
const propTypes = {
tooltip: PropTypes.shape({
title: PropTypes.string,
content: PropTypes.string.isRequired,
...OverlayPropTypes,
}),
};
function OverlayPopover(props) {
const {
popover: {
title,
content,
delay,
trigger = 'click',
placement = 'right',
fallbackPlacement,
},
...elementProps
} = props;
const target = <Component {...elementProps} />;
const template = (
<Popover>
{title && <Popover.Header>{title}</Popover.Header>}
<Popover.Body>
<BaseText essentials={{}}>{content}</BaseText>
</Popover.Body>
</Popover>
);
return useOverlay(target, template, {
delay,
trigger,
placement,
fallbackPlacement,
});
}
OverlayPopover.displayName = 'Overlay(Popover)';
OverlayPopover.propTypes = propTypes;
return OverlayPopover;
}
|
[Glitch] Fix style of legacy column headers
Backports daefbd66a653b11a17be73b7b0a4ca200b466cec | import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
export default class ColumnHeader extends React.PureComponent {
static propTypes = {
icon: PropTypes.string,
type: PropTypes.string,
active: PropTypes.bool,
onClick: PropTypes.func,
columnHeaderId: PropTypes.string,
};
handleClick = () => {
this.props.onClick();
}
render () {
const { icon, type, active, columnHeaderId } = this.props;
let iconElement = '';
if (icon) {
iconElement = <i className={`fa fa-fw fa-${icon} column-header__icon`} />;
}
return (
<h1 className={classNames('column-header', { active })} id={columnHeaderId || null}>
<button onClick={this.handleClick}>
{iconElement}
{type}
</button>
</h1>
);
}
}
| import React from 'react';
import PropTypes from 'prop-types';
export default class ColumnHeader extends React.PureComponent {
static propTypes = {
icon: PropTypes.string,
type: PropTypes.string,
active: PropTypes.bool,
onClick: PropTypes.func,
columnHeaderId: PropTypes.string,
};
handleClick = () => {
this.props.onClick();
}
render () {
const { type, active, columnHeaderId } = this.props;
let icon = '';
if (this.props.icon) {
icon = <i className={`fa fa-fw fa-${this.props.icon} column-header__icon`} />;
}
return (
<div role='heading' tabIndex='0' className={`column-header ${active ? 'active' : ''}`} onClick={this.handleClick} id={columnHeaderId || null}>
{icon}
{type}
</div>
);
}
}
|
Add HTTP cache in Github request/response
As we are running this command many times, there's no reason to query every
time the Github to retrieve the same information. | // gddoexp is a command line tool crated to list eligible packages for
// archiving in GoDoc.org
package main
import (
"fmt"
"net/http"
"os"
"path"
"github.com/golang/gddo/database"
"github.com/gregjones/httpcache"
"github.com/gregjones/httpcache/diskcache"
"github.com/rafaeljusto/gddoexp"
)
func main() {
// add cache to avoid to repeated requests to Github
gddoexp.HTTPClient = &http.Client{
Transport: httpcache.NewTransport(
diskcache.New(path.Join(os.Getenv("HOME"), ".gddoexp")),
),
}
db, err := database.New()
if err != nil {
fmt.Println("error connecting to database:", err)
return
}
pkgs, err := db.AllPackages()
if err != nil {
fmt.Println("error retrieving all packages:", err)
return
}
for _, pkg := range pkgs {
if archive, err := gddoexp.ShouldArchivePackage(pkg.Path, db); err != nil {
fmt.Println(err)
} else if archive {
fmt.Printf("package “%s” should be archived\n", pkg.Path)
}
}
}
| // gddoexp is a command line tool crated to list eligible packages for
// archiving in GoDoc.org
package main
import (
"fmt"
"github.com/golang/gddo/database"
"github.com/rafaeljusto/gddoexp"
)
func main() {
db, err := database.New()
if err != nil {
fmt.Println("error connecting to database:", err)
return
}
pkgs, err := db.AllPackages()
if err != nil {
fmt.Println("error retrieving all packages:", err)
return
}
for _, pkg := range pkgs {
if archive, err := gddoexp.ShouldArchivePackage(pkg.Path, db); err != nil {
fmt.Println(err)
} else if archive {
fmt.Printf("package “%s” should be archived\n", pkg.Path)
}
}
}
|
Revert "Try less than 2.0."
This reverts commit 1bffae34a767e56943bb83027719fbe6dffcdc3b. | import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='mdot',
version='0.1',
packages=['mdot'],
include_package_data=True,
install_requires=[
'setuptools',
'django<1.9rc1',
'django-compressor',
'django_mobileesp',
'uw-restclients==1.1',
'django-htmlmin',
],
license='Apache License, Version 2.0',
description='A Django app to ...',
long_description=README,
url='http://www.example.com/',
author='Your Name',
author_email='yourname@example.com',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
| import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='mdot',
version='0.1',
packages=['mdot'],
include_package_data=True,
install_requires=[
'setuptools',
'django<1.9rc1',
'django-compressor',
'django_mobileesp',
'uw-restclients<2.0',
'django-htmlmin',
],
license='Apache License, Version 2.0',
description='A Django app to ...',
long_description=README,
url='http://www.example.com/',
author='Your Name',
author_email='yourname@example.com',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
|
Add argparse as a dependency to setyp.py
Needed for python 2.6
Change-Id: I87df47c7b814024b1ec91d227f45762711de03c0 | """
setup.py
"""
__author__ = 'Gavin M. Roy'
__email__ = 'gmr@myyearbook.com'
__since__ = '2011-09-13'
from hockeyapp import __version__
from setuptools import setup
long_description = """Python client for the HockeyApp.net API"""
setup(name='hockeyapp',
version=__version__,
description="HockeyApp.net API",
long_description=long_description,
classifiers=[
'Development Status :: 4 - Beta',
],
author='Gavin M. Roy',
author_email='gmr@myyearbook.com',
url='http://github.com/gmr/hockeyapp',
packages=['hockeyapp'],
entry_points=dict(console_scripts=['hockeyapp-cli=hockeyapp.cli:main']),
zip_safe=True,
install_requires=[
'poster', 'argparse'
])
| """
setup.py
"""
__author__ = 'Gavin M. Roy'
__email__ = 'gmr@myyearbook.com'
__since__ = '2011-09-13'
from hockeyapp import __version__
from setuptools import setup
long_description = """Python client for the HockeyApp.net API"""
setup(name='hockeyapp',
version=__version__,
description="HockeyApp.net API",
long_description=long_description,
classifiers=[
'Development Status :: 4 - Beta',
],
author='Gavin M. Roy',
author_email='gmr@myyearbook.com',
url='http://github.com/gmr/hockeyapp',
packages=['hockeyapp'],
entry_points=dict(console_scripts=['hockeyapp-cli=hockeyapp.cli:main']),
zip_safe=True,
install_requires=[
'poster'
])
|
Adjust tests for the new interface | 'use strict';
var expect = require('chai').expect;
var floraCluster = require('../');
describe('flora-cluster', function () {
it('should be an object', function () {
expect(floraCluster).to.be.an('object');
});
it('should expose master and worker objects', function () {
expect(floraCluster).to.have.property('Master');
expect(floraCluster).to.have.property('Worker');
});
describe('Worker', function () {
it('should be a function', function () {
expect(floraCluster.Worker).to.be.a('function');
});
describe('instance', function () {
var worker = new floraCluster.Worker();
it('should expose functions', function () {
expect(worker).to.have.property('run');
expect(worker).to.have.property('attach');
expect(worker).to.have.property('serverStatus');
expect(worker).to.have.property('shutdown');
});
});
});
});
| 'use strict';
var expect = require('chai').expect;
var floraCluster = require('../');
describe('flora-cluster', function () {
it('should be an object', function () {
expect(floraCluster).to.be.an('object');
});
it('should expose master and worker objects', function () {
expect(floraCluster).to.have.property('master');
expect(floraCluster).to.have.property('worker');
});
describe('worker', function () {
it('should be an object', function () {
expect(floraCluster.worker).to.be.an('object');
});
it('should expose functions', function () {
expect(floraCluster.worker).to.have.property('run');
expect(floraCluster.worker).to.have.property('attach');
expect(floraCluster.worker).to.have.property('serverStatus');
expect(floraCluster.worker).to.have.property('shutdown');
});
});
});
|
Update to Redux 1.0 RC | import isPromise from './isPromise';
export default function promiseMiddleware() {
return next => action => {
if (!isPromise(action.payload)) {
return next(action);
}
const { types } = action;
const promise = action.payload;
const [ PENDING, FULFILLED, REJECTED ] = types;
/**
* Dispatch the first async handler. This tells the
* reducer that an async action has been dispatched.
*/
next({
type: PENDING
});
/**
* Return either the fulfilled action object or the rejected
* action object.
*/
return promise.then(
payload => next({
payload,
type: FULFILLED
}),
error => next({
payload: error,
type: REJECTED
})
);
};
}
| import isPromise from './isPromise';
export default function promiseMiddleware(next) {
return action => {
if (!isPromise(action.payload)) {
return next(action);
}
const { types } = action;
const promise = action.payload;
const [ PENDING, FULFILLED, REJECTED ] = types;
/**
* Dispatch the first async handler. This tells the
* reducer that an async action has been dispatched.
*/
next({
type: PENDING
});
/**
* Return either the fulfilled action object or the rejected
* action object.
*/
return promise.then(
payload => next({
payload,
type: FULFILLED
}),
error => next({
payload: error,
type: REJECTED
})
);
};
}
|
Complete the information for the help-plugin | <?php
class hash extends Script
{
protected $availableAlgos;
protected $helpMessage = "hash ALGORITHM STRING";
protected $description = 'Returns the hash of the given string, hashed with the given algorithm';
function __construct($message, $matches, $waConnection)
{
$this->availableAlgos = hash_algos();
$this->matches = $matches;
$this->message = $message;
$this->waConnection = $waConnection;
}
public function run()
{
if(!in_array(strtolower($this->matches[1]), $this->availableAlgos)) {
$this->response = $this->matches[1] . " is not supported!\n";
$this->response .= "Available algorithms:\n";
foreach ($this->availableAlgos as $value) {
$this->response .= $value . "\n";
}
return $this->send($this->response);
} else {
return $this->send(hash($this->matches[1], $this->matches[2]));
}
}
function __destruct()
{
}
}
| <?php
class hash extends Script
{
protected $availableAlgos;
protected $helpMessage = 'Returns a hash of the given string, hashed with the given algorithm';
function __construct($message, $matches, $waConnection)
{
$this->availableAlgos = hash_algos();
$this->matches = $matches;
$this->message = $message;
$this->waConnection = $waConnection;
}
public function run()
{
if(!in_array(strtolower($this->matches[1]), $this->availableAlgos)) {
$this->response = $this->matches[1] . " is not supported!\n";
$this->response .= "Available algorithms:\n";
foreach ($this->availableAlgos as $value) {
$this->response .= $value . "\n";
}
return $this->send($this->response);
} else {
return $this->send(hash($this->matches[1], $this->matches[2]));
}
}
function __destruct()
{
}
}
|
Add multi_select in the DateEditor params for Custom editors. | #------------------------------------------------------------------------------
#
# Copyright (c) 2008, Enthought, Inc.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in enthought/LICENSE.txt and may be redistributed only
# under the conditions described in the aforementioned license. The license
# is also available online at http://www.enthought.com/licenses/BSD.txt
#
# Thanks for using Enthought open source!
#
# Author: Judah De Paula
# Date: 10/7/2008
#
#------------------------------------------------------------------------------
"""
A Traits UI editor that wraps a WX calendar panel.
"""
import datetime
from enthought.traits.traits import Property
from enthought.traits.trait_types import Bool
from enthought.traits.ui.editor_factory import EditorFactory
from enthought.traits.ui.toolkit import toolkit_object
#-- DateEditor definition -----------------------------------------------------
class DateEditor ( EditorFactory ):
"""
Editor factory for date/time editors.
"""
#---------------------------------------------------------------------------
# Trait definitions:
#---------------------------------------------------------------------------
# Custom date editors can operate on a list of Dates, or just one.
multi_select = Bool(True)
#-- end DateEditor definition -------------------------------------------------
#-- eof -----------------------------------------------------------------------
| #------------------------------------------------------------------------------
#
# Copyright (c) 2008, Enthought, Inc.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in enthought/LICENSE.txt and may be redistributed only
# under the conditions described in the aforementioned license. The license
# is also available online at http://www.enthought.com/licenses/BSD.txt
#
# Thanks for using Enthought open source!
#
# Author: Judah De Paula
# Date: 10/7/2008
#
#------------------------------------------------------------------------------
"""
A Traits UI editor that wraps a WX calendar panel.
"""
import datetime
from enthought.traits.traits import Property
from enthought.traits.ui.editor_factory import EditorFactory
from enthought.traits.ui.toolkit import toolkit_object
#-- DateEditor definition -----------------------------------------------------
class DateEditor ( EditorFactory ):
"""
Editor factory for date/time editors.
"""
#---------------------------------------------------------------------------
# Trait definitions:
#---------------------------------------------------------------------------
# TODO: Placeholder for date-editor-specific traits.
pass
#-- end DateEditor definition -------------------------------------------------
#-- eof -----------------------------------------------------------------------
|
Remove trailing single quote typo in favicon URL | import React from 'react';
import Head from 'next/head';
import { color } from 'lib/variables';
/**
* Adds the Lagoon icon as the favicon for the website.
*/
const Favicon = () => (
<Head>
<link rel="apple-touch-icon" sizes="180x180" href="/static/images/favicons/apple-touch-icon.png" />
<link rel="icon" type="image/png" sizes="32x32" href="/static/images/favicons/favicon-32x32.png" />
<link rel="icon" type="image/png" sizes="16x16" href="/static/images/favicons/favicon-16x16.png" />
<meta name="apple-mobile-web-app-title" content="Lagoon" />
<meta name="application-name" content="Lagoon" />
<meta name="msapplication-TileColor" content={color.blue} />
<meta name="theme-color" content={color.white} />
</Head>
);
export default Favicon;
| import React from 'react';
import Head from 'next/head';
import { color } from 'lib/variables';
/**
* Adds the Lagoon icon as the favicon for the website.
*/
const Favicon = () => (
<Head>
<link rel="apple-touch-icon" sizes="180x180" href="/static/images/favicons/apple-touch-icon.png" />
<link rel="icon" type="image/png" sizes="32x32" href="/static/images/favicons/favicon-32x32.png'" />
<link rel="icon" type="image/png" sizes="16x16" href="/static/images/favicons/favicon-16x16.png" />
<meta name="apple-mobile-web-app-title" content="Lagoon" />
<meta name="application-name" content="Lagoon" />
<meta name="msapplication-TileColor" content={color.blue} />
<meta name="theme-color" content={color.white} />
</Head>
);
export default Favicon;
|
Disable sourcemaps since we don't use them | exports.files = {
javascripts: {
joinTo: {
'fateOfAllFools.js': /^(?!spec)/
}
},
stylesheets: {
joinTo: 'fateOfAllFools.css'
}
};
/*
Tests are handled by Karma. This is to silence a warning that Brunch
reports (which is helpful actually in most cases!) because it sees JS files
outside the scope of its purview.
*/
exports.conventions = {
ignored: /^spec/
};
/*
Inject our message bus (wrapper around Postal) in to each module. We use
the bus to communicate and need a hook to be able to silence events when
those modules are not under test.
*/
exports.modules = {
wrapper: (path, data) => {
const fateBusTemplate = `
const fateBus = require('fateBus.js');
fateBus.registerModule(module);
`;
return `
require.register("${path}", function(exports, require, module) {
${(path === 'fateBus.js') ? ('') : (fateBusTemplate)}
${data}
});`
},
autoRequire: {
'fateOfAllFools.js': ['fateBus.js', 'main.js']
}
}
// Doesn't fit our debugging style
exports.sourceMaps = false;
| exports.files = {
javascripts: {
joinTo: {
'fateOfAllFools.js': /^(?!spec)/
}
},
stylesheets: {
joinTo: 'fateOfAllFools.css'
}
};
/*
Tests are handled by Karma. This is to silence a warning that Brunch
reports (which is helpful actually in most cases!) because it sees JS files
outside the scope of its purview.
*/
exports.conventions = {
ignored: /^spec/
};
/*
Inject our message bus (wrapper around Postal) in to each module. We use
the bus to communicate and need a hook to be able to silence events when
those modules are not under test.
*/
exports.modules = {
wrapper: (path, data) => {
const fateBusTemplate = `
const fateBus = require('fateBus.js');
fateBus.registerModule(module);
`;
return `
require.register("${path}", function(exports, require, module) {
${(path === 'fateBus.js') ? ('') : (fateBusTemplate)}
${data}
});`
},
autoRequire: {
'fateOfAllFools.js': ['fateBus.js', 'main.js']
}
}
|
BAP-108: Implement basic sorter interface
- implemented sorter factory and sorter interfaces
- refactored parameters interface | <?php
namespace Acme\Bundle\DemoGridBundle\Datagrid;
use Oro\Bundle\GridBundle\Datagrid\DatagridManager;
use Oro\Bundle\GridBundle\Field\FieldDescription;
class UserDatagridManager extends DatagridManager
{
/**
* {@inheritdoc}
*/
protected function getListFields()
{
$email = new FieldDescription();
$email->setName('email');
$email->setOption('label', 'Email');
$firstName = new FieldDescription();
$firstName->setName('firstname');
$firstName->setOption('label', 'Firstname');
$lastName = new FieldDescription();
$lastName->setName('lastname');
$lastName->setOption('label', 'Lastname');
return array($email, $firstName, $lastName);
}
/**
* @return array
*/
protected function getSorters()
{
return array();
}
}
| <?php
namespace Acme\Bundle\DemoGridBundle\Datagrid;
use Oro\Bundle\GridBundle\Datagrid\DatagridManager;
use Oro\Bundle\GridBundle\Field\FieldDescription;
class UserDatagridManager extends DatagridManager
{
/**
* {@inheritdoc}
*/
protected function getListFields()
{
$email = new FieldDescription();
$email->setName('email');
$email->setOption('label', 'Email');
$firstName = new FieldDescription();
$firstName->setName('firstname');
$firstName->setOption('label', 'Firstname');
$lastName = new FieldDescription();
$lastName->setName('lastname');
$lastName->setOption('label', 'Lastname');
return array($email, $firstName, $lastName);
}
}
|
Add trailing comma to satisfy linter | const pgp = require('pg-promise')()
const dbName = 'vinyl'
const connectionString = process.env.DATABASE_URL || `postgres://localhost:5432/${dbName}`
const db = pgp(connectionString)
const getAlbums = () => {
return db.query('SELECT * FROM albums')
}
const getAlbumById = (albumId) => {
return db.one(`
SELECT * FROM albums
WHERE id = $1
`, [albumId])
}
const getUserByEmail = (email) => {
return db.one(`
SELECT * FROM users WHERE LOWER(email) = LOWER($1)
`, [email])
.catch((error) => {
console.error('\nError in queries.getUserByEmail\n')
throw error
})
}
const createUser = (name, email, password) => {
return db.none(`
INSERT INTO
users (name, email, password)
VALUES
($1, $2, $3)
`, [name, email, password])
}
module.exports = {
getAlbums,
getAlbumById,
createUser,
getUserByEmail,
}
| const pgp = require('pg-promise')()
const dbName = 'vinyl'
const connectionString = process.env.DATABASE_URL || `postgres://localhost:5432/${dbName}`
const db = pgp(connectionString)
const getAlbums = () => {
return db.query('SELECT * FROM albums')
}
const getAlbumById = (albumId) => {
return db.one(`
SELECT * FROM albums
WHERE id = $1
`, [albumId])
}
const getUserByEmail = (email) => {
return db.one(`
SELECT * FROM users WHERE LOWER(email) = LOWER($1)
`, [email])
.catch((error) => {
console.error('\nError in queries.getUserByEmail\n')
throw error
})
}
const createUser = (name, email, password) => {
return db.none(`
INSERT INTO
users (name, email, password)
VALUES
($1, $2, $3)
`, [name, email, password])
}
module.exports = {
getAlbums,
getAlbumById,
createUser,
getUserByEmail
}
|
Add char count and disable submit feature | import React from 'react';
export default class MessageInput extends React.Component {
constructor() {
super();
this.state = {
input: '',
charLimit: 140,
};
}
submitItem() {
this.props.displayMessage(this.state);
this.clearField();
}
clearField() {
this.setState({ input: '' });
}
inputField(e){
this.setState({input: e.target.value})
}
enableSubmit() {
let typedChar = this.state.charLimit - this.state.input.length
return typedChar > 0 && typedChar < this.state.charLimit ? false : true
}
render() {
return (
<div>
<input
type='text'
placeholder='Message'
value={this.state.input}
onChange={(e)=>{ this.inputField(e) }}/>
<button
disabled={this.enableSubmit()}
type='submit' onClick={() => { this.submitItem()}}>Submit</button>
<button onClick={()=> this.clearField()}>Clear</button>
<h5>{this.state.charLimit - this.state.input.length}</h5>
</div>
);
}
};
| import React from 'react';
export default class MessageInput extends React.Component {
constructor() {
super();
this.state = {
input: '',
};
}
submitItem() {
this.props.displayMessage(this.state);
this.clearField();
}
clearField() {
this.setState({ input: '' });
}
inputField(e){
this.setState({input: e.target.value})
}
render() {
return (
<div>
<input
type='text'
placeholder='Message'
value={this.state.input}
onChange={(e)=>{ this.inputField(e) }}/>
<button type='submit' onClick={() => { this.submitItem()}}>Submit</button>
<button onClick={()=> this.clearField()}>Clear</button>
</div>
);
}
};
|
Add variable in test for search ~/.vim | package main
import (
"fmt"
"os"
"path/filepath"
"testing"
"github.com/mitchellh/go-homedir"
)
var (
home, errInit = homedir.Dir()
dotvim = filepath.Join(home, ".vim")
)
func TestMain(m *testing.M) {
if errInit != nil {
fmt.Fprintln(os.Stderr, "vub:", errInit)
os.Exit(1)
}
os.Exit(m.Run())
}
var sourceURITests = []struct {
src string
dst string
}{
//Full URI
{
"https://github.com/sunaku/vim-unbundle",
"https://github.com/sunaku/vim-unbundle",
},
//Short GitHub URI
{
"Shougo/neobundle.vim",
"https://github.com/Shougo/neobundle.vim",
},
{
"thinca/vim-quickrun",
"https://github.com/thinca/vim-quickrun",
},
}
func TestSourceURI(t *testing.T) {
for _, test := range sourceURITests {
expect := test.dst
actual, err := ToSourceURI(test.src)
if err != nil {
t.Errorf("ToSourceURI(%q) returns %q, want nil", err)
}
if actual != expect {
t.Errorf("%q: got %q, want %q",
test.src, actual, expect)
}
}
}
| package main
import (
"testing"
)
var sourceURITests = []struct {
src string
dst string
}{
//Full URI
{
"https://github.com/sunaku/vim-unbundle",
"https://github.com/sunaku/vim-unbundle",
},
//Short GitHub URI
{
"Shougo/neobundle.vim",
"https://github.com/Shougo/neobundle.vim",
},
{
"thinca/vim-quickrun",
"https://github.com/thinca/vim-quickrun",
},
}
func TestSourceURI(t *testing.T) {
for _, test := range sourceURITests {
expect := test.dst
actual, err := ToSourceURI(test.src)
if err != nil {
t.Errorf("ToSourceURI(%q) returns %q, want nil", err)
}
if actual != expect {
t.Errorf("%q: got %q, want %q",
test.src, actual, expect)
}
}
}
|
Reduce transient memory consumption of lib/image.Image.ListMissingObjects(). | package image
import (
"github.com/Symantec/Dominator/lib/hash"
"github.com/Symantec/Dominator/lib/objectserver"
)
func (image *Image) listObjects() []hash.Hash {
hashes := make([]hash.Hash, 0, image.FileSystem.NumRegularInodes+2)
image.forEachObject(func(hashVal hash.Hash) error {
hashes = append(hashes, hashVal)
return nil
})
return hashes
}
func (image *Image) listMissingObjects(
objectsChecker objectserver.ObjectsChecker) ([]hash.Hash, error) {
hashBuffer := make([]hash.Hash, 1024)
var missingObjects []hash.Hash
index := 0
image.forEachObject(func(hashVal hash.Hash) error {
hashBuffer[index] = hashVal
index++
if index < len(hashBuffer) {
return nil
}
var err error
missingObjects, err = listMissingObjects(missingObjects, hashBuffer,
objectsChecker)
if err != nil {
return err
}
index = 0
return nil
})
return listMissingObjects(missingObjects, hashBuffer[:index],
objectsChecker)
}
func listMissingObjects(missingObjects, hashes []hash.Hash,
objectsChecker objectserver.ObjectsChecker) ([]hash.Hash, error) {
objectSizes, err := objectsChecker.CheckObjects(hashes)
if err != nil {
return nil, err
}
for index, size := range objectSizes {
if size < 1 {
missingObjects = append(missingObjects, hashes[index])
}
}
return missingObjects, nil
}
| package image
import (
"github.com/Symantec/Dominator/lib/hash"
"github.com/Symantec/Dominator/lib/objectserver"
)
func (image *Image) listObjects() []hash.Hash {
hashes := make([]hash.Hash, 0, image.FileSystem.NumRegularInodes+2)
image.forEachObject(func(hashVal hash.Hash) error {
hashes = append(hashes, hashVal)
return nil
})
return hashes
}
func (image *Image) listMissingObjects(
objectsChecker objectserver.ObjectsChecker) ([]hash.Hash, error) {
// TODO(rgooch): Implement an API that avoids copying hash lists.
hashes := image.ListObjects()
objectSizes, err := objectsChecker.CheckObjects(hashes)
if err != nil {
return nil, err
}
var missingObjects []hash.Hash
for index, size := range objectSizes {
if size < 1 {
missingObjects = append(missingObjects, hashes[index])
}
}
return missingObjects, nil
}
|
Check if ObjectId is type | var Mystique = require('mystique');
var Mongoose = require('mongoose');
var ObjectId = Mongoose.Types.ObjectId;
var getIdForModel = function(model, propertyName) {
var prop = model.get(propertyName);
if (prop instanceof ObjectId) {
return prop;
}
return prop.id;
};
var CheckInTransformer = Mystique.Transformer.extend({
resourceName: 'checkIn',
mapOut: function(checkIn) {
return {
book: getIdForModel(checkIn, 'book'),
checkedInAt: checkIn.checkedInAt,
checkedOutAt: checkIn.checkedOutAt,
};
},
mapIn(req) {
return {
book: req.body.checkIn.book,
checkedInAt: req.body.checkIn.checkedInAt,
checkedOutAt: req.body.checkIn.checkedOutAt,
};
},
});
Mystique.registerTransformer('CheckIn', CheckInTransformer);
| var Mystique = require('mystique');
var Mystique = require('mystique');
var getIdForModel = function(model, propertyName) {
var prop = model.get(propertyName);
if (typeof prop === 'string') {
return prop;
}
return prop.id;
};
var CheckInTransformer = Mystique.Transformer.extend({
resourceName: 'checkIn',
mapOut: function(checkIn) {
return {
// book: getIdForModel(checkIn, 'book'),
book: checkIn.get('book'),
checkedInAt: checkIn.checkedInAt,
checkedOutAt: checkIn.checkedOutAt,
};
},
mapIn(req) {
return {
book: req.body.checkIn.book,
checkedInAt: req.body.checkIn.checkedInAt,
checkedOutAt: req.body.checkIn.checkedOutAt,
};
},
});
Mystique.registerTransformer('CheckIn', CheckInTransformer);
|
Use proper symbol for square meters | import PropTypes from 'prop-types';
import React from 'react';
import { AREA_UNITS } from '../../constants/units';
const AreaUnits = ({ value, unit, className, ...rest }) => {
switch (unit) {
case AREA_UNITS.METERS_SQUARED: return (
<span
{ ...rest }
className={ className }
>
{ value }
m²
</span>
);
case AREA_UNITS.SQUARE_FOOT:
default: return (
<span
{ ...rest }
className={ className }
>
{ value } sq ft
</span>
);
}
};
AreaUnits.propTypes = {
value: PropTypes.oneOfType([
PropTypes.number,
PropTypes.string,
]).isRequired,
unit: PropTypes.string.isRequired,
className: PropTypes.string,
};
AreaUnits.defaultProps = {
unit: AREA_UNITS.SQUARE_FOOT,
};
export default AreaUnits;
| import PropTypes from 'prop-types';
import React from 'react';
import { AREA_UNITS } from '../../constants/units';
const AreaUnits = ({ value, unit, className, ...rest }) => {
switch (unit) {
case AREA_UNITS.METERS_SQUARED: return (
<span
{ ...rest }
className={ className }
>
{ value }
m<sup>2</sup>
</span>
);
case AREA_UNITS.SQUARE_FOOT:
default: return (
<span
{ ...rest }
className={ className }
>
{ value } sq ft
</span>
);
}
};
AreaUnits.propTypes = {
value: PropTypes.oneOfType([
PropTypes.number,
PropTypes.string,
]).isRequired,
unit: PropTypes.string.isRequired,
className: PropTypes.string,
};
AreaUnits.defaultProps = {
unit: AREA_UNITS.SQUARE_FOOT,
};
export default AreaUnits;
|
Test issue with expected exception | <?php
/*
* This file is part of the Sonata package.
*
* (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sonata\BlockBundle\Tests\Block;
use Sonata\BlockBundle\Block\Loader\ServiceLoader;
class ServiceLoaderTest extends \PHPUnit_Framework_TestCase
{
/**
* @expectedException RuntimeException
*/
public function testBlockNotFoundException()
{
$loader = new ServiceLoader(array());
$loader->load('foo');
}
public function testLoader()
{
$loader = new ServiceLoader(array('foo.bar' => array('option1' => 42)));
$definition = array(
'type' => 'foo.bar',
'settings' => array('option2' => 23)
);
$this->assertTrue($loader->support($definition));
$this->assertInstanceOf('Sonata\BlockBundle\Model\BlockInterface', $loader->load($definition));
}
} | <?php
/*
* This file is part of the Sonata package.
*
* (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sonata\BlockBundle\Tests\Block;
use Sonata\BlockBundle\Block\Loader\ServiceLoader;
class ServiceLoaderTest extends \PHPUnit_Framework_TestCase
{
/**
* @expectedException \RuntimeException
*/
public function testBlockNotFoundException()
{
$loader = new ServiceLoader(array());
$loader->load('foo');
}
public function testLoader()
{
$loader = new ServiceLoader(array('foo.bar' => array('option1' => 42)));
$definition = array(
'type' => 'foo.bar',
'settings' => array('option2' => 23)
);
$this->assertTrue($loader->support($definition));
$this->assertInstanceOf('Sonata\BlockBundle\Model\BlockInterface', $loader->load($definition));
}
} |
[cli] Fix 'react-native start' on Windows
Based on https://github.com/facebook/react-native/pull/2989
Thanks @BerndWessels! | 'use strict';
var path = require('path');
var child_process = require('child_process');
module.exports = function(newWindow) {
if (newWindow) {
var launchPackagerScript =
path.resolve(__dirname, '..', 'packager', 'launchPackager.command');
if (process.platform === 'darwin') {
child_process.spawnSync('open', [launchPackagerScript]);
} else if (process.platform === 'linux') {
child_process.spawn(
'xterm',
['-e', 'sh', launchPackagerScript],
{detached: true});
}
} else {
if (/^win/.test(process.platform)) {
child_process.spawn('node', [
path.resolve(__dirname, '..', 'packager', 'packager.js'),
'--projectRoots',
process.cwd(),
], {stdio: 'inherit'});
} else {
child_process.spawn('sh', [
path.resolve(__dirname, '..', 'packager', 'packager.sh'),
'--projectRoots',
process.cwd(),
], {stdio: 'inherit'});
}
}
};
| 'use strict';
var path = require('path');
var child_process = require('child_process');
module.exports = function(newWindow) {
if (newWindow) {
var launchPackagerScript =
path.resolve(__dirname, '..', 'packager', 'launchPackager.command');
if (process.platform === 'darwin') {
child_process.spawnSync('open', [launchPackagerScript]);
} else if (process.platform === 'linux') {
child_process.spawn(
'xterm',
['-e', 'sh', launchPackagerScript],
{detached: true});
}
} else {
child_process.spawn('sh', [
path.resolve(__dirname, '..', 'packager', 'packager.sh'),
'--projectRoots',
process.cwd(),
], {stdio: 'inherit'});
}
};
|
Clear flashed messages on reset | $('#send').submit(function(e) {
$('.flash').text("");
var name = $('#name').val();
var email = $('#email').val();
var text = $('#text').val();
if (name && email && text) {
console.log('Conditions met.');
emailjs.send("gmail", "standard",
{
"name": name,
"email": email,
"message": text
}).then(function(response) {
console.log(response.status + response.text);
$('.flash').text("Message sent!");
}, function(err) {
console.log(err);
$('.flash').text("Unable to send message. Try again later!");
});
$('#name').val("");
$('#email').val("");
$('#text').val("");
} else {
$('.flash').text("All fields required.");
}
e.preventDefault();
});
$('#send').on('reset', function() {
$('.flash').text("");
}); | $('#send').submit(function(e) {
$('.flash').text("");
var name = $('#name').val();
var email = $('#email').val();
var text = $('#text').val();
if (name && email && text) {
console.log('Conditions met.');
emailjs.send("gmail", "standard",
{
"name": name,
"email": email,
"message": text
}).then(function(response) {
console.log(response.status + response.text);
$('.flash').text("Message sent!");
}, function(err) {
console.log(err);
$('.flash').text("Unable to send message. Try again later!");
});
$('#name').val("");
$('#email').val("");
$('#text').val("");
} else {
$('.flash').text("All fields required.");
}
e.preventDefault();
}) |
Store high scores to redis set | module.exports = function Server(expressInstance, sessionStore) {
var redis = require('redis'), redisClient = redis.createClient();
var parseCookie = require('connect').utils.parseCookie;
var io = require('socket.io').listen(expressInstance);
io.configure(function () {
io.set('log level', 0);
});
io.set('authorization', function(handshakeData, ack) {
var cookies = parseCookie(handshakeData.headers.cookie);
sessionStore.get(cookies['connect.sid'], function(err, sessionData) {
handshakeData.session = sessionData || {};
handshakeData.sid = cookies['connect.sid']|| null;
ack(err, err ? false : true);
});
});
io.sockets.on('connection', function(client) {
client.emit('woo', 'Hello!');
client.on('disconnect', function() { console.log('disconnect'); });
client.on('scoreSubmit', function(scoreData) {
// TODO - identify player
redisClient.zadd('HIGHSCORES',scoreData.score, 'playername');
});
});
io.sockets.on('error', function(){ console.log(arguments); });
return io;
};
| module.exports = function Server(expressInstance, sessionStore) {
var parseCookie = require('connect').utils.parseCookie;
var io = require('socket.io').listen(expressInstance);
io.configure(function () {
io.set('log level', 0);
});
io.set('authorization', function(handshakeData, ack) {
var cookies = parseCookie(handshakeData.headers.cookie);
sessionStore.get(cookies['connect.sid'], function(err, sessionData) {
handshakeData.session = sessionData || {};
handshakeData.sid = cookies['connect.sid']|| null;
ack(err, err ? false : true);
});
});
io.sockets.on('connection', function(client) {
client.emit('woo', 'Hello!');
client.on('disconnect', function() { console.log('disconnect'); });
client.on('scoreSubmit', function(scoreData) {
console.log('Score submitted: ' + scoreData.score);
});
});
io.sockets.on('error', function(){ console.log(arguments); });
return io;
};
|
Remove price check from order email template
For some reason, only lines with prices were rendered in the email. Changed
this so that the free lines (from campaigns) are shown also.
No ref | # -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
MESSAGE_SUBJECT_TEMPLATE = "{{ order.shop }} - Order {{ order.identifier }} Received"
MESSAGE_BODY_TEMPLATE = """
Thank you for your order, {{ order.customer }}!
Your order has been received and will be processed as soon as possible.
For reference, here's a list of your order's contents.
{% for line in order.lines.all() %}
* {{ line.quantity }} x {{ line.text }} - {{ line.taxful_price|money }}
{%- endfor %}
Order Total: {{ order.taxful_total_price|money }}
{% if not order.is_paid() %}
Please note that no record of your order being paid currently exists.
{% endif %}
Thank you for shopping with us!
""".strip()
| # -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
MESSAGE_SUBJECT_TEMPLATE = "{{ order.shop }} - Order {{ order.identifier }} Received"
MESSAGE_BODY_TEMPLATE = """
Thank you for your order, {{ order.customer }}!
Your order has been received and will be processed as soon as possible.
For reference, here's a list of your order's contents.
{% for line in order.lines.all() %}
{%- if line.taxful_price %}
* {{ line.quantity }} x {{ line.text }} - {{ line.taxful_price|money }}
{% endif -%}
{%- endfor %}
Order Total: {{ order.taxful_total_price|money }}
{% if not order.is_paid() %}
Please note that no record of your order being paid currently exists.
{% endif %}
Thank you for shopping with us!
""".strip()
|
:art: Add info dialog for more re: file reads | 'use babel'
import {React} from 'react-for-atom'
export default React.createClass({
propTypes: {
readyCount: React.PropTypes.number,
totalCount: React.PropTypes.number
},
render () {
if (isNaN(this.props.readyCount) || isNaN(this.props.totalCount)) {
return <span />
} else {
return (
<div className='tv-loading-progress'>
<span className='inline-block text-smaller text-subtle icon icon-info' ref='tooltip' onMouseOver={this._onHover}>
Reading {this.props.readyCount} of {this.props.totalCount} notes
</span>
<progress className='inline-block' max={this.props.totalCount} value={this.props.readyCount} />
</div>)
}
},
_onHover () {
atom.notifications.addInfo('Reading files', {
description: 'This is necesary to populate the search index. It is only necessary the first time, the notes will be cached for next session.',
dismissible: true
})
}
})
| 'use babel'
import {React} from 'react-for-atom'
export default React.createClass({
propTypes: {
readyCount: React.PropTypes.number,
totalCount: React.PropTypes.number
},
render () {
if (isNaN(this.props.readyCount) || isNaN(this.props.totalCount)) {
return <span />
} else {
return (
<div className='tv-loading-progress'>
<span className='inline-block text-smaller text-subtle'>
Reading {this.props.readyCount} of {this.props.totalCount} notes
</span>
<progress className='inline-block' max={this.props.totalCount} value={this.props.readyCount} />
</div>)
}
}
})
|
Add support for passing rollup via options |
var through = require('through2'),
gutil = require('gulp-util'),
Rollup = require('rollup');
var PluginError = gutil.PluginError;
module.exports = function(options) {
if (options.rollup) {
Rollup = options.rollup;
delete options.rollup;
}
var stream = through.obj(function(file, encoding, callback) {
if (file.isNull()) {
return callback();
}
var filePath = file.path;
options.entry = filePath;
return Rollup.rollup(options).then(function (bundle) {
var proccessed = bundle.generate(options);
file.contents = new Buffer(proccessed.code);
if (options.sourceMap) {
var map = proccessed.map;
if (map) {
map.file = file.relative;
map.sources = map.sources.map(function(fileName) {
return fileName;
});
file.sourceMap = map;
}
}
callback(null, file);
}).catch(function (err) {
callback(new PluginError('gulp-rollup-mep', err));
});
});
return stream;
};
|
var through = require('through2'),
gutil = require('gulp-util'),
Rollup = require('rollup');
var PluginError = gutil.PluginError;
module.exports = function(options) {
var stream = through.obj(function(file, encoding, callback) {
if (file.isNull()) {
return callback();
}
var filePath = file.path;
options.entry = filePath;
return Rollup.rollup(options).then(function (bundle) {
var proccessed = bundle.generate(options);
file.contents = new Buffer(proccessed.code);
if (options.sourceMap) {
var map = proccessed.map;
if (map) {
map.file = file.relative;
map.sources = map.sources.map(function(fileName) {
return fileName;
});
file.sourceMap = map;
}
}
callback(null, file);
}).catch(function (err) {
callback(new PluginError('gulp-rollup-mep', err));
});
});
return stream;
};
|
Add newline at the end of the file for my sanity. | # -*- coding: utf-8 -*-
"""
test_pops
~~~~~~~~~
tests for population code
"""
from abm import pops
from abm.entities import Task
import pytest
from scipy.stats.distributions import uniform
import numpy as np
@pytest.fixture
def basicenv():
return pops.Environment()
@pytest.mark.unit
def test_distribute_awards(basicenv):
class MockEntity(object):
total_award = 0
def award(self, amount):
self.total_award += amount
basicenv.population = []
for i in range(6):
basicenv.population.append(MockEntity())
basicenv.path = [1, 2, 3, 2, 4]
task = Task(4)
basicenv._distribute_awards(task)
observed = [
x.total_award for x in basicenv.population
]
expected = ([0] + [.25] * 3 + [0, 0])
assert observed == expected
assert np.isclose(sum(observed), .75)
basicenv.path = [0, 4]
basicenv._distribute_awards(task)
assert basicenv.population[0].total_award == 1.
basicenv.path = [5] * (basicenv.path_cutoff + 1)
basicenv._distribute_awards(task)
assert basicenv.population[5].total_award == -.05
| # -*- coding: utf-8 -*-
"""
test_pops
~~~~~~~~~
tests for population code
"""
from abm import pops
from abm.entities import Task
import pytest
from scipy.stats.distributions import uniform
import numpy as np
@pytest.fixture
def basicenv():
return pops.Environment()
@pytest.mark.unit
def test_distribute_awards(basicenv):
class MockEntity(object):
total_award = 0
def award(self, amount):
self.total_award += amount
basicenv.population = []
for i in range(6):
basicenv.population.append(MockEntity())
basicenv.path = [1, 2, 3, 2, 4]
task = Task(4)
basicenv._distribute_awards(task)
observed = [
x.total_award for x in basicenv.population
]
expected = ([0] + [.25] * 3 + [0, 0])
assert observed == expected
assert np.isclose(sum(observed), .75)
basicenv.path = [0, 4]
basicenv._distribute_awards(task)
assert basicenv.population[0].total_award == 1.
basicenv.path = [5] * (basicenv.path_cutoff + 1)
basicenv._distribute_awards(task)
assert basicenv.population[5].total_award == -.05
|
Fix Firefox 18.0.2 complaining about a missing parameter for a setter | //.CommonJS
var CSSOM = {};
///CommonJS
/**
* @constructor
* @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSValue
*
* TODO: add if needed
*/
CSSOM.CSSValue = function CSSValue() {
};
CSSOM.CSSValue.prototype = {
constructor: CSSOM.CSSValue,
// @see: http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSValue
set cssText(text) {
var name = this._getConstructorName();
throw new Exception('DOMException: property "cssText" of "' + name + '" is readonly!');
},
get cssText() {
var name = this._getConstructorName();
throw new Exception('getter "cssText" of "' + name + '" is not implemented!');
},
_getConstructorName: function() {
var s = this.constructor.toString(),
c = s.match(/function\s([^\(]+)/),
name = c[1];
return name;
}
};
//.CommonJS
exports.CSSValue = CSSOM.CSSValue;
///CommonJS
| //.CommonJS
var CSSOM = {};
///CommonJS
/**
* @constructor
* @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSValue
*
* TODO: add if needed
*/
CSSOM.CSSValue = function CSSValue() {
};
CSSOM.CSSValue.prototype = {
constructor: CSSOM.CSSValue,
// @see: http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSValue
set cssText() {
var name = this._getConstructorName();
throw new Exception('DOMException: property "cssText" of "' + name + '" is readonly!');
},
get cssText() {
var name = this._getConstructorName();
throw new Exception('getter "cssText" of "' + name + '" is not implemented!');
},
_getConstructorName: function() {
var s = this.constructor.toString(),
c = s.match(/function\s([^\(]+)/),
name = c[1];
return name;
}
};
//.CommonJS
exports.CSSValue = CSSOM.CSSValue;
///CommonJS
|
Improve Hidden element value logic | "use strict";
const ElementInstance = require('./elementInstance');
const he = require('he');
class HiddenInstance extends ElementInstance {
async init(data={}) {
await super.init(data);
const TagSingle = this.context.theme.getRenderable('TagSingle');
let renderable = TagSingle.newInstance(this.context, {
name: this.name,
data: {
tag: 'input',
attributes: {
type: 'hidden',
name: this.name,
value: he.escape(
this.data.value
? this.data.value
: this.context.post[this.formInstance.id][this.name] != undefined
? this.context.post[this.formInstance.id][this.name]
: this.data.defaultValue
? this.data.defaultValue
: ''),
},
},
});
this.addInstance(renderable);
}
}
module.exports = HiddenInstance;
| "use strict";
const ElementInstance = require('./elementInstance');
const he = require('he');
class HiddenInstance extends ElementInstance {
async init(data={}) {
await super.init(data);
const TagSingle = this.context.theme.getRenderable('TagSingle');
let renderable = TagSingle.newInstance(this.context, {
name: this.name,
data: {
tag: 'input',
attributes: {
type: 'hidden',
name: this.name,
value: he.escape((this.data && (this.data.value != undefined)) ? this.data.value : ''),
},
},
});
this.addInstance(renderable);
}
}
module.exports = HiddenInstance;
|
Add kolibri version to server start logging. | """
WSGI config for kolibri project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import logging
import os
import time
from django.core.wsgi import get_wsgi_application
from django.db.utils import OperationalError
import kolibri
os.environ.setdefault(
"DJANGO_SETTINGS_MODULE", "kolibri.deployment.default.settings.base"
)
logger = logging.getLogger(__name__)
application = None
tries_remaining = 6
interval = 10
while not application and tries_remaining:
try:
logger.info("Starting Kolibri {version}".format(version=kolibri.__version__))
application = get_wsgi_application()
except OperationalError:
# an OperationalError happens when sqlite vacuum is being executed. the db is locked
logger.info("DB busy. Trying again in {}s".format(interval))
tries_remaining -= 1
time.sleep(interval)
application = get_wsgi_application() # try again one last time
if not application:
logger.error("Could not start Kolibri")
| """
WSGI config for kolibri project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import logging
import os
import time
from django.core.wsgi import get_wsgi_application
from django.db.utils import OperationalError
os.environ.setdefault(
"DJANGO_SETTINGS_MODULE", "kolibri.deployment.default.settings.base"
)
logger = logging.getLogger(__name__)
application = None
tries_remaining = 6
interval = 10
while not application and tries_remaining:
try:
logger.info("Starting Kolibri")
application = get_wsgi_application()
except OperationalError:
# an OperationalError happens when sqlite vacuum is being executed. the db is locked
logger.info("DB busy. Trying again in {}s".format(interval))
tries_remaining -= 1
time.sleep(interval)
application = get_wsgi_application() # try again one last time
if not application:
logger.error("Could not start Kolibri")
|
fix(cli): Read files relative from script's directory | const nunjucks = require('nunjucks');
const fs = require('fs-promise');
const path = require('path');
const yaml = require('js-yaml');
const Promise = require('bluebird');
const schemesDir = path.join(__dirname, '../db/schemes');
fs
.readdir(schemesDir)
.then(function(schemeFileNames) {
const promises = [];
schemeFileNames.forEach(function(schemeFileName) {
promises.push(fs.readFile(path.join(schemesDir, schemeFileName), 'utf-8'));
});
Promise.all(promises).then(function(yamlSchemes) {
yamlSchemes = yamlSchemes.map(yamlScheme => yaml.load(yamlScheme));
fs
.readFile(path.join(__dirname, './schemesPreview.nunJucks'), 'utf-8')
.then(function(templ) {
const preview = nunjucks.renderString(templ, {
schemes: yamlSchemes
});
fs.writeFile(path.join(__dirname, '../dist/index.html'), preview);
});
});
});
| const nunjucks = require('nunjucks');
const fs = require('fs-promise');
const path = require('path');
const yaml = require('js-yaml');
const Promise = require('bluebird');
const schemesDir = '../db/schemes';
fs
.readdir(schemesDir)
.then(function(schemeFileNames) {
const promises = [];
schemeFileNames.forEach(function(schemeFileName) {
promises.push(fs.readFile(path.join(schemesDir, schemeFileName), 'utf-8'));
});
Promise.all(promises).then(function(yamlSchemes) {
yamlSchemes = yamlSchemes.map(yamlScheme => yaml.load(yamlScheme));
fs
.readFile('./schemesPreview.nunJucks', 'utf-8')
.then(function(templ) {
const preview = nunjucks.renderString(templ, {
schemes: yamlSchemes
});
fs.writeFile('../dist/index.html', preview);
});
});
});
|
Include search query used to generate results | import request from 'request';
import {Observable} from 'rxjs';
import fs from 'fs';
const githubSearchQuery = `cycle+OR+cyclejs+language%3AJavaScript+created%3A>2014-11-01+stars%3A>3&type=Repositories&sort=stars&order=desc`;
function githubApiSearch (query) {
return `https://api.github.com/search/repositories?q=${query}`;
}
function githubSearch (query) {
return `https://github.com/search?q=${query}`;
}
const requestOptions = {
url: githubApiSearch(githubSearchQuery),
headers: {
'User-Agent': 'cycle-ecosystem'
}
};
Observable.bindCallback(request)(requestOptions)
.map(([error, response]) => JSON.parse(response.body).items)
.map(toMarkdown)
.forEach(updateReadme);
function toMarkdown (searchResults) {
return `
# cycle-ecosystem
What are the most popular libraries for Cycle.js?
| Name | Description | Stars |
| -------- | ----------------- | ------|
${searchResults.map(toMarkdownEntry).join('\n')}
Auto generated by update.js by [searching Github](${githubSearch(githubSearchQuery)}).
Last updated at ${new Date().toString()}.
`;
}
function toMarkdownEntry (result) {
return `| [${result.full_name}](${result.html_url}) | ${result.description} | ${result.stargazers_count} |`;
}
function updateReadme (markdown) {
fs.writeFile('./README.md', markdown);
}
| import request from 'request';
import {Observable} from 'rxjs';
import fs from 'fs';
const githubSearchQuery = `
https://api.github.com/search/repositories?q=cycle+OR+cyclejs+language%3AJavaScript+created%3A>2014-11-01+stars%3A>3&type=Repositories&sort=stars&order=desc
`;
const requestOptions = {
url: githubSearchQuery,
headers: {
'User-Agent': 'cycle-ecosystem'
}
};
Observable.bindCallback(request)(requestOptions)
.map(([error, response]) => JSON.parse(response.body).items)
.map(toMarkdown)
.forEach(updateReadme);
function toMarkdown (searchResults) {
return `
# cycle-ecosystem
What are the most popular libraries for Cycle.js?
| Name | Description | Stars |
| -------- | ----------------- | ------|
${searchResults.map(toMarkdownEntry).join('\n')}
Auto generated by update.js.
Last updated at ${new Date().toString()}.
`;
}
function toMarkdownEntry (result) {
return `| [${result.full_name}](${result.html_url}) | ${result.description} | ${result.stargazers_count} |`;
}
function updateReadme (markdown) {
fs.writeFile('./README.md', markdown);
}
|
Add the possibility to append `label` on component toolbar buttons | var Backbone = require('backbone');
module.exports = Backbone.View.extend({
events() {
return (
this.model.get('events') || {
mousedown: 'handleClick'
}
);
},
attributes() {
return this.model.get('attributes');
},
initialize(opts) {
this.editor = opts.config.editor;
},
handleClick(event) {
event.preventDefault();
event.stopPropagation();
this.execCommand(event);
},
execCommand(event) {
const opts = { event };
const command = this.model.get('command');
const editor = this.editor;
if (typeof command === 'function') {
command(editor, null, opts);
}
if (typeof command === 'string') {
editor.runCommand(command, opts);
}
},
render() {
const { editor, $el, model } = this;
const label = model.get('label');
const pfx = editor.getConfig('stylePrefix');
$el.addClass(`${pfx}toolbar-item`);
label && $el.append(label);
return this;
}
});
| var Backbone = require('backbone');
module.exports = Backbone.View.extend({
events() {
return (
this.model.get('events') || {
mousedown: 'handleClick'
}
);
},
attributes() {
return this.model.get('attributes');
},
initialize(opts) {
this.editor = opts.config.editor;
},
handleClick(event) {
event.preventDefault();
event.stopPropagation();
this.execCommand(event);
},
execCommand(event) {
const opts = { event };
const command = this.model.get('command');
const editor = this.editor;
if (typeof command === 'function') {
command(editor, null, opts);
}
if (typeof command === 'string') {
editor.runCommand(command, opts);
}
},
render() {
var config = this.editor.getConfig();
this.el.className += ' ' + config.stylePrefix + 'toolbar-item';
return this;
}
});
|
Use C++ implementations of hp sampling | """Implements the Runner interface fo LDA
"""
from microscopes.common import validator
from microscopes.common.rng import rng
from microscopes.lda.kernels import lda_crp_gibbs
from microscopes.lda.kernels import sample_gamma, sample_alpha
class runner(object):
"""The LDA runner
Parameters
----------
defn : ``model_definition``: The structural definition.
view : A list of list of serializable objects (the 'documents')
latent : ``state``: The initialization state.
"""
def __init__(self, defn, view, latent, kernel_config='assign'):
self._defn = defn
self._view = view
self._latent = latent
def run(self, r, niters=10000):
"""Run the lda kernel for `niters`, in a single thread.
Parameters
----------
r : random state
niters : int
"""
validator.validate_type(r, rng, param_name='r')
validator.validate_positive(niters, param_name='niters')
for _ in xrange(niters):
lda_crp_gibbs(self._latent, r)
sample_gamma(self._latent, r, 5, 0.1)
sample_alpha(self._latent, r, 5, 0.1)
| """Implements the Runner interface fo LDA
"""
from microscopes.common import validator
from microscopes.common.rng import rng
from microscopes.lda.kernels import lda_crp_gibbs
from microscopes.lda.kernels import lda_sample_dispersion
class runner(object):
"""The LDA runner
Parameters
----------
defn : ``model_definition``: The structural definition.
view : A list of list of serializable objects (the 'documents')
latent : ``state``: The initialization state.
"""
def __init__(self, defn, view, latent, kernel_config='assign'):
self._defn = defn
self._view = view
self._latent = latent
def run(self, r, niters=10000):
"""Run the lda kernel for `niters`, in a single thread.
Parameters
----------
r : random state
niters : int
"""
validator.validate_type(r, rng, param_name='r')
validator.validate_positive(niters, param_name='niters')
for _ in xrange(niters):
lda_crp_gibbs(self._latent, r)
lda_sample_dispersion(self._latent, r)
|
[Bugfix] Add Apiato facade class to fix Apiato::call | <?php
namespace App\Containers\Authentication\Actions;
use Apiato\Core\Foundation\Facades\Apiato;
use App\Containers\Authorization\Exceptions\UserNotAdminException;
use App\Ship\Parents\Actions\Action;
use App\Ship\Parents\Requests\Request;
/**
* Class WebAdminLoginAction.
*
* @author Mahmoud Zalt <mahmoud@zalt.me>
*/
class WebAdminLoginAction extends Action
{
/**
* @param \App\Ship\Parents\Requests\Request $request
*
* @return mixed
* @throws \App\Containers\Authorization\Exceptions\UserNotAdminException
*/
public function run(Request $request)
{
$user = Apiato::call('Authentication@WebLoginTask',
[$request->email, $request->password, $request->remember_me ?? false]);
Apiato::call('Authentication@CheckIfUserIsConfirmedTask', [], [['setUser' => [$user]]]);
if (!$user->hasAdminRole()) {
throw new UserNotAdminException();
}
return $user;
}
}
| <?php
namespace App\Containers\Authentication\Actions;
use App\Containers\Authorization\Exceptions\UserNotAdminException;
use App\Ship\Parents\Actions\Action;
use App\Ship\Parents\Requests\Request;
/**
* Class WebAdminLoginAction.
*
* @author Mahmoud Zalt <mahmoud@zalt.me>
*/
class WebAdminLoginAction extends Action
{
/**
* @param \App\Ship\Parents\Requests\Request $request
*
* @return mixed
* @throws \App\Containers\Authorization\Exceptions\UserNotAdminException
*/
public function run(Request $request)
{
$user = Apiato::call('Authentication@WebLoginTask',
[$request->email, $request->password, $request->remember_me ?? false]);
Apiato::call('Authentication@CheckIfUserIsConfirmedTask', [], [['setUser' => [$user]]]);
if (!$user->hasAdminRole()) {
throw new UserNotAdminException();
}
return $user;
}
}
|
Remove import of n/a benchmark module.
git-svn-id: 8b0eea19d26e20ec80f5c0ea247ec202fbcc1090@75 5646265b-94b7-0310-9681-9501d24b2df7 | import warnings
from dtml import tal, metal, tales, context
from sheared.python import io
class Entwiner:
def __init__(self):
self.builtins = context.BuiltIns({})
#self.context = context.Context()
#self.context.setDefaults(self.builtins)
def handle(self, request, reply, subpath):
self.context = {}
self.entwine(request, reply, subpath)
r = self.execute(self.page_path, throwaway=0)
reply.send(r)
def execute(self, path, throwaway=1):
r = io.readfile(path)
c = tal.compile(r, tales)
r = tal.execute(c, self.context, self.builtins, tales)
c = metal.compile(r, tales)
r = metal.execute(c, self.context, self.builtins, tales)
if throwaway and r.strip():
warnings.warn('%s: ignored non-macro content' % path)
return r
| import warnings
from dtml import tal, metal, tales, context
from sheared.python import io
from sheared.python import benchmark
class Entwiner:
def __init__(self):
self.builtins = context.BuiltIns({})
#self.context = context.Context()
#self.context.setDefaults(self.builtins)
def handle(self, request, reply, subpath):
self.context = {}
self.entwine(request, reply, subpath)
r = self.execute(self.page_path, throwaway=0)
reply.send(r)
def execute(self, path, throwaway=1):
r = io.readfile(path)
c = tal.compile(r, tales)
r = tal.execute(c, self.context, self.builtins, tales)
c = metal.compile(r, tales)
r = metal.execute(c, self.context, self.builtins, tales)
if throwaway and r.strip():
warnings.warn('%s: ignored non-macro content' % path)
return r
|
Remove unnecessary @db_txn decorator on alias_route | from flask import redirect
from flask import render_template
from flask import request
import database.link
from linkr import app
from uri.link import *
from uri.main import *
@app.route(LinkAliasRedirectURI.path, methods=LinkAliasRedirectURI.methods)
def alias_route(alias):
# Attempt to fetch the link mapping from the database
link = database.link.get_link_by_alias(alias)
if not link:
if request.method == 'GET':
# For GET requests (likely from a browser), direct to a frontend error
return redirect(LinkNotFoundURI.path)
elif request.method == 'POST':
# For POST requests (likely programmatic), send a plain-text response with an
# appropriate status code
return 'Link alias not found', 404
link.increment_hits()
return redirect(link.outgoing_url)
@app.route(HomeURI.path, defaults={'path': ''}, methods=HomeURI.methods)
@app.route(DefaultURI.path, methods=DefaultURI.methods)
def frontend(path):
return render_template('index.html')
| from flask import redirect
from flask import render_template
from flask import request
import database.link
from database import db_txn
from linkr import app
from uri.link import *
from uri.main import *
@app.route(LinkAliasRedirectURI.path, methods=LinkAliasRedirectURI.methods)
@db_txn
def alias_route(alias):
# Attempt to fetch the link mapping from the database
link = database.link.get_link_by_alias(alias)
if not link:
if request.method == 'GET':
# For GET requests (likely from a browser), direct to a frontend error
return redirect(LinkNotFoundURI.path)
elif request.method == 'POST':
# For POST requests (likely programmatic), send a plain-text response with an
# appropriate status code
return 'Link alias not found', 404
link.increment_hits()
return redirect(link.outgoing_url)
@app.route(HomeURI.path, defaults={'path': ''}, methods=HomeURI.methods)
@app.route(DefaultURI.path, methods=DefaultURI.methods)
def frontend(path):
return render_template('index.html')
|
Make test dependencies more explicit | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from setuptools import setup
root = os.path.abspath(os.path.dirname(__file__))
version = __import__('swf').__version__
with open(os.path.join(root, 'README.rst')) as f:
README = f.read()
setup(
name='simple-workflow',
version=version,
license='MIT',
description='Amazon simple workflow service wrapper for python',
long_description=README + '\n\n',
author='Oleiade',
author_email='tcrevon@gmail.com',
url='http://github.com/botify-labs/python-simple-workflow',
keywords='amazon simple wokflow swf python',
zip_safe=True,
install_requires=[
'boto',
'xworkflows==1.0.0',
],
tests_require=[
'mock==1.0.1',
'py.test>=2.8.5',
],
package_dir={'': '.'},
include_package_data=False,
packages=[
'swf',
'swf.actors',
'swf.querysets',
'swf.models',
'swf.models.event',
'swf.models.decision',
'swf.models.history',
],
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from setuptools import setup
root = os.path.abspath(os.path.dirname(__file__))
version = __import__('swf').__version__
with open(os.path.join(root, 'README.rst')) as f:
README = f.read()
setup(
name='simple-workflow',
version=version,
license='MIT',
description='Amazon simple workflow service wrapper for python',
long_description=README + '\n\n',
author='Oleiade',
author_email='tcrevon@gmail.com',
url='http://github.com/botify-labs/python-simple-workflow',
keywords='amazon simple wokflow swf python',
zip_safe=True,
install_requires=[
'boto',
'mock==1.0.1',
'xworkflows==1.0.0',
],
package_dir={'': '.'},
include_package_data=False,
packages=[
'swf',
'swf.actors',
'swf.querysets',
'swf.models',
'swf.models.event',
'swf.models.decision',
'swf.models.history',
],
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.