text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
DNS: Change name value to "Answer". Add error checking of api_result. | (function(env){
'use strict';
env.ddg_spice_dns = function(api_result) {
if (!api_result || !DDG.getProperty(api_result, 'response.records').length) {
return Spice.failed('dns');
}
api_result.response.records.sort(function(a, b) {
if (a.type < b.type)
return -1
if (a.type > b.type)
return 1
return parseInt(a.priority) - parseInt(b.priority);
});
Spice.add({
id: 'dns',
name: "Answer",
data: api_result.response,
meta: {
sourceUrl: 'http://www.viewdns.info/dnsrecord/?domain=' + api_result.query.domain,
sourceName: 'ViewDNS'
},
templates: {
group: 'base',
options: {
content: Spice.dns.content,
moreAt: true
}
}
});
};
})(this);
| (function(env){
'use strict';
env.ddg_spice_dns = function(api_result) {
var records = DDG.getProperty(api_result, 'response.records');
if (!records.length) {
return Spice.failed('dns');
}
api_result.response.records.sort(function(a, b) {
if (a.type < b.type)
return -1
if (a.type > b.type)
return 1
return parseInt(a.priority) - parseInt(b.priority);
});
Spice.add({
id: 'dns',
name: api_result.query.domain,
data: api_result.response,
meta: {
sourceUrl: 'http://www.viewdns.info/dnsrecord/?domain=' + api_result.query.domain,
sourceName: 'ViewDNS'
},
templates: {
group: 'base',
options: {
content: Spice.dns.content,
moreAt: true
}
}
});
};
})(this);
|
Remove class in SpringBooTest annotation | package io.github.web.springtest;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import io.github.bonigarcia.SeleniumExtension;
@ExtendWith({ SeleniumExtension.class, SpringExtension.class })
@SpringBootTest(webEnvironment = RANDOM_PORT)
public class SpringChromeJupiterTest {
@LocalServerPort
int serverPort;
@Test
public void test(ChromeDriver driver) {
// Open system under test
driver.get("http://localhost:" + serverPort);
// Verify first page title
String firstPageTitle = driver.getTitle();
String expectedFirstPageTitle = "Spring Boot Test - Page 1";
assertEquals(expectedFirstPageTitle, firstPageTitle);
// Click on link
driver.findElement(By.linkText("another")).click();
// Verify second page caption
String secondPageCaption = driver.findElement(By.id("caption"))
.getText();
String expectedSecondPageTitle = "Other page";
assertEquals(expectedSecondPageTitle, secondPageCaption);
}
}
| package io.github.web.springtest;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import io.github.bonigarcia.SeleniumExtension;
@ExtendWith({ SeleniumExtension.class, SpringExtension.class })
@SpringBootTest(classes = SpringTestDemoApp.class, webEnvironment = RANDOM_PORT)
public class SpringChromeJupiterTest {
@LocalServerPort
int serverPort;
@Test
public void test(ChromeDriver driver) {
// Open system under test
driver.get("http://localhost:" + serverPort);
// Verify first page title
String firstPageTitle = driver.getTitle();
String expectedFirstPageTitle = "Spring Boot Test - Page 1";
assertEquals(expectedFirstPageTitle, firstPageTitle);
// Click on link
driver.findElement(By.linkText("another")).click();
// Verify second page caption
String secondPageCaption = driver.findElement(By.id("caption"))
.getText();
String expectedSecondPageTitle = "Other page";
assertEquals(expectedSecondPageTitle, secondPageCaption);
}
}
|
Upgrade tangled 1.0a11 => 1.0a12 | from setuptools import setup, PEP420PackageFinder
setup(
name='tangled.web',
version='1.0a13.dev0',
description='RESTful Web Framework',
long_description=open('README.rst').read(),
url='http://tangledframework.org/',
download_url='https://github.com/TangledWeb/tangled.web/tags',
author='Wyatt Baldwin',
author_email='[email protected]',
packages=PEP420PackageFinder.find(include=['tangled*']),
include_package_data=True,
install_requires=[
'tangled>=1.0a12',
'MarkupSafe>=0.23',
'WebOb>=1.5.1',
],
extras_require={
'dev': [
'tangled[dev]>=1.0a12',
],
},
entry_points="""
[tangled.scripts]
serve = tangled.web.scripts.serve
shell = tangled.web.scripts.shell
show = tangled.web.scripts.show
[tangled.scaffolds]
basic = tangled.web.scaffolds:basic
""",
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
)
| from setuptools import setup, PEP420PackageFinder
setup(
name='tangled.web',
version='1.0a13.dev0',
description='RESTful Web Framework',
long_description=open('README.rst').read(),
url='http://tangledframework.org/',
download_url='https://github.com/TangledWeb/tangled.web/tags',
author='Wyatt Baldwin',
author_email='[email protected]',
packages=PEP420PackageFinder.find(include=['tangled*']),
include_package_data=True,
install_requires=[
'tangled>=1.0a11',
'MarkupSafe>=0.23',
'WebOb>=1.5.1',
],
extras_require={
'dev': [
'tangled[dev]>=1.0a11',
],
},
entry_points="""
[tangled.scripts]
serve = tangled.web.scripts.serve
shell = tangled.web.scripts.shell
show = tangled.web.scripts.show
[tangled.scaffolds]
basic = tangled.web.scaffolds:basic
""",
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
)
|
Fix error in delete button in dashboard page | angular.module('zoomableApp').factory('servicesAPI', function($http, $q, Upload, $timeout) {
return {
createVideo : function(video) {
return $http.post('/api/video', video);
},
createAccount : function(accountData) {
return $http.post('/api/user/signup', accountData);
},
get : function() {
return $http.get('api/video');
},
getOne : function(id) {
return $http.get('/api/video/' + id);
},
getUploadProgress : function(id) {
return $http.post('/api/video/isComplete', id);
},
delete : function(id) {
return $http.delete('/api/video/' + id);
},
deleteAll : function(ids) {
return $http.delete('/api/video', {data : ids});
},
update : function(id, videoData) {
return $http.put('/api/video/' + id, videoData);
},
login : function(accountData) {
return $http.post('/api/user/login', accountData);
},
upload : function (file) {
return $q(function(resolve, reject) {
setTimeout(function() {
Upload.upload({
url : '/api/video/upload',
data : {
id : file.id,
video : file
}
}).then(function (res) {
resolve(res);
});
});
});
}
}
});
| angular.module('zoomableApp').factory('servicesAPI', function($http, $q, Upload, $timeout) {
return {
createVideo : function(video) {
return $http.post('/api/video', video);
},
createAccount : function(accountData) {
return $http.post('/api/user/signup', accountData);
},
get : function() {
return $http.get('api/video');
},
getOne : function(id) {
return $http.get('/api/video/' + id);
},
getUploadProgress : function(id) {
return $http.post('/api/video/isComplete', id);
},
delete : function(id) {
return $http.delete('/api/video' + id);
},
deleteAll : function(ids) {
return $http.delete('/api/video', {data : ids});
},
update : function(id, videoData) {
return $http.put('/api/video/' + id, videoData);
},
login : function(accountData) {
return $http.post('/api/user/login', accountData);
},
upload : function (file) {
return $q(function(resolve, reject) {
setTimeout(function() {
Upload.upload({
url : '/api/video/upload',
data : {
id : file.id,
video : file
}
}).then(function (res) {
resolve(res);
});
});
});
}
}
});
|
Fix login issue with token | LoginController.$inject = ['$rootScope', '$location', 'auth',
'role', 'toaster', 'TbUtils'];
function LoginController ($rootScope, $location, auth, role, toaster, TbUtils) {
var vm = this;
vm.username = "";
vm.password = "";
vm.login = login;
vm.loading = false;
auth.ClearCredentials();
function login() {
vm.loading = true;
auth.Login( vm.username, vm.password, LoginSuccess, LoginFail);
}
function LoginSuccess(response) {
console.log(response);
auth.SetCredentials(response.data.Token);
window.localStorage['Session'] =
$rootScope.Session =
vm.username;
window.localStorage['Username'] =
$rootScope.Username =
$rootScope.Session.slice(0, $rootScope.Session.indexOf('@'));
role.get($rootScope.Session, getRoleSuccess);
}
function getRoleSuccess (response) {
window.localStorage['Role'] =
$rootScope.Role =
response.data;
$location.path('/proyectos');
vm.loading = false;
}
function LoginFail(response) {
console.log(response);
TbUtils.showErrorMessage('error', response,
'La cuenta ingresada no tiene privilegios de acceso',
'Falla autorizacion');
vm.loading = false;
}
}
module.exports = { name: 'LoginController', ctrl: LoginController }; | LoginController.$inject = ['$rootScope', '$location', 'auth',
'role', 'toaster', 'TbUtils'];
function LoginController ($rootScope, $location, auth, role, toaster, TbUtils) {
var vm = this;
vm.username = "";
vm.password = "";
vm.login = login;
vm.loading = false;
auth.ClearCredentials();
function login() {
vm.loading = true;
auth.Login( vm.username, vm.password, LoginSuccess, LoginFail);
}
function LoginSuccess(response) {
console.log(response);
auth.SetCredentials(response.data);
window.localStorage['Session'] =
$rootScope.Session =
vm.username;
window.localStorage['Username'] =
$rootScope.Username =
$rootScope.Session.slice(0, $rootScope.Session.indexOf('@'));
role.get($rootScope.Session, getRoleSuccess);
}
function getRoleSuccess (response) {
window.localStorage['Role'] =
$rootScope.Role =
response.data;
$location.path('/proyectos');
vm.loading = false;
}
function LoginFail(response) {
console.log(response);
TbUtils.showErrorMessage('error', response,
'La cuenta ingresada no tiene privilegios de acceso',
'Falla autorizacion');
vm.loading = false;
}
}
module.exports = { name: 'LoginController', ctrl: LoginController }; |
Check if the file exists before doing anything else. | #!/usr/bin/env python
# -*- coding: utf8 -*-
# My imports
import argparse
import gzip
import os
def _parser():
parser = argparse.ArgumentParser(description='Prepare the data downloaded '
'from VALD.')
parser.add_argument('input', help='input compressed file', type=str)
parser.add_argument('-o', '--output',
help='Optional output',
default=False, type=str)
return parser.parse_args()
def main(input, output=False):
if not os.path.isfile(input):
raise IOError('File: %s does not exists' % input)
fname = input.rpartition('.')[0]
if not output:
output = '%s.dat' % fname
oref = '%s.ref' % fname
fout = ''
fref = ''
with gzip.open(input, 'r') as lines:
for i, line in enumerate(lines):
if i < 2:
fout += '# %s' % line.replace("'", '')
else:
fout += line.replace("'", '')
if 'References' in line:
break
with open(output, 'w') as fo:
fo.write(fout)
if __name__ == '__main__':
args = _parser()
input, output = args.input, args.output
main(input, output)
| #!/usr/bin/env python
# -*- coding: utf8 -*-
# My imports
import argparse
import gzip
def _parser():
parser = argparse.ArgumentParser(description='Prepare the data downloaded '
'from VALD.')
parser.add_argument('input', help='input compressed file')
parser.add_argument('-o', '--output',
help='Optional output',
default=False)
return parser.parse_args()
def main(input, output=False):
if not isinstance(input, str):
raise TypeError('Input must be a str. A %s was parsed' % type(input))
if not isinstance(output, str) and output:
raise TypeError('Output must be a str. A %s was parsed' % type(output))
# TODO: Check if the input exists
fname = input.rpartition('.')[0]
if not output:
output = '%s.dat' % fname
oref = '%s.ref' % fname
fout = ''
fref = ''
with gzip.open(input, 'r') as lines:
for i, line in enumerate(lines):
if i < 2:
fout += '# %s' % line.replace("'", '')
else:
fout += line.replace("'", '')
if 'References' in line:
break
with open(output, 'w') as fo:
fo.write(fout)
if __name__ == '__main__':
args = _parser()
input, output = args.input, args.output
main(input, output)
|
USe payout amount to calculate total | from babel.numbers import get_currency_name, get_currency_symbol
from bluebottle.utils.exchange_rates import convert
from django.db.models import Sum
from djmoney.money import Money
from bluebottle.funding.models import PaymentProvider
def get_currency_settings():
result = []
for provider in PaymentProvider.objects.all():
for cur in provider.paymentcurrency_set.all():
result.append({
'provider': provider.name,
'providerName': provider.title,
'code': cur.code,
'name': get_currency_name(cur.code),
'symbol': get_currency_symbol(cur.code).replace('US$', '$').replace('NGN', '₦'),
'defaultAmounts': [
cur.default1,
cur.default2,
cur.default3,
cur.default4,
],
'minAmount': cur.min_amount,
'maxAmount': cur.max_amount
})
return result
def calculate_total(queryset, target='EUR'):
totals = queryset.values(
'donor__payout_amount_currency'
).annotate(
total=Sum('donor__payout_amount')
).order_by('-created')
amounts = [Money(tot['total'], tot['donor__payout_amount_currency']) for tot in totals]
amounts = [convert(amount, target) for amount in amounts]
return sum(amounts) or Money(0, target)
| from babel.numbers import get_currency_name, get_currency_symbol
from bluebottle.utils.exchange_rates import convert
from django.db.models import Sum
from djmoney.money import Money
from bluebottle.funding.models import PaymentProvider
def get_currency_settings():
result = []
for provider in PaymentProvider.objects.all():
for cur in provider.paymentcurrency_set.all():
result.append({
'provider': provider.name,
'providerName': provider.title,
'code': cur.code,
'name': get_currency_name(cur.code),
'symbol': get_currency_symbol(cur.code).replace('US$', '$').replace('NGN', '₦'),
'defaultAmounts': [
cur.default1,
cur.default2,
cur.default3,
cur.default4,
],
'minAmount': cur.min_amount,
'maxAmount': cur.max_amount
})
return result
def calculate_total(queryset, target='EUR'):
totals = queryset.values(
'donor__amount_currency'
).annotate(
total=Sum('donor__amount')
).order_by('-created')
amounts = [Money(tot['total'], tot['donor__amount_currency']) for tot in totals]
amounts = [convert(amount, target) for amount in amounts]
return sum(amounts) or Money(0, target)
|
Add newline to end of output. | <?php
/*
+------------------------------------------------------------------------+
| dd |
+------------------------------------------------------------------------+
| Copyright (c) 2016 Phalcon Team (https://www.phalconphp.com) |
+------------------------------------------------------------------------+
| This source file is subject to the New BSD License that is bundled |
| with this package in the file LICENSE.txt. |
| |
| If you did not receive a copy of the license and are unable to |
| obtain it through the world-wide-web, please send an email |
| to [email protected] so we can send you a copy immediately. |
+------------------------------------------------------------------------+
| Authors: Serghei Iakovlev <[email protected]> |
+------------------------------------------------------------------------+
*/
use Phalcon\Debug\Dump;
if (!function_exists('dd')) {
/**
* Dump the passed variables and end the script.
*
* @param mixed
* @return void
*/
function dd()
{
array_map(function ($x) {
$string = (new Dump(null, true))->variable($x);
echo (PHP_SAPI == 'cli' ? strip_tags($string) . PHP_EOL : $string);
}, func_get_args());
die(1);
}
}
| <?php
/*
+------------------------------------------------------------------------+
| dd |
+------------------------------------------------------------------------+
| Copyright (c) 2016 Phalcon Team (https://www.phalconphp.com) |
+------------------------------------------------------------------------+
| This source file is subject to the New BSD License that is bundled |
| with this package in the file LICENSE.txt. |
| |
| If you did not receive a copy of the license and are unable to |
| obtain it through the world-wide-web, please send an email |
| to [email protected] so we can send you a copy immediately. |
+------------------------------------------------------------------------+
| Authors: Serghei Iakovlev <[email protected]> |
+------------------------------------------------------------------------+
*/
use Phalcon\Debug\Dump;
if (!function_exists('dd')) {
/**
* Dump the passed variables and end the script.
*
* @param mixed
* @return void
*/
function dd()
{
array_map(function ($x) {
$string = (new Dump(null, true))->variable($x);
echo (PHP_SAPI == 'cli' ? strip_tags($string) : $string);
}, func_get_args());
die(1);
}
}
|
CRM-1974: Introduce transport settings - fixed flush of selected value | /*global define*/
define(['jquery', 'underscore', 'backbone'
], function ($, _, Backbone) {
'use strict';
/**
* @export oroemail/js/email/template/view
* @class oroemail.email.template.View
* @extends Backbone.View
*/
return Backbone.View.extend({
events: {
'change': 'selectionChanged'
},
target: null,
/**
* Constructor
*
* @param options {Object}
*/
initialize: function (options) {
this.template = $('#emailtemplate-chooser-template').html();
this.target = options.target;
this.listenTo(this.collection, 'reset', this.render);
if (!$(this.target).val()) {
this.selectionChanged();
}
},
/**
* onChange event listener
*/
selectionChanged: function () {
var entityId = this.$el.val();
this.collection.setEntityId(entityId.split('\\').join('_'));
if (entityId) {
this.collection.fetch({reset: true});
} else {
this.collection.reset();
}
},
render: function () {
$(this.target).val('').trigger('change');
$(this.target).find('option[value!=""]').remove();
if (this.collection.models.length > 0) {
$(this.target).append(_.template(this.template, {entities: this.collection.models}));
}
}
});
});
| /*global define*/
define(['jquery', 'underscore', 'backbone'
], function ($, _, Backbone) {
'use strict';
/**
* @export oroemail/js/email/template/view
* @class oroemail.email.template.View
* @extends Backbone.View
*/
return Backbone.View.extend({
events: {
'change': 'selectionChanged'
},
target: null,
/**
* Constructor
*
* @param options {Object}
*/
initialize: function (options) {
this.template = $('#emailtemplate-chooser-template').html();
this.target = options.target;
this.listenTo(this.collection, 'reset', this.render);
this.selectionChanged();
},
/**
* onChange event listener
*/
selectionChanged: function () {
var entityId = this.$el.val();
this.collection.setEntityId(entityId.split('\\').join('_'));
if (entityId) {
this.collection.fetch({reset: true});
} else {
this.collection.reset();
}
},
render: function () {
$(this.target).val('').trigger('change');
$(this.target).find('option[value!=""]').remove();
if (this.collection.models.length > 0) {
$(this.target).append(_.template(this.template, {entities: this.collection.models}));
}
}
});
});
|
Use new name of README. | import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-authority',
version='0.7',
description=(
"A Django app that provides generic per-object-permissions "
"for Django's auth app."
),
long_description=read('README.rst'),
author='Jannis Leidel',
author_email='[email protected]',
license='BSD',
url='https://github.com/jezdez/django-authority/',
packages=find_packages(),
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Framework :: Django',
],
install_requires=['django'],
package_data = {
'authority': [
'fixtures/test.json',
'templates/authority/*.html',
'templates/admin/edit_inline/action_tabular.html',
'templates/admin/permission_change_form.html',
]
},
zip_safe=False,
)
| import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-authority',
version='0.7',
description=(
"A Django app that provides generic per-object-permissions "
"for Django's auth app."
),
long_description=read('README'),
author='Jannis Leidel',
author_email='[email protected]',
license='BSD',
url='https://github.com/jezdez/django-authority/',
packages=find_packages(),
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Framework :: Django',
],
install_requires=['django'],
package_data = {
'authority': [
'fixtures/test.json',
'templates/authority/*.html',
'templates/admin/edit_inline/action_tabular.html',
'templates/admin/permission_change_form.html',
]
},
zip_safe=False,
)
|
Fix bad ref, forgot the __salt__ :P | '''
Disk monitoring state
Monitor the state of disk resources
'''
def status(name, max=None, min=None):
'''
Return the current disk usage stats for the named device
'''
# Monitoring state, no changes will be made so no test interface needed
ret = {'name': name,
'result': False,
'comment': '',
'changes': {},
'data': {}} # Data field for monitoring state
data = __salt__['disk.usage']()
if not name in data:
ret['result'] = False
ret['comment'] += 'Named disk mount not present '
return ret
if max:
try:
if isinstance(max, basestring):
max = int(max.strip('%'))
except Exception:
ret['comment'] += 'Max argument must be an integer '
if min:
try:
if isinstance(min, basestring):
min = int(min.strip('%'))
except Exception:
ret['comment'] += 'Min argument must be an integer '
if min and max:
if min >= max:
ret['comment'] += 'Min must be less than max'
if ret['comment']:
return ret
cap = int(data[name]['capacity'].strip('%'))
ret['data'] = data[name]
if min:
if cap < min:
ret['comment'] = 'Disk is below minimum of {0} at {1}'.format(
min, cap)
return ret
if max:
if cap > max:
ret['comment'] = 'Disk is below maximum of {0} at {1}'.format(
max, cap)
return ret
ret['comment'] = 'Disk in acceptable range'
ret['result'] = True
return ret
| '''
Disk monitoring state
Monitor the state of disk resources
'''
def status(name, max=None, min=None):
'''
Return the current disk usage stats for the named device
'''
# Monitoring state, no changes will be made so no test interface needed
ret = {'name': name,
'result': False,
'comment': '',
'changes': {},
'data': {}} # Data field for monitoring state
data = disk.usage()
if not name in data:
ret['result'] = False
ret['comment'] += 'Named disk mount not present '
return ret
if max:
try:
if isinstance(max, basestring):
max = int(max.strip('%'))
except Exception:
ret['comment'] += 'Max argument must be an integer '
if min:
try:
if isinstance(min, basestring):
min = int(min.strip('%'))
except Exception:
ret['comment'] += 'Min argument must be an integer '
if min and max:
if min >= max:
ret['comment'] += 'Min must be less than max'
if ret['comment']:
return ret
cap = int(data[name]['capacity'].strip('%'))
ret['data'] = data[name]
if min:
if cap < min:
ret['comment'] = 'Disk is below minimum of {0} at {1}'.format(
min, cap)
return ret
if max:
if cap > max:
ret['comment'] = 'Disk is below maximum of {0} at {1}'.format(
max, cap)
return ret
ret['comment'] = 'Disk in acceptable range'
ret['result'] = True
return ret
|
Add missing tests for interfaces | import unittest
import aiozmq
class ZmqTransportTests(unittest.TestCase):
def test_interface(self):
tr = aiozmq.ZmqTransport()
self.assertRaises(NotImplementedError, tr.write, [b'data'])
self.assertRaises(NotImplementedError, tr.abort)
self.assertRaises(NotImplementedError, tr.getsockopt, 1)
self.assertRaises(NotImplementedError, tr.setsockopt, 1, 2)
self.assertRaises(NotImplementedError, tr.set_write_buffer_limits)
self.assertRaises(NotImplementedError, tr.get_write_buffer_size)
self.assertRaises(NotImplementedError, tr.pause_reading)
self.assertRaises(NotImplementedError, tr.resume_reading)
self.assertRaises(NotImplementedError, tr.bind, 'endpoint')
self.assertRaises(NotImplementedError, tr.unbind, 'endpoint')
self.assertRaises(NotImplementedError, tr.bindings)
self.assertRaises(NotImplementedError, tr.connect, 'endpoint')
self.assertRaises(NotImplementedError, tr.disconnect, 'endpoint')
self.assertRaises(NotImplementedError, tr.connections)
self.assertRaises(NotImplementedError, tr.subscribe, b'filter')
self.assertRaises(NotImplementedError, tr.unsubscribe, b'filter')
self.assertRaises(NotImplementedError, tr.subscriptions)
class ZmqProtocolTests(unittest.TestCase):
def test_interface(self):
pr = aiozmq.ZmqProtocol()
self.assertIsNone(pr.msg_received((b'data',)))
| import unittest
import aiozmq
class ZmqTransportTests(unittest.TestCase):
def test_interface(self):
tr = aiozmq.ZmqTransport()
self.assertRaises(NotImplementedError, tr.write, [b'data'])
self.assertRaises(NotImplementedError, tr.abort)
self.assertRaises(NotImplementedError, tr.getsockopt, 1)
self.assertRaises(NotImplementedError, tr.setsockopt, 1, 2)
self.assertRaises(NotImplementedError, tr.set_write_buffer_limits)
self.assertRaises(NotImplementedError, tr.get_write_buffer_size)
self.assertRaises(NotImplementedError, tr.bind, 'endpoint')
self.assertRaises(NotImplementedError, tr.unbind, 'endpoint')
self.assertRaises(NotImplementedError, tr.bindings)
self.assertRaises(NotImplementedError, tr.connect, 'endpoint')
self.assertRaises(NotImplementedError, tr.disconnect, 'endpoint')
self.assertRaises(NotImplementedError, tr.connections)
self.assertRaises(NotImplementedError, tr.subscribe, b'filter')
self.assertRaises(NotImplementedError, tr.unsubscribe, b'filter')
self.assertRaises(NotImplementedError, tr.subscriptions)
class ZmqProtocolTests(unittest.TestCase):
def test_interface(self):
pr = aiozmq.ZmqProtocol()
self.assertIsNone(pr.msg_received((b'data',)))
|
Fix unicode error when showing voucher error message | from django import forms
from django.utils.translation import pgettext_lazy
from .models import Voucher, NotApplicable
class VoucherField(forms.ModelChoiceField):
default_error_messages = {
'invalid_choice': pgettext_lazy(
'voucher', pgettext_lazy(
'voucher', 'Discount code incorrect or expired')),
}
class CheckoutDiscountForm(forms.Form):
voucher = VoucherField(
queryset=Voucher.objects.active(), to_field_name='code',
label=pgettext_lazy('voucher', 'Gift card or discount code'),
widget=forms.TextInput)
def __init__(self, *args, **kwargs):
self.checkout = kwargs.pop('checkout')
initial = kwargs.get('initial', {})
if 'voucher' not in initial:
initial['voucher'] = self.checkout.voucher_code
kwargs['initial'] = initial
super(CheckoutDiscountForm, self).__init__(*args, **kwargs)
def clean(self):
cleaned_data = super(CheckoutDiscountForm, self).clean()
if 'voucher' in cleaned_data:
voucher = cleaned_data['voucher']
try:
discount = voucher.get_discount_for_checkout(self.checkout)
cleaned_data['discount'] = discount
except NotApplicable as e:
self.add_error('voucher', unicode(e))
return cleaned_data
def apply_discount(self):
discount = self.cleaned_data['discount']
voucher = self.cleaned_data['voucher']
self.checkout.discount = discount
self.checkout.voucher_code = voucher.code
| from django import forms
from django.utils.translation import pgettext_lazy
from .models import Voucher, NotApplicable
class VoucherField(forms.ModelChoiceField):
default_error_messages = {
'invalid_choice': pgettext_lazy(
'voucher', pgettext_lazy(
'voucher', 'Discount code incorrect or expired')),
}
class CheckoutDiscountForm(forms.Form):
voucher = VoucherField(
queryset=Voucher.objects.active(), to_field_name='code',
label=pgettext_lazy('voucher', 'Gift card or discount code'),
widget=forms.TextInput)
def __init__(self, *args, **kwargs):
self.checkout = kwargs.pop('checkout')
initial = kwargs.get('initial', {})
if 'voucher' not in initial:
initial['voucher'] = self.checkout.voucher_code
kwargs['initial'] = initial
super(CheckoutDiscountForm, self).__init__(*args, **kwargs)
def clean(self):
cleaned_data = super(CheckoutDiscountForm, self).clean()
if 'voucher' in cleaned_data:
voucher = cleaned_data['voucher']
try:
discount = voucher.get_discount_for_checkout(self.checkout)
cleaned_data['discount'] = discount
except NotApplicable as e:
self.add_error('voucher', str(e))
return cleaned_data
def apply_discount(self):
discount = self.cleaned_data['discount']
voucher = self.cleaned_data['voucher']
self.checkout.discount = discount
self.checkout.voucher_code = voucher.code
|
Handle missing title localisation file. | /**
* i18n plugin
* register handlebars handler which looks up translations in a dictionary
*/
var path = require("path");
var fs = require("fs");
var handlebars = require("handlebars");
module.exports = function makePlugin() {
return function (opts) {
var data = {
"en": {}
};
//load translation data
if (opts.locales) {
try {
opts.locales.forEach( function (loc) {
try {
content = fs.readFileSync(path.join(__dirname + "../../../", loc.file));
data[loc.locale] = JSON.parse(content);
} catch (e) {
console.error("Failed to load: " + e.path);
}
});
} catch (e) {
console.error(e);
}
}
handlebars.registerHelper("i18n", function (msg) {
if (msg && this.file.locale && data[this.file.locale] && data[this.file.locale][msg]) {
return data[this.file.locale][msg];
}
return msg;
});
return function(files, metalsmith, done){
for (filename in files) {
// add locale metadata to files
var locale = filename.split("/")[0];
files[filename]['locale'] = locale;
}
done();
};
};
};
| /**
* i18n plugin
* register handlebars handler which looks up translations in a dictionary
*/
var path = require("path");
var fs = require("fs");
var handlebars = require("handlebars");
module.exports = function makePlugin() {
return function (opts) {
var data = {
"en": {}
};
//load translation data
if (opts.locales) {
try {
opts.locales.forEach( function (loc) {
content = fs.readFileSync(path.join(__dirname + "../../../", loc.file));
data[loc.locale] = JSON.parse(content);
});
} catch (e) {
console.error(e);
}
}
handlebars.registerHelper("i18n", function (msg) {
if (msg && this.file.locale && data[this.file.locale] && data[this.file.locale][msg]) {
return data[this.file.locale][msg];
}
return msg;
});
return function(files, metalsmith, done){
for (filename in files) {
// add locale metadata to files
var locale = filename.split("/")[0];
files[filename]['locale'] = locale;
}
done();
};
};
};
|
Remove atFile entries when we remove files | <?php
namespace Concrete\Core\Entity\Attribute\Value\Value;
use Concrete\Core\File\FileProviderInterface;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table(name="atFile")
*/
class ImageFileValue extends AbstractValue implements FileProviderInterface
{
/**
* @ORM\ManyToOne(targetEntity="\Concrete\Core\Entity\File\File")
* @ORM\JoinColumn(name="fID", referencedColumnName="fID", onDelete="CASCADE")
*/
protected $file;
public function getFileID()
{
if (is_object($this->file)) {
return $this->file->getFileID();
}
return 0;
}
public function getFileObjects()
{
if (is_object($this->file)) {
return array($this->file);
}
return array();
}
public function getValue()
{
return $this->file;
}
public function getFileObject()
{
return $this->file;
}
/**
* @param mixed $value
*/
public function setFileObject($file)
{
$this->file = $file;
}
public function __toString()
{
if (is_object($this->file)) {
return (string) \URL::to('/download_file', $this->file->getFileID());
}
return '';
}
}
| <?php
namespace Concrete\Core\Entity\Attribute\Value\Value;
use Concrete\Core\File\FileProviderInterface;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table(name="atFile")
*/
class ImageFileValue extends AbstractValue implements FileProviderInterface
{
/**
* @ORM\ManyToOne(targetEntity="\Concrete\Core\Entity\File\File")
* @ORM\JoinColumn(name="fID", referencedColumnName="fID")
*/
protected $file;
public function getFileID()
{
if (is_object($this->file)) {
return $this->file->getFileID();
}
return 0;
}
public function getFileObjects()
{
if (is_object($this->file)) {
return array($this->file);
}
return array();
}
public function getValue()
{
return $this->file;
}
public function getFileObject()
{
return $this->file;
}
/**
* @param mixed $value
*/
public function setFileObject($file)
{
$this->file = $file;
}
public function __toString()
{
if (is_object($this->file)) {
return (string) \URL::to('/download_file', $this->file->getFileID());
}
return '';
}
}
|
Add user key for names | const Router = require("falcor-router");
const $ref = require('falcor').Model.ref;
const User = require("./models/User");
const mock = {
content: 'content',
sub: 'subtitle',
};
module.exports = new Router([
{
route: "title",
get: (path) => {
console.log('path:', path);
return { path: [ "title" ], value: $ref({hi: 's'}) };
},
},
{
route: "user",
get: () => {
return User.findOne({ where: { firstName: "John" } }).then(user => {
return { path: [ "user" ], value: $ref(user) }
})
// return { path: [ "user" ], value: 'user' };
},
},
{
route: "users[{integers:indices}]['firstName', 'lastName']",
get: (path) => {
return User.findAll().then(users => {
const array = [];
path.indices.forEach(index => {
const u = users[index];
if (!u) {
array.push({
path: ['users', index],
value: null,
});
} else {
path[2].forEach(key => {
array.push({
path: ['users', index, key],
value: u[key],
});
});
}
});
return { path: [ "users" ], value: $ref(users) }
});
},
},
])
| const Router = require("falcor-router");
const $ref = require('falcor').Model.ref;
const User = require("./models/User");
const mock = {
content: 'content',
sub: 'subtitle',
};
module.exports = new Router([
{
route: "title",
get: (path) => {
console.log('path:', path);
return { path: [ "title" ], value: $ref({hi: 's'}) };
},
},
{
route: "user",
get: () => {
return User.findOne({ where: { firstName: "John" } }).then(user => {
return { path: [ "user" ], value: $ref(user) }
})
// return { path: [ "user" ], value: 'user' };
},
},
{
route: "users[{integers:indices}]",
get: (path) => {
return User.findAll().then(users => {
const array = [];
path.indices.forEach(index => {
const u = users[index];
if (!u) {
array.push({
path: ['users', index],
value: null,
});
} else {
array.push({
path: ['users', index],
value: $ref(u),
});
}
});
return { path: [ "users" ], value: $ref(users) }
});
},
},
])
|
Stop including sourcemap for production mode | const path = require('path');
const webpack = require('webpack');
const nodeEnv = process.env.NODE_ENV || 'development';
const { VueLoaderPlugin } = require('vue-loader');
const config = {
mode: nodeEnv,
entry: "./src/entries/dist.js",
devtool: (nodeEnv === 'production') ? undefined : 'inline-source-map',
output: {
path: path.join(__dirname, 'dist'),
filename: "h5p-audio-recorder.js",
sourceMapFilename: '[file].map'
},
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js'
},
modules: [
path.resolve('./src'),
path.resolve('./node_modules')
]
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
preserveWhitespace: false
},
},
{
test: /\.js$/,
exclude: /node_modules/,
use: 'babel-loader'
},
{
test: /\.(s[ac]ss|css)$/,
use: [
'vue-style-loader',
'css-loader',
'sass-loader'
]
},
{
test: /\.(svg)$/,
include: path.join(__dirname, 'src/images'),
type: 'asset/inline'
}
]
},
plugins: [
// make sure to include the plugin for the magic
new VueLoaderPlugin(),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify(nodeEnv)
}
}),
]
};
module.exports = config;
| const path = require('path');
const webpack = require('webpack');
const nodeEnv = process.env.NODE_ENV || 'development';
const { VueLoaderPlugin } = require('vue-loader');
const config = {
mode: nodeEnv,
entry: "./src/entries/dist.js",
output: {
path: path.join(__dirname, 'dist'),
filename: "h5p-audio-recorder.js",
sourceMapFilename: '[file].map'
},
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js'
},
modules: [
path.resolve('./src'),
path.resolve('./node_modules')
]
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
preserveWhitespace: false
},
},
{
test: /\.js$/,
exclude: /node_modules/,
use: 'babel-loader'
},
{
test: /\.(s[ac]ss|css)$/,
use: [
'vue-style-loader',
'css-loader',
'sass-loader'
]
},
{
test: /\.(svg)$/,
include: path.join(__dirname, 'src/images'),
type: 'asset/inline'
}
]
},
plugins: [
// make sure to include the plugin for the magic
new VueLoaderPlugin(),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify(nodeEnv)
}
}),
]
};
module.exports = config;
|
Add get_property, set_property and delete_property functions | from devicehive.handler import Handler
from devicehive.device_hive import DeviceHive
class ApiCallHandler(Handler):
"""Api call handler class."""
def __init__(self, api, call, *call_args, **call_kwargs):
super(ApiCallHandler, self).__init__(api)
self._call = call
self._call_args = call_args
self._call_kwargs = call_kwargs
self._call_result = None
@property
def call_result(self):
return self._call_result
def handle_connect(self):
self._call_result = getattr(self.api, self._call)(*self._call_args,
**self._call_kwargs)
self.api.disconnect()
class DeviceHiveApi(object):
"""Device hive api class."""
def __init__(self, transport_url, **options):
self._transport_url = transport_url
self._options = options
def _call(self, call, *call_args, **call_kwargs):
device_hive = DeviceHive(ApiCallHandler, call, *call_args,
**call_kwargs)
device_hive.connect(self._transport_url, **self._options)
return device_hive.transport.handler.handler.call_result
def get_info(self):
return self._call('get_info')
def get_cluster_info(self):
return self._call('get_cluster_info')
def get_property(self, name):
return self._call('get_property', name)
def set_property(self, name, value):
return self._call('set_property', name, value)
def delete_property(self, name):
return self._call('delete_property', name)
| from devicehive.handler import Handler
from devicehive.device_hive import DeviceHive
class ApiCallHandler(Handler):
"""Api call handler class."""
def __init__(self, api, call, *call_args, **call_kwargs):
super(ApiCallHandler, self).__init__(api)
self._call = call
self._call_args = call_args
self._call_kwargs = call_kwargs
self._call_result = None
@property
def call_result(self):
return self._call_result
def handle_connect(self):
self._call_result = getattr(self.api, self._call)(*self._call_args,
**self._call_kwargs)
self.api.disconnect()
class DeviceHiveApi(object):
"""Device hive api class."""
def __init__(self, transport_url, **options):
self._transport_url = transport_url
self._options = options
def _call(self, call, *call_args, **call_kwargs):
device_hive = DeviceHive(ApiCallHandler, call, *call_args,
**call_kwargs)
device_hive.connect(self._transport_url, **self._options)
return device_hive.transport.handler.handler.call_result
def get_info(self):
return self._call('get_info')
def get_cluster_info(self):
return self._call('get_cluster_info')
|
[CONSISTENCY] Add newline between different phpdoc tag in docBlock | <?php
/**
* @author Pierre-Henry Soria <[email protected]>
* @copyright (c) 2018-2019, 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 / Core / Class
*/
namespace PH7;
use PH7\Framework\Math\Measure\Year as YearMeasure;
class UserBirthDateCore
{
const DEFAULT_AGE = 30;
const BIRTHDATE_DELIMITER = '-';
const NUMBER_ARRAY_ELEMENTS = 3;
/**
* @param string $sBirthDate YYYY-MM-DD format.
*
* @return int
*/
public static function getAgeFromBirthDate($sBirthDate)
{
$aAge = explode(self::BIRTHDATE_DELIMITER, $sBirthDate);
if (self::isInvalidBirthDate($aAge)) {
return self::DEFAULT_AGE;
}
return (new YearMeasure($aAge[0], $aAge[1], $aAge[2]))->get();
}
/**
* @param array $aAge
*
* @return bool
*/
private static function isInvalidBirthDate(array $aAge)
{
$iAgeElements = count($aAge);
return $iAgeElements < self::NUMBER_ARRAY_ELEMENTS ||
$iAgeElements > self::NUMBER_ARRAY_ELEMENTS;
}
}
| <?php
/**
* @author Pierre-Henry Soria <[email protected]>
* @copyright (c) 2018-2019, 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 / Core / Class
*/
namespace PH7;
use PH7\Framework\Math\Measure\Year as YearMeasure;
class UserBirthDateCore
{
const DEFAULT_AGE = 30;
const BIRTHDATE_DELIMITER = '-';
const NUMBER_ARRAY_ELEMENTS = 3;
/**
* @param string $sBirthDate YYYY-MM-DD format.
*
* @return int
*/
public static function getAgeFromBirthDate($sBirthDate)
{
$aAge = explode(self::BIRTHDATE_DELIMITER, $sBirthDate);
if (self::isInvalidBirthDate($aAge)) {
return self::DEFAULT_AGE;
}
return (new YearMeasure($aAge[0], $aAge[1], $aAge[2]))->get();
}
/**
* @param array $aAge
* @return bool
*/
private static function isInvalidBirthDate(array $aAge)
{
$iAgeElements = count($aAge);
return $iAgeElements < self::NUMBER_ARRAY_ELEMENTS ||
$iAgeElements > self::NUMBER_ARRAY_ELEMENTS;
}
}
|
Set cov-core dependency to 1.8 | import setuptools
setuptools.setup(name='pytest-cov',
version='1.6',
description='py.test plugin for coverage reporting with '
'support for both centralised and distributed testing, '
'including subprocesses and multiprocessing',
long_description=open('README.rst').read().strip(),
author='Marc Schlaich',
author_email='[email protected]',
url='https://github.com/schlamar/pytest-cov',
py_modules=['pytest_cov'],
install_requires=['pytest>=2.5.2',
'cov-core>=1.8'],
entry_points={'pytest11': ['pytest_cov = pytest_cov']},
license='MIT License',
zip_safe=False,
keywords='py.test pytest cover coverage distributed parallel',
classifiers=['Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.4',
'Programming Language :: Python :: 2.5',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.0',
'Programming Language :: Python :: 3.1',
'Topic :: Software Development :: Testing'])
| import setuptools
setuptools.setup(name='pytest-cov',
version='1.6',
description='py.test plugin for coverage reporting with '
'support for both centralised and distributed testing, '
'including subprocesses and multiprocessing',
long_description=open('README.rst').read().strip(),
author='Marc Schlaich',
author_email='[email protected]',
url='https://github.com/schlamar/pytest-cov',
py_modules=['pytest_cov'],
install_requires=['pytest>=2.5.2',
'cov-core>=1.6'],
entry_points={'pytest11': ['pytest_cov = pytest_cov']},
license='MIT License',
zip_safe=False,
keywords='py.test pytest cover coverage distributed parallel',
classifiers=['Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.4',
'Programming Language :: Python :: 2.5',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.0',
'Programming Language :: Python :: 3.1',
'Topic :: Software Development :: Testing'])
|
Add help text to enterprise settings | hqDefine("accounting/js/enterprise_settings", [
'jquery',
'knockout',
'underscore',
'hqwebapp/js/assert_properties',
'hqwebapp/js/initial_page_data',
], function(
$,
ko,
_,
assertProperties,
initialPageData
) {
var settingsFormModel = function(options) {
assertProperties.assert(options, ['accounts_email'], ['restrict_signup', 'restricted_domains']);
var self = {};
self.restrictSignup = ko.observable(options.restrict_signup);
var context = {
domains: options.restricted_domains.join(", "),
email: options.accounts_email,
};
self.restrictSignupHelp = _.template(gettext("Do not allow new users to sign up on commcarehq.org. " +
"This may take up to an hour to take effect. " +
"<br>This will affect users with email addresses from the following domains: " +
"<strong><%= domains %></strong>" +
"<br>Contact <a href='mailto:<%= email %>'><%= email %></a> to change the list of domains."))(context);
return self;
};
$(function() {
var form = settingsFormModel({
accounts_email: initialPageData.get('accounts_email'),
restricted_domains: initialPageData.get('restricted_domains'),
restrict_signup: initialPageData.get('restrict_signup'),
});
$('#enterprise-settings-form').koApplyBindings(form);
});
});
| hqDefine("accounting/js/enterprise_settings", [
'jquery',
'knockout',
'underscore',
'hqwebapp/js/assert_properties',
'hqwebapp/js/initial_page_data',
], function(
$,
ko,
_,
assertProperties,
initialPageData
) {
var settingsFormModel = function(options) {
assertProperties.assert(options, ['accounts_email'], ['restrict_signup', 'restricted_domains']);
var self = {};
self.restrictSignup = ko.observable(options.restrict_signup);
var context = {
domains: options.restricted_domains.join(", "),
email: options.accounts_email,
};
self.restrictSignupHelp = _.template(gettext("Do not allow new users to sign up on commcarehq.org." +
"<br>This will affect users with email addresses from the following domains: " +
"<strong><%= domains %></strong>" +
"<br>Contact <a href='mailto:<%= email %>'><%= email %></a> to change the list of domains."))(context);
return self;
};
$(function() {
var form = settingsFormModel({
accounts_email: initialPageData.get('accounts_email'),
restricted_domains: initialPageData.get('restricted_domains'),
restrict_signup: initialPageData.get('restrict_signup'),
});
$('#enterprise-settings-form').koApplyBindings(form);
});
});
|
Set classes for showing the lists horizontally | import React from 'react';
import { List, ListSubHeader, ListCheckbox } from 'react-toolbox/lib/list';
const SponsorAffinities = () => {
return (
<div className="horizontal">
<List selectable ripple className="horizontalChild">
<ListSubHeader caption='list_a' />
<ListCheckbox
caption='affinity'
checked={false} />
<ListCheckbox
caption='affinity'
checked={false} />
<ListCheckbox
caption='affinity'
checked={false} />
<ListCheckbox
caption='affinity'
checked={false} />
<ListCheckbox
caption='affinity'
checked={false} />
<ListCheckbox
caption='affinity'
checked={false} />
</List>
<List selectable ripple className="horizontalChild">
<ListSubHeader caption='list_b' />
<ListCheckbox
caption='affinity'
checked={false} />
<ListCheckbox
caption='affinity'
checked={false} />
<ListCheckbox
caption='affinity'
checked={false} />
<ListCheckbox
caption='affinity'
checked={false} />
<ListCheckbox
caption='affinity'
checked={false} />
<ListCheckbox
caption='affinity'
checked={false} />
</List>
</div>
);
};
export default SponsorAffinities; | import React from 'react';
import { List, ListSubHeader, ListCheckbox } from 'react-toolbox/lib/list';
const SponsorAffinities = () => {
return (
<div>
<List selectable ripple>
<ListSubHeader caption='list_a' />
<ListCheckbox
caption='affinity'
checked={false} />
<ListCheckbox
caption='affinity'
checked={false} />
<ListCheckbox
caption='affinity'
checked={false} />
<ListCheckbox
caption='affinity'
checked={false} />
<ListCheckbox
caption='affinity'
checked={false} />
<ListCheckbox
caption='affinity'
checked={false} />
</List>
<List selectable ripple>
<ListSubHeader caption='list_b' />
<ListCheckbox
caption='affinity'
checked={false} />
<ListCheckbox
caption='affinity'
checked={false} />
<ListCheckbox
caption='affinity'
checked={false} />
<ListCheckbox
caption='affinity'
checked={false} />
<ListCheckbox
caption='affinity'
checked={false} />
<ListCheckbox
caption='affinity'
checked={false} />
</List>
</div>
);
};
export default SponsorAffinities; |
Add support for partial JSON messages from the server. | 'use strict';
var React = require('react');
var WebSocket = require('ws');
module.exports = React.createClass({
propTypes: {
url: React.PropTypes.string.isRequired,
onMessage: React.PropTypes.func.isRequired,
debug: React.PropTypes.bool
},
getDefaultProps: function () {
return {
debug: false
}
},
getInitialState: function () {
return {
ws: new WebSocket(this.props.url),
partial: ''
}
},
log: function (logline) {
if (this.props.debug === true) {
console.log(logline);
}
},
componentWillMount: function () {
this.log('Websocket componentWillMount');
var self = this;
var ws = self.state.ws;
var partial = self.state.partial;
ws.addEventListener('open', function open() {
self.log('Websocket connected');
});
ws.addEventListener('message', function incoming(event) {
try {
var data = JSON.parse(partial + event.data);
self.log('Websocket incoming data');
self.log(partial + event.data);
partial = '';
self.setState({partial:partial});
self.props.onMessage(data);
} catch (err) {
partial += event.data;
self.log('Websocket storing partial');
self.setState({partial:partial});
}
});
ws.addEventListener('close', function close() {
self.log('Websocket disconnected');
});
},
componentWillUnmount: function () {
this.log('Websocket componentWillUnmount');
this.state.ws.close();
},
render: function () {
return React.createElement("div", React.__spread({}, this.props))
}
});
| 'use strict';
var React = require('react');
var WebSocket = require('ws');
module.exports = React.createClass({
propTypes: {
url: React.PropTypes.string.isRequired,
onMessage: React.PropTypes.func.isRequired,
debug: React.PropTypes.bool
},
getDefaultProps: function () {
return {
debug: false
}
},
getInitialState: function () {
return {
ws: new WebSocket(this.props.url)
}
},
log: function (logline) {
if (this.props.debug === true) {
console.log(logline);
}
},
componentWillMount: function () {
this.log('Websocket componentWillMount');
var self = this;
var ws = self.state.ws;
ws.addEventListener('open', function open() {
self.log('Websocket connected');
});
ws.addEventListener('message', function incoming(event) {
var data = JSON.parse(event.data);
self.log('Websocket incoming data');
self.log(event.data);
self.props.onMessage(data);
});
ws.addEventListener('close', function close() {
self.log('Websocket disconnected');
});
},
componentWillUnmount: function () {
this.log('Websocket componentWillUnmount');
this.state.ws.close();
},
render: function () {
return React.createElement("div", React.__spread({}, this.props))
}
});
|
Set object id and initiate parent_ids array | (function (tree) {
tree.Extend = function Extend(selector, option, index) {
this.selector = selector;
this.option = option;
this.index = index;
this.object_id = tree.Extend.next_id++;
this.parent_ids = [this.object_id];
switch(option) {
case "all":
this.allowBefore = true;
this.allowAfter = true;
break;
default:
this.allowBefore = false;
this.allowAfter = false;
break;
}
};
tree.Extend.next_id = 0;
tree.Extend.prototype = {
type: "Extend",
accept: function (visitor) {
this.selector = visitor.visit(this.selector);
},
eval: function (env) {
return new(tree.Extend)(this.selector.eval(env), this.option, this.index);
},
clone: function (env) {
return new(tree.Extend)(this.selector, this.option, this.index);
},
findSelfSelectors: function (selectors) {
var selfElements = [],
i,
selectorElements;
for(i = 0; i < selectors.length; i++) {
selectorElements = selectors[i].elements;
// duplicate the logic in genCSS function inside the selector node.
// future TODO - move both logics into the selector joiner visitor
if (i > 0 && selectorElements.length && selectorElements[0].combinator.value === "") {
selectorElements[0].combinator.value = ' ';
}
selfElements = selfElements.concat(selectors[i].elements);
}
this.selfSelectors = [{ elements: selfElements }];
}
};
})(require('../tree'));
| (function (tree) {
tree.Extend = function Extend(selector, option, index) {
this.selector = selector;
this.option = option;
this.index = index;
switch(option) {
case "all":
this.allowBefore = true;
this.allowAfter = true;
break;
default:
this.allowBefore = false;
this.allowAfter = false;
break;
}
};
tree.Extend.prototype = {
type: "Extend",
accept: function (visitor) {
this.selector = visitor.visit(this.selector);
},
eval: function (env) {
return new(tree.Extend)(this.selector.eval(env), this.option, this.index);
},
clone: function (env) {
return new(tree.Extend)(this.selector, this.option, this.index);
},
findSelfSelectors: function (selectors) {
var selfElements = [],
i,
selectorElements;
for(i = 0; i < selectors.length; i++) {
selectorElements = selectors[i].elements;
// duplicate the logic in genCSS function inside the selector node.
// future TODO - move both logics into the selector joiner visitor
if (i > 0 && selectorElements.length && selectorElements[0].combinator.value === "") {
selectorElements[0].combinator.value = ' ';
}
selfElements = selfElements.concat(selectors[i].elements);
}
this.selfSelectors = [{ elements: selfElements }];
}
};
})(require('../tree'));
|
Add implemented interfaces to rule history | /**
* @license
* Copyright 2019 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
package: 'foam.nanos.ruler',
name: 'RuleHistory',
documentation: 'Represents rule execution history.',
implements: [
'foam.nanos.auth.CreatedAware',
'foam.nanos.auth.LastModifiedAware'
],
properties: [
{
class: 'Long',
name: 'id',
visibility: 'RO'
},
{
class: 'DateTime',
name: 'created',
documentation: 'Creation date.'
},
{
class: 'DateTime',
name: 'lastModified',
documentation: 'Last modified date.'
},
{
class: 'Reference',
of: 'foam.nanos.ruler.Rule',
name: 'ruleId',
documentation: 'The applied rule.'
},
{
class: 'Object',
name: 'ObjectId',
visibility: 'RO',
documentation: 'Id of the object onwhich rule is applied.'
},
{
class: 'String',
name: 'objectDaoKey',
visibility: 'RO',
documentation: 'DAO name of the object'
},
{
class: 'Object',
name: 'result',
documentation: 'Result of rule execution.',
tableCellFormatter: function (value) {
if (!!value) {
this.add(value.toString());
}
}
}
]
});
| /**
* @license
* Copyright 2019 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
package: 'foam.nanos.ruler',
name: 'RuleHistory',
documentation: 'Represents rule execution history.',
properties: [
{
class: 'Long',
name: 'id',
visibility: 'RO'
},
{
class: 'DateTime',
name: 'created',
documentation: 'Creation date.'
},
{
class: 'DateTime',
name: 'lastModified',
documentation: 'Last modified date.'
},
{
class: 'Reference',
of: 'foam.nanos.ruler.Rule',
name: 'ruleId',
documentation: 'The applied rule.'
},
{
class: 'Object',
name: 'ObjectId',
visibility: 'RO',
documentation: 'Id of the object onwhich rule is applied.'
},
{
class: 'String',
name: 'objectDaoKey',
visibility: 'RO',
documentation: 'DAO name of the object'
},
{
class: 'Object',
name: 'result',
documentation: 'Result of rule execution.',
tableCellFormatter: function (value) {
if (!!value) {
this.add(value.toString());
}
}
}
]
});
|
Create an HTTP with a coordinator. | #!/usr/bin/env/node
/*
Provide a command-line interface for `reconfigure`.
___ greeting, usage ___ en_US ___
usage: node.bin.js
___ serve, usage ___ en_US ___
usage: node bin.js reconfigure server
options:
-l, --listen [string] IP and port to bind to.
-i, --id [string] reconfigure instance ID (or IP)
___ ___ ___
*/
require('arguable')(module, require('cadence')(function (async, options) {
var UserAgent = require('./reconfigure/ua.js')
var Consensus = require('./reconfigure/consensus.js')
var Coordinator = require('./reconfigure/coordinator.js')
var http = require ('./reconfigure/http.js')
switch (options.command[0]) {
case 'serve':
console.log('coming soon')
serve(options.param.listen.split(':'))
break
case 'greeting':
if (options.param.string != null) {
console.log(options.param.string)
} else {
console.log('Hello, World!')
}
break
}
function serve (ip) {
var port
if (ip.length) {
port = ip[1]
ip = ip[0]
} else {
port = '8080'
ip = ip[0]
}
async(function () {
var server = new http({
coordinator: new Coordinator(
new Consensus('reconfigure', ip, port, async()),
new UserAgent()
)
})
var disp = server.dispatcher()
disp.server()
}, function () {
//Consensus stopped
})
}
}))
| #!/usr/bin/env/node
/*
Provide a command-line interface for `reconfigure`.
___ greeting, usage ___ en_US ___
usage: node.bin.js
___ serve, usage ___ en_US ___
usage: node bin.js reconfigure server
options:
-l, --listen [string] IP and port to bind to.
-i, --id [string] reconfigure instance ID (or IP)
___ ___ ___
*/
require('arguable')(module, require('cadence')(function (async, options) {
switch (options.command[0]) {
case 'serve':
var ip, port
console.log('coming soon')
ip = options.param.listen.split(':')
if (ip.length) {
port = ip[1]
ip = ip[0]
} else {
port = '8080'
ip = ip[0]
}
console.log('ip: ' + ip + ' port: ' + port)
break
case 'greeting':
if (options.param.string != null) {
console.log(options.param.string)
} else {
console.log('Hello, World!')
}
break
}
}))
|
Add link for domains section | import React from 'react';
import { c } from 'ttag';
import {
useEventManager,
useOrganization,
useDomains,
SubTitle,
Alert,
PrimaryButton,
Button,
Block,
useModal
} from 'react-components';
import DomainModal from './DomainModal';
import DomainsTable from './DomainsTable';
const DomainsSection = () => {
const [domains, loading] = useDomains();
const [organization] = useOrganization();
const { isOpen, open, close } = useModal();
const { UsedDomains, MaxDomains } = organization;
const { call } = useEventManager(); // TODO: Use event manager or expose a refresh fn in the models?
return (
<>
<SubTitle>{c('Title').t`Manage custom domains`}</SubTitle>
<Alert learnMore="https://protonmail.com/support/categories/custom-domains/">
{c('Message')
.t`Add a custom filter to perform actions such as automatically labeling or archiving messages.`}
</Alert>
<Block>
<PrimaryButton onClick={open}>{c('Action').t`Add domain`}</PrimaryButton>
<DomainModal show={isOpen} onClose={close} />
<Button disabled={loading} onClick={call}>{c('Action').t`Refresh status`}</Button>
</Block>
{!loading && !domains.length ? <Alert>{c('Info').t`No domains yet`}</Alert> : null}
{loading ? null : <DomainsTable domains={domains} />}
<Block>
{UsedDomains} / {MaxDomains} {c('Info').t`domains used`}
</Block>
</>
);
};
export default DomainsSection;
| import React from 'react';
import { c } from 'ttag';
import {
useEventManager,
useOrganization,
useDomains,
SubTitle,
Alert,
PrimaryButton,
Button,
Block,
useModal
} from 'react-components';
import DomainModal from './DomainModal';
import DomainsTable from './DomainsTable';
const DomainsSection = () => {
const [domains, loading] = useDomains();
const [organization] = useOrganization();
const { isOpen, open, close } = useModal();
const { UsedDomains, MaxDomains } = organization;
const { call } = useEventManager(); // TODO: Use event manager or expose a refresh fn in the models?
return (
<>
<SubTitle>{c('Title').t`Domains`}</SubTitle>
<Alert learnMore="todo">
{c('Message')
.t`Add a custom filter to perform actions such as automatically labeling or archiving messages.`}
</Alert>
<Block>
<PrimaryButton onClick={open}>{c('Action').t`Add domain`}</PrimaryButton>
<DomainModal show={isOpen} onClose={close} />
<Button disabled={loading} onClick={call}>{c('Action').t`Refresh status`}</Button>
</Block>
{!loading && !domains.length ? <Alert>{c('Info').t`No domains yet`}</Alert> : null}
{loading ? null : <DomainsTable domains={domains} />}
<Block>
{UsedDomains} / {MaxDomains} {c('Info').t`domains used`}
</Block>
</>
);
};
export default DomainsSection;
|
Add some `toString` conversions (required by MongoDB) | module.exports = function(sugar, schemas, assert, api) {
return function(cb) {
api.create(null, function(err, d) {
var name = d.name + d.name;
d.name = name;
sugar.update(schemas.Author, d._id, d, function(err, d) {
assert.equal(d.name, name);
sugar.count(schemas.Author, function(err, count) {
assert.equal(count, 1);
sugar.getOne(schemas.Author, d._id, function(err, author) {
// depending on implementation author might be missing
// fields that evaluate as false
assert.equal(d._id, author._id.toString()); // XXX
assert.deepEqual(d.extra, author.extra);
assert.equal(d.name, author.name);
assert.equal(d.created, author.created.toString()); // XXX
cb(err, d);
});
});
});
});
};
};
| module.exports = function(sugar, schemas, assert, api) {
return function(cb) {
api.create(null, function(err, d) {
var name = d.name + d.name;
d.name = name;
sugar.update(schemas.Author, d._id, d, function(err, d) {
assert.equal(d.name, name);
sugar.count(schemas.Author, function(err, count) {
assert.equal(count, 1);
sugar.getOne(schemas.Author, d._id, function(err, author) {
// depending on implementation author might be missing
// fields that evaluate as false
assert.equal(d._id, author._id);
assert.equal(d.extra, author.extra);
assert.equal(d.name, author.name);
assert.equal(d.created, author.created);
cb(err, d);
});
});
});
});
};
};
|
Replace all occurances of $graph->getNumberOfEdges()
replaced with count($graph->getEdges()) | <?php
use Fhaculty\Graph\Algorithm\Complete;
use Fhaculty\Graph\Algorithm\Directed;
use Fhaculty\Graph\Graph;
use Fhaculty\Graph\Loader\CompleteGraph;
class CompleteGraphTest extends TestCase
{
public function testOne()
{
$loader = new CompleteGraph(1);
$graph = $loader->createGraph();
$expected = new Graph();
$expected->createVertex();
$this->assertGraphEquals($expected, $graph);
}
public function testUndirected()
{
$n = 9;
$loader = new CompleteGraph($n);
$graph = $loader->createGraph();
$this->assertEquals($n, count($graph->getVertices()));
$this->assertEquals($n*($n-1)/2, count($graph->getEdges()));
}
public function testDirected()
{
$n = 8;
$loader = new CompleteGraph($n);
$loader->setEnableDirectedEdges(true);
$graph = $loader->createGraph();
$this->assertEquals($n, count($graph->getVertices()));
$this->assertEquals($n*($n-1), count($graph->getEdges())); // n*(n-1) for directed graphs
$alg = new Directed($graph);
$this->assertTrue($alg->isDirected());
$alg = new Complete($graph);
$this->assertTrue($alg->isComplete());
}
}
| <?php
use Fhaculty\Graph\Algorithm\Complete;
use Fhaculty\Graph\Algorithm\Directed;
use Fhaculty\Graph\Graph;
use Fhaculty\Graph\Loader\CompleteGraph;
class CompleteGraphTest extends TestCase
{
public function testOne()
{
$loader = new CompleteGraph(1);
$graph = $loader->createGraph();
$expected = new Graph();
$expected->createVertex();
$this->assertGraphEquals($expected, $graph);
}
public function testUndirected()
{
$n = 9;
$loader = new CompleteGraph($n);
$graph = $loader->createGraph();
$this->assertEquals($n, count($graph->getVertices()));
$this->assertEquals($n*($n-1)/2, $graph->getNumberOfEdges());
}
public function testDirected()
{
$n = 8;
$loader = new CompleteGraph($n);
$loader->setEnableDirectedEdges(true);
$graph = $loader->createGraph();
$this->assertEquals($n, count($graph->getVertices()));
$this->assertEquals($n*($n-1), $graph->getNumberOfEdges()); // n*(n-1) for directed graphs
$alg = new Directed($graph);
$this->assertTrue($alg->isDirected());
$alg = new Complete($graph);
$this->assertTrue($alg->isComplete());
}
}
|
Move app name log to timestamp | 'use strict';
const winston = require('winston');
// Setup winston default instance
const LOGGER_LEVEL = process.env.LOGGER_LEVEL || 'info';
const LOGGER_TIMESTAMP = !(process.env.LOGGER_TIMESTAMP === 'false');
const LOGGER_COLORIZE = !(process.env.LOGGER_COLORIZE === 'false');
const LOGGER_PRETTY_PRINT = !(process.env.LOGGER_PRETTY_PRINT === 'false');
winston.configure({
transports: [
new winston.transports.Console({
prettyPrint: LOGGER_PRETTY_PRINT,
colorize: LOGGER_COLORIZE,
level: LOGGER_LEVEL,
formatter: (options) => {
const message = [];
if (LOGGER_TIMESTAMP) {
message.push(new Date().toISOString());
// TODO: log dyno name
message.push('app[]:');
}
message.push(`at=${options.level}`);
// TODO: get from config
message.push('application=blink');
if (options.meta.length > 0) {
options.meta.forEach((key, value) => {
message.push(`${key}=${value}`);
});
}
if (options.message) {
message.push(options.message);
}
return message.join(' ');
},
}),
],
exceptionHandlers: [
new winston.transports.Console({
prettyPrint: LOGGER_PRETTY_PRINT,
colorize: LOGGER_COLORIZE,
}),
],
});
| 'use strict';
const winston = require('winston');
// Setup winston default instance
const LOGGER_LEVEL = process.env.LOGGER_LEVEL || 'info';
const LOGGER_TIMESTAMP = !(process.env.LOGGER_TIMESTAMP === 'false');
const LOGGER_COLORIZE = !(process.env.LOGGER_COLORIZE === 'false');
const LOGGER_PRETTY_PRINT = !(process.env.LOGGER_PRETTY_PRINT === 'false');
winston.configure({
transports: [
new winston.transports.Console({
prettyPrint: LOGGER_PRETTY_PRINT,
colorize: LOGGER_COLORIZE,
level: LOGGER_LEVEL,
formatter: (options) => {
const message = [];
if (LOGGER_TIMESTAMP) {
message.push(new Date().toISOString());
}
// TODO: log dyno name
message.push('app[]:');
message.push(`at=${options.level}`);
// TODO: get from config
message.push('application=blink');
if (options.meta.length > 0) {
options.meta.forEach((key, value) => {
message.push(`${key}=${value}`);
});
}
if (options.message) {
message.push(options.message);
}
return message.join(' ');
},
}),
],
exceptionHandlers: [
new winston.transports.Console({
prettyPrint: LOGGER_PRETTY_PRINT,
colorize: LOGGER_COLORIZE,
}),
],
});
|
Make cities a property, set inside constructor | <?php
namespace SepomexPhp;
class Locations implements \IteratorAggregate, \Countable
{
/** @var Location[] */
private $collection;
/** @var Cities */
private $cities;
public function __construct(Location ...$location)
{
$this->collection = $location;
$this->cities = $this->extractUniqueCities(...$location);
}
public static function extractUniqueCities(Location ...$locations): Cities
{
// This method is static because it does not use $this
$cities = [];
foreach ($locations as $location) {
if ($location->hasCity()) {
$city = $location->city();
if (! array_key_exists($city->id(), $cities)) {
$cities[$city->id()] = $location->city();
}
}
}
return new Cities(...$cities);
}
public function getIterator()
{
return new \ArrayIterator($this->collection);
}
public function count(): int
{
return count($this->collection);
}
/**
* @return Cities|City[]
*/
public function cities(): Cities
{
return $this->cities;
}
public function asArray(): array
{
$array = [];
foreach ($this->collection as $location) {
$array[] = $location->asArray();
}
return $array;
}
}
| <?php
namespace SepomexPhp;
class Locations implements \IteratorAggregate, \Countable
{
/** @var Location[] */
private $collection;
public function __construct(Location ...$location)
{
$this->collection = $location;
public static function extractUniqueCities(Location ...$locations): Cities
{
// This method is static because it does not use $this
$cities = [];
foreach ($locations as $location) {
if ($location->hasCity()) {
$city = $location->city();
if (! array_key_exists($city->id(), $cities)) {
$cities[$city->id()] = $location->city();
}
}
}
return new Cities(...$cities);
}
public function getIterator()
{
return new \ArrayIterator($this->collection);
}
public function count(): int
{
return count($this->collection);
}
/**
* @return Cities|City[]
*/
public function cities(): Cities
{
$cities = [];
foreach ($this->collection as $location) {
if ($location->hasCity()) {
$city = $location->city();
if (! array_key_exists($city->id(), $cities)) {
$cities[$city->id()] = $location->city();
}
}
}
return new Cities(...$cities);
}
public function asArray(): array
{
$array = [];
foreach ($this->collection as $location) {
$array[] = $location->asArray();
}
return $array;
}
}
|
Tag searching now really works! | module.exports = function (models) {
const {
Photo,
User
} = models;
return {
searchPhotos(pattern) {
let regex = new RegExp(pattern, 'i');
return new Promise((resolve, reject) => {
Photo.find({
$or: [{
'title': regex
}, {
'description': regex
}]
},
(err, photos) => {
if (err) {
reject(err);
}
resolve(photos);
})
});
},
searchUsers(pattern) {
let regex = new RegExp(pattern, 'i');
return new Promise((resolve, reject) => {
User.find({
$or: [{
'username': regex
}, {
'description': regex
}, {
'name': regex
}]
},
(err, users) => {
if (err) {
reject(err);
}
resolve(users);
})
});
},
searchTags(tag) {
return new Promise((resolve, reject) => {
Photo.find({
$or: [{
'tags': tag
}]
},
(err, photos) => {
if (err) {
reject(err);
}
resolve(photos);
})
});
},
};
}; | module.exports = function (models) {
const {
Photo,
User
} = models;
return {
searchPhotos(pattern) {
let regex = new RegExp(pattern, 'i');
return new Promise((resolve, reject) => {
Photo.find({
$or: [{
'title': regex
}, {
'description': regex
}]
},
(err, photos) => {
if (err) {
reject(err);
}
resolve(photos);
})
});
},
searchUsers(pattern) {
let regex = new RegExp(pattern, 'i');
return new Promise((resolve, reject) => {
User.find({
$or: [{
'username': regex
}, {
'description': regex
}, {
'name': regex
}]
},
(err, users) => {
if (err) {
reject(err);
}
resolve(users);
})
});
},
searchTags(tag) {
return new Promise((resolve, reject) => {
let regex = new RegExp(tag, 'i');
Photo.find({
$or: [{
'tags': regex
}]
},
(err, photos) => {
if (err) {
reject(err);
}
resolve(photos);
})
});
},
};
}; |
Update: Remove unused variable and import | var minimatch = require('minimatch');
var cheerio = require('cheerio');
var marked = require('marked');
var config = require('../config/marked');
marked.setOptions(config);
function plugin(opts) {
return function(files, metalsmith, done) {
// Get global metadata.
var metadata = metalsmith.metadata();
// Get all file names.
Object.keys(files)
// Get stylesheets file names.
.filter(minimatch.filter('*.html', { matchBase: true }))
// Curate content.
.forEach(function(file) {
// Get file data.
var data = files[file];
// Get file HTML.
var html = data.contents.toString();
// Prepare HTML for analysis.
var $ = cheerio.load(html, {
decodeEntities: false
});
// Find all <jade> nodes.
$('md').each(function(i, el) {
// Get the content.
var source = $(this).html();
// Render the content as Jade.
var html = marked(source);
// Replace the <jade> node with the new rendered content.
$(this).replaceWith(html);
});
// Save updated HTML.
data.contents = new Buffer($.html(), 'utf8');
});
done();
}
}
module.exports = plugin;
| var minimatch = require('minimatch');
var cheerio = require('cheerio');
var extend = require('extend');
var marked = require('marked');
var config = require('../config/marked');
marked.setOptions(config);
function plugin(opts) {
return function(files, metalsmith, done) {
// Get global metadata.
var metadata = metalsmith.metadata();
// Get all file names.
Object.keys(files)
// Get stylesheets file names.
.filter(minimatch.filter('*.html', { matchBase: true }))
// Curate content.
.forEach(function(file) {
// Get file data.
var data = files[file];
// Get file HTML.
var html = data.contents.toString();
// Prepare HTML for analysis.
var $ = cheerio.load(html, {
decodeEntities: false
});
// Find all <jade> nodes.
$('md').each(function(i, el) {
// Get the content.
var source = $(this).html();
// Merge global metadata with local file data.
var options = extend({}, opts, metadata, data);
// Render the content as Jade.
var html = marked(source);
// Replace the <jade> node with the new rendered content.
$(this).replaceWith(html);
});
// Save updated HTML.
data.contents = new Buffer($.html(), 'utf8');
});
done();
}
}
module.exports = plugin;
|
Exit early if MySql is not present. Fixes MySql not installed message being displayed when database creation was successful. | <?php
namespace App\Actions;
use App\Shell\Shell;
use Symfony\Component\Process\ExecutableFinder;
class CreateDatabase
{
use LamboAction;
protected $finder;
protected $shell;
public function __construct(Shell $shell, ExecutableFinder $finder)
{
$this->finder = $finder;
$this->shell = $shell;
}
public function __invoke()
{
if (! (config('lambo.store.create_database') || config('lambo.store.full'))) {
return;
}
if (! $this->mysqlExists()) {
$this->warn("MySql does not seem to be installed. Skipping new database creation.");
return;
}
$this->logStep('Creating database');
$process = $this->shell->execInProject($this->command());
$this->abortIf(! $process->isSuccessful(), "The new database was not created.", $process);
$this->info('Created a new database ' . config('lambo.store.database_name'));
}
protected function mysqlExists()
{
return $this->finder->find('mysql') !== null;
}
protected function command()
{
return sprintf(
'mysql --user=%s --password=%s -e "CREATE DATABASE IF NOT EXISTS %s";',
config('lambo.store.database_username'),
config('lambo.store.database_password'),
config('lambo.store.database_name')
);
}
}
| <?php
namespace App\Actions;
use App\Shell\Shell;
use Symfony\Component\Process\ExecutableFinder;
class CreateDatabase
{
use LamboAction;
protected $finder;
protected $shell;
public function __construct(Shell $shell, ExecutableFinder $finder)
{
$this->finder = $finder;
$this->shell = $shell;
}
public function __invoke()
{
if (! (config('lambo.store.create_database') || config('lambo.store.full'))) {
return;
}
$this->logStep('Creating database');
if ($this->mysqlExists()) {
$process = $this->shell->execInProject($this->command());
$this->abortIf(! $process->isSuccessful(), "The new database was not created.", $process);
$this->info('Created a new database ' . config('lambo.store.database_name'));
}
$this->warn("MySql does not seem to be installed. Skipping new database creation.");
}
protected function mysqlExists()
{
return $this->finder->find('mysql') !== null;
}
protected function command()
{
return sprintf(
'mysql --user=%s --password=%s -e "CREATE DATABASE IF NOT EXISTS %s";',
config('lambo.store.database_username'),
config('lambo.store.database_password'),
config('lambo.store.database_name')
);
}
}
|
Include enum class name when using flags. | package wge3.game.entity.creatures;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import wge3.game.engine.constants.StateFlag;
import static wge3.game.engine.constants.Team.PlayerTeam;
public final class Player extends Creature {
private OrthographicCamera camera;
private ShapeRenderer shapeRenderer;
private boolean showHP;
public Player() {
setSprite(4, 3);
team = PlayerTeam;
size = 14;
HP.setMaximum(100);
strength = 10;
defense = 5;
stateFlags.add(StateFlag.PICKS_UP_ITEMS);
showHP = true;
shapeRenderer = new ShapeRenderer();
}
public void setCamera(OrthographicCamera camera) {
this.camera = camera;
}
@Override
public void move(float dx, float dy) {
float oldX = getX();
float oldY = getY();
super.move(dx, dy);
camera.translate(getX() - oldX, getY() - oldY);
camera.update();
}
@Override
public void draw(Batch batch) {
super.draw(batch);
}
}
| package wge3.game.entity.creatures;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import static wge3.game.engine.constants.StateFlag.PICKS_UP_ITEMS;
import static wge3.game.engine.constants.Team.PlayerTeam;
public final class Player extends Creature {
private OrthographicCamera camera;
private ShapeRenderer shapeRenderer;
private boolean showHP;
public Player() {
setSprite(4, 3);
team = PlayerTeam;
size = 14;
HP.setMaximum(100);
strength = 10;
defense = 5;
stateFlags.add(PICKS_UP_ITEMS);
System.out.println(stateFlags);
showHP = true;
shapeRenderer = new ShapeRenderer();
}
public void setCamera(OrthographicCamera camera) {
this.camera = camera;
}
@Override
public void move(float dx, float dy) {
float oldX = getX();
float oldY = getY();
super.move(dx, dy);
camera.translate(getX() - oldX, getY() - oldY);
camera.update();
}
@Override
public void draw(Batch batch) {
super.draw(batch);
}
}
|
fix(Build): Stop cssnano from removing needed vendor prefixes.
cssnano was removing `-webkit` properties that were needed to support older versions of iOS. This
commit passes a list of supported browsers to cssnano so that such prefixed properties make it into
the nano-ified CSS. | (function () {
'use strict';
module.exports = function (gulp, plugins, config) {
return function () {
var supported =
['last 10 Chrome versions',
'last 10 Firefox versions',
'Safari >= 9',
'ie >= 9',
'Edge >= 1',
'iOS >= 8',
'Android >= 4.4'];
var source = gulp.src([config.patternsPath + '/**/*.scss', config.templatesPath + '/scss/**/*.scss'])
.pipe(plugins.plumber({ errorHandler: plugins.notify.onError('Error: <%= error.message %>') }))
.pipe(plugins.sourcemaps.init())
.pipe(plugins.sass())
.pipe(plugins.autoprefixer({
browsers: supported
}))
.pipe(plugins.postcss([plugins.postcssFlexibility()]))
;
var max = source.pipe(plugins.clone())
.pipe(plugins.sourcemaps.write('.', { sourceRoot: null }))
.pipe(gulp.dest(config.buildCssPath))
;
var min = source.pipe(plugins.clone())
.pipe(plugins.sourcemaps.init())
.pipe(plugins.rename({ suffix: '.min' }))
.pipe(plugins.postcss([plugins.cssnano({ autoprefixer: { browsers: supported } })]))
.pipe(plugins.size(config.sizeOptions))
.pipe(plugins.sourcemaps.write('.', { sourceRoot: null }))
.pipe(gulp.dest(config.buildCssPath))
.pipe(plugins.browserSync.stream({ match: '**/*.css' }))
;
return plugins.mergeStream(max, min);
};
};
})();
| (function () {
'use strict';
module.exports = function (gulp, plugins, config) {
return function () {
var source = gulp.src([config.patternsPath + '/**/*.scss', config.templatesPath + '/scss/**/*.scss'])
.pipe(plugins.plumber({ errorHandler: plugins.notify.onError('Error: <%= error.message %>') }))
.pipe(plugins.sourcemaps.init())
.pipe(plugins.sass())
.pipe(plugins.autoprefixer({
browsers: ['last 10 Chrome versions',
'last 10 Firefox versions',
'Safari >= 9',
'ie >= 9',
'Edge >= 1',
'iOS >= 8',
'Android >= 4.4']
}))
.pipe(plugins.postcss([plugins.postcssFlexibility()]))
;
var max = source.pipe(plugins.clone())
.pipe(plugins.sourcemaps.write('.', { sourceRoot: null }))
.pipe(gulp.dest(config.buildCssPath))
;
var min = source.pipe(plugins.clone())
.pipe(plugins.sourcemaps.init())
.pipe(plugins.rename({ suffix: '.min' }))
.pipe(plugins.postcss([plugins.cssnano()]))
.pipe(plugins.size(config.sizeOptions))
.pipe(plugins.sourcemaps.write('.', { sourceRoot: null }))
.pipe(gulp.dest(config.buildCssPath))
.pipe(plugins.browserSync.stream({ match: '**/*.css' }))
;
return plugins.mergeStream(max, min);
};
};
})();
|
Add decimal types to Garmin PGRME fields. | # Garmin
from decimal import Decimal
from ... import nmea
class GRM(nmea.ProprietarySentence):
sentence_types = {}
def __new__(_cls, manufacturer, data):
name = manufacturer + data[0]
cls = _cls.sentence_types.get(name, _cls)
return super(GRM, cls).__new__(cls)
def __init__(self, manufacturer, data):
self.sentence_type = manufacturer + data[0]
super(GRM, self).__init__(manufacturer, data[1:])
class GRME(GRM):
""" GARMIN Estimated position error
"""
fields = (
("Estimated Horiz. Position Error", "hpe", Decimal),
("Estimated Horiz. Position Error Unit (M)", "hpe_unit"),
("Estimated Vert. Position Error", "vpe", Decimal),
("Estimated Vert. Position Error Unit (M)", "vpe_unit"),
("Estimated Horiz. Position Error", "osepe", Decimal),
("Overall Spherical Equiv. Position Error", "osepe_unit")
)
class GRMM(GRM):
""" GARMIN Map Datum
"""
fields = (
('Currently Active Datum', 'datum'),
)
class GRMZ(GRM):
""" GARMIN Altitude Information
"""
fields = (
("Altitude", "altitude"),
("Altitude Units (Feet)", "altitude_unit"),
("Positional Fix Dimension (2=user, 3=GPS)", "pos_fix_dim")
)
| # Garmin
from ... import nmea
class GRM(nmea.ProprietarySentence):
sentence_types = {}
def __new__(_cls, manufacturer, data):
name = manufacturer + data[0]
cls = _cls.sentence_types.get(name, _cls)
return super(GRM, cls).__new__(cls)
def __init__(self, manufacturer, data):
self.sentence_type = manufacturer + data[0]
super(GRM, self).__init__(manufacturer, data[1:])
class GRME(GRM):
""" GARMIN Estimated position error
"""
fields = (
("Estimated Horiz. Position Error", "hpe"),
("Estimated Horiz. Position Error Unit (M)", "hpe_unit"),
("Estimated Vert. Position Error", "vpe"),
("Estimated Vert. Position Error Unit (M)", "vpe_unit"),
("Estimated Horiz. Position Error", "osepe"),
("Overall Spherical Equiv. Position Error", "osepe_unit")
)
class GRMM(GRM):
""" GARMIN Map Datum
"""
fields = (
('Currently Active Datum', 'datum'),
)
class GRMZ(GRM):
""" GARMIN Altitude Information
"""
fields = (
("Altitude", "altitude"),
("Altitude Units (Feet)", "altitude_unit"),
("Positional Fix Dimension (2=user, 3=GPS)", "pos_fix_dim")
)
|
Remove l2 from lm_default_config since it is currently unused | lm_default_config = {
### GENERAL
'seed': None,
'verbose': True,
'show_plots': True,
### TRAIN
'train_config': {
# Classifier
# Class balance (if learn_class_balance=False, fix to class_balance)
'learn_class_balance': False,
# Class balance initialization / prior
'class_balance_init': None, # (array) If None, assume uniform
# Model params initialization / priors
'mu_init': 0.4,
# Optimizer
'optimizer_config': {
'optimizer': 'sgd',
'optimizer_common': {
'lr': 0.01,
},
# Optimizer - SGD
'sgd_config': {
'momentum': 0.9,
},
},
# Scheduler
'scheduler_config': {
'scheduler': None,
},
# Checkpointer
'checkpoint': False,
# Train loop
'n_epochs': 100,
'print_every': 10,
},
}
| lm_default_config = {
### GENERAL
'seed': None,
'verbose': True,
'show_plots': True,
### TRAIN
'train_config': {
# Classifier
# Class balance (if learn_class_balance=False, fix to class_balance)
'learn_class_balance': False,
# Class balance initialization / prior
'class_balance_init': None, # (array) If None, assume uniform
# Model params initialization / priors
'mu_init': 0.4,
# L2 regularization (around prior values)
'l2': 0.01,
# Optimizer
'optimizer_config': {
'optimizer': 'sgd',
'optimizer_common': {
'lr': 0.01,
},
# Optimizer - SGD
'sgd_config': {
'momentum': 0.9,
},
},
# Scheduler
'scheduler_config': {
'scheduler': None,
},
# Checkpointer
'checkpoint': False,
# Train loop
'n_epochs': 100,
'print_every': 10,
},
}
|
Fix SerialConnection.close() with invalid device. | from serial import serial_for_url
from .connection import BufferTooShort, Connection, TimeoutError
class SerialConnection(Connection):
__serial = None
def __init__(self, url, timeout=None):
self.__serial = serial_for_url(url, baudrate=19200, timeout=timeout)
def close(self):
if self.__serial:
self.__serial.close()
def recv(self, maxlength=None):
buf = bytearray()
while True:
c = self.__serial.read()
if not c:
raise TimeoutError("Timeout waiting for serial data")
elif c == b"$" or c == b"#":
break
elif maxlength is not None and maxlength <= len(buf):
raise BufferTooShort("Buffer too short for data received")
else:
buf.extend(c)
return bytes(buf)
def send(self, buf, offset=0, size=None):
n = len(buf)
if offset < 0:
raise ValueError("offset is negative")
elif n < offset:
raise ValueError("buffer length < offset")
elif size is None:
size = n - offset
elif size < 0:
raise ValueError("size is negative")
elif offset + size > n:
raise ValueError("buffer length < offset + size")
self.__serial.write(b'"')
self.__serial.write(buf[offset : offset + size])
self.__serial.write(b"$")
self.__serial.flush()
@classmethod
def scan(_):
from serial.tools.list_ports import comports
return ((info.device, info.description) for info in comports())
| from serial import serial_for_url
from .connection import BufferTooShort, Connection, TimeoutError
class SerialConnection(Connection):
def __init__(self, url, timeout=None):
self.__serial = serial_for_url(url, baudrate=19200, timeout=timeout)
def close(self):
self.__serial.close()
def recv(self, maxlength=None):
buf = bytearray()
while True:
c = self.__serial.read()
if not c:
raise TimeoutError("Timeout waiting for serial data")
elif c == b"$" or c == b"#":
break
elif maxlength is not None and maxlength <= len(buf):
raise BufferTooShort("Buffer too short for data received")
else:
buf.extend(c)
return bytes(buf)
def send(self, buf, offset=0, size=None):
n = len(buf)
if offset < 0:
raise ValueError("offset is negative")
elif n < offset:
raise ValueError("buffer length < offset")
elif size is None:
size = n - offset
elif size < 0:
raise ValueError("size is negative")
elif offset + size > n:
raise ValueError("buffer length < offset + size")
self.__serial.write(b'"')
self.__serial.write(buf[offset : offset + size])
self.__serial.write(b"$")
self.__serial.flush()
@classmethod
def scan(_):
from serial.tools.list_ports import comports
return ((info.device, info.description) for info in comports())
|
Update user plugin to use deduped kolibri module. | const KolibriModule = require('kolibri.coreModules.kolibriModule');
const coreActions = require('kolibri.coreVue.vuex.actions');
const router = require('kolibri.coreVue.router');
const Vue = require('kolibri.lib.vue');
const RootVue = require('./vue');
const actions = require('./actions');
const store = require('./state/store');
const PageNames = require('./state/constants').PageNames;
class UserModule extends KolibriModule {
ready() {
const routes = [
{
name: PageNames.SIGN_IN,
path: '/signin',
handler: (toRoute, fromRoute) => {
actions.showSignIn(store);
},
},
{
name: PageNames.SIGN_UP,
path: '/signup',
handler: (toRoute, fromRoute) => {
actions.showSignUp(store);
},
},
{
name: PageNames.PROFILE,
path: '/profile',
handler: (toRoute, fromRoute) => {
actions.showProfile(store);
},
},
{
name: PageNames.SCRATCHPAD,
path: '/scratchpad',
handler: (toRoute, fromRoute) => {
actions.showScratchpad(store);
},
},
{
path: '/',
redirect: '/signin',
},
];
this.rootvue = new Vue({
el: 'rootvue',
render: createElement => createElement(RootVue),
router: router.init(routes),
});
coreActions.getCurrentSession(store);
}
}
module.exports = new UserModule();
| const KolibriModule = require('kolibri_module');
const coreActions = require('kolibri.coreVue.vuex.actions');
const router = require('kolibri.coreVue.router');
const Vue = require('kolibri.lib.vue');
const RootVue = require('./vue');
const actions = require('./actions');
const store = require('./state/store');
const PageNames = require('./state/constants').PageNames;
class UserModule extends KolibriModule {
ready() {
const routes = [
{
name: PageNames.SIGN_IN,
path: '/signin',
handler: (toRoute, fromRoute) => {
actions.showSignIn(store);
},
},
{
name: PageNames.SIGN_UP,
path: '/signup',
handler: (toRoute, fromRoute) => {
actions.showSignUp(store);
},
},
{
name: PageNames.PROFILE,
path: '/profile',
handler: (toRoute, fromRoute) => {
actions.showProfile(store);
},
},
{
name: PageNames.SCRATCHPAD,
path: '/scratchpad',
handler: (toRoute, fromRoute) => {
actions.showScratchpad(store);
},
},
{
path: '/',
redirect: '/signin',
},
];
this.rootvue = new Vue({
el: 'rootvue',
render: createElement => createElement(RootVue),
router: router.init(routes),
});
coreActions.getCurrentSession(store);
}
}
module.exports = new UserModule();
|
Remove warning about lizmap_search
Quick fix FTW! | <?php
/**
* Lizmap FTS searcher.
*
* @author 3liz
* @copyright 2017 3liz
*
* @see http://3liz.com
*
* @license Mozilla Public License : http://www.mozilla.org/MPL/
*/
class lizmapFtsSearchListener extends jEventListener
{
public function onsearchServiceItem($event)
{
// Check if needed table lizmap_fts is queryable
if ($this->checkLizmapFts()) {
$event->add(
array(
'type' => 'Fts',
'service' => 'lizmapFts',
'url' => jUrl::get('lizmap~searchFts:get'),
)
);
}
}
protected function checkLizmapFts()
{
$ok = false;
$profile = 'search';
try {
// try to get the specific search profile to do not rebuild it
jProfiles::get('jdb', $profile, true);
} catch (Exception $e) {
// else use default
$profile = null;
}
// Try to get data from lizmap_fts table / view / materialized view
try {
// try to get the specific search profile to do not rebuild it
$cnx = jDb::getConnection($profile);
@$cnx->query('SELECT * FROM lizmap_search LIMIT 0;');
$ok = true;
} catch (Exception $e) {
$ok = false;
}
return $ok;
}
}
| <?php
/**
* Lizmap FTS searcher.
*
* @author 3liz
* @copyright 2017 3liz
*
* @see http://3liz.com
*
* @license Mozilla Public License : http://www.mozilla.org/MPL/
*/
class lizmapFtsSearchListener extends jEventListener
{
public function onsearchServiceItem($event)
{
// Check if needed table lizmap_fts is queryable
if ($this->checkLizmapFts()) {
$event->add(
array(
'type' => 'Fts',
'service' => 'lizmapFts',
'url' => jUrl::get('lizmap~searchFts:get'),
)
);
}
}
protected function checkLizmapFts()
{
$ok = false;
$profile = 'search';
try {
// try to get the specific search profile to do not rebuild it
jProfiles::get('jdb', $profile, true);
} catch (Exception $e) {
// else use default
$profile = null;
}
// Try to get data from lizmap_fts table / view / materialized view
try {
// try to get the specific search profile to do not rebuild it
$cnx = jDb::getConnection($profile);
$cnx->query('SELECT * FROM lizmap_search LIMIT 0;');
$ok = true;
} catch (Exception $e) {
$ok = false;
}
return $ok;
}
}
|
Remove redundant array check found by Psalm | <?php
/*
* This file is a part of dflydev/dot-access-data.
*
* (c) Dragonfly Development Inc.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Dflydev\DotAccessData;
class Util
{
/**
* Test if array is an associative array
*
* Note that this function will return true if an array is empty. Meaning
* empty arrays will be treated as if they are associative arrays.
*
* @param array $arr
*
* @return boolean
*/
public static function isAssoc(array $arr)
{
return !count($arr) || count(array_filter(array_keys($arr),'is_string')) == count($arr);
}
/**
* Merge contents from one associtative array to another
*
* @param array $to
* @param array $from
* @param bool $clobber
*/
public static function mergeAssocArray($to, $from, $clobber = true)
{
if ( is_array($from) ) {
foreach ($from as $k => $v) {
if (!isset($to[$k])) {
$to[$k] = $v;
} else {
$to[$k] = self::mergeAssocArray($to[$k], $v, $clobber);
}
}
return $to;
}
return $clobber ? $from : $to;
}
}
| <?php
/*
* This file is a part of dflydev/dot-access-data.
*
* (c) Dragonfly Development Inc.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Dflydev\DotAccessData;
class Util
{
/**
* Test if array is an associative array
*
* Note that this function will return true if an array is empty. Meaning
* empty arrays will be treated as if they are associative arrays.
*
* @param array $arr
*
* @return boolean
*/
public static function isAssoc(array $arr)
{
return (is_array($arr) && (!count($arr) || count(array_filter(array_keys($arr),'is_string')) == count($arr)));
}
/**
* Merge contents from one associtative array to another
*
* @param array $to
* @param array $from
* @param bool $clobber
*/
public static function mergeAssocArray($to, $from, $clobber = true)
{
if ( is_array($from) ) {
foreach ($from as $k => $v) {
if (!isset($to[$k])) {
$to[$k] = $v;
} else {
$to[$k] = self::mergeAssocArray($to[$k], $v, $clobber);
}
}
return $to;
}
return $clobber ? $from : $to;
}
}
|
Fix migration rollback for ban_reason_improvements - is_default still exists | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class BanReasonImprovements extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('mship_note_type', function(Blueprint $table) {
$table->string('short_code', 20)->nullable()->after("name");
$table->boolean("is_default")->default(0)->after("is_system");
});
DB::table("mship_note_type")->insert([
["name" => "Discipline", "short_code" => "discipline", "is_available" => 1, "is_system" => 1, "colour_code" => "danger", "created_at" => \Carbon\Carbon::now(), "updated_at" => \Carbon\Carbon::now()],
]);
DB::table("mship_note_type")->where("name", "=", "System Generated")->update(["short_code" => "system", "is_default" => true]);
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
DB::table("mship_note_type")->where("short_code", "=", "discipline")->delete();
Schema::table('mship_note_type', function(Blueprint $table) {
$table->dropColumn("short_code");
$table->dropColumn('is_default');
});
}
}
| <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class BanReasonImprovements extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('mship_note_type', function(Blueprint $table) {
$table->string('short_code', 20)->nullable()->after("name");
$table->boolean("is_default")->default(0)->after("is_system");
});
DB::table("mship_note_type")->insert([
["name" => "Discipline", "short_code" => "discipline", "is_available" => 1, "is_system" => 1, "colour_code" => "danger", "created_at" => \Carbon\Carbon::now(), "updated_at" => \Carbon\Carbon::now()],
]);
DB::table("mship_note_type")->where("name", "=", "System Generated")->update(["short_code" => "system", "is_default" => true]);
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
DB::table("mship_note_type")->where("short_code", "=", "discipline")->delete();
Schema::table('mship_note_type', function(Blueprint $table) {
$table->dropColumn("short_code");
});
}
}
|
Add the GitHub issue number as a new line in the commitMessage field. | # -*- coding: utf-8 -*-
from AbstractVisitor import AbstractVisitor
from duralex.alinea_parser import *
from github import Github
class AddGitHubIssueVisitor(AbstractVisitor):
def __init__(self, args):
self.github = Github(args.github_token)
self.repo = self.github.get_repo(args.github_repository)
self.issues = list(self.repo.get_issues())
self.current_issue = -1
super(AddGitHubIssueVisitor, self).__init__()
def visit_edit_node(self, node, post):
if post:
return
if 'commitMessage' not in node:
node['commitMessage'] = '(#' + str(self.current_issue) + ')'
else:
node['commitMessage'] = node['commitMessage'] + '\nGitHub: #' + str(self.current_issue)
def visit_node(self, node):
if 'type' in node and node['type'] == 'article':
title = 'Article ' + str(node['order'])
body = node['content']
found = False
for issue in self.issues:
if issue.title == title:
found = True
node['githubIssue'] = issue.html_url
self.current_issue = issue.number
if issue.body != body:
issue.edit(title=title, body=body)
if not found:
issue = self.repo.create_issue(title=title, body=body)
self.current_issue = issue.number
super(AddGitHubIssueVisitor, self).visit_node(node)
| # -*- coding: utf-8 -*-
from AbstractVisitor import AbstractVisitor
from duralex.alinea_parser import *
from github import Github
class AddGitHubIssueVisitor(AbstractVisitor):
def __init__(self, args):
self.github = Github(args.github_token)
self.repo = self.github.get_repo(args.github_repository)
self.issues = list(self.repo.get_issues())
self.current_issue = -1
super(AddGitHubIssueVisitor, self).__init__()
def visit_edit_node(self, node, post):
if post:
return
if 'commitMessage' not in node:
node['commitMessage'] = '(#' + str(self.current_issue) + ')'
else:
node['commitMessage'] = node['commitMessage'] + ' (#' + str(self.current_issue) + ')'
def visit_node(self, node):
if 'type' in node and node['type'] == 'article':
title = 'Article ' + str(node['order'])
body = node['content']
found = False
for issue in self.issues:
if issue.title == title:
found = True
node['githubIssue'] = issue.html_url
self.current_issue = issue.number
if issue.body != body:
issue.edit(title=title, body=body)
if not found:
issue = self.repo.create_issue(title=title, body=body)
self.current_issue = issue.number
super(AddGitHubIssueVisitor, self).visit_node(node)
|
Add broadcasting of login event for non-github login | angular.module('codebrag.auth')
.factory('authService', function($http, httpRequestsBuffer, $q, $rootScope, events) {
var authService = {
loggedInUser: undefined,
login: function(user) {
var loginRequest = $http.post('rest/users', user, {bypassQueue: true});
return loginRequest.then(function(response) {
authService.loggedInUser = response.data;
$rootScope.$broadcast(events.loggedIn);
httpRequestsBuffer.retryAllRequest();
});
},
logout: function() {
var logoutRequest = $http.get('rest/users/logout');
return logoutRequest.then(function() {
authService.loggedInUser = undefined;
})
},
isAuthenticated: function() {
return !angular.isUndefined(authService.loggedInUser);
},
isNotAuthenticated: function() {
return !authService.isAuthenticated();
},
requestCurrentUser: function() {
if (authService.isAuthenticated()) {
return $q.when(authService.loggedInUser);
}
var promise = $http.get('rest/users');
return promise.then(function(response) {
authService.loggedInUser = response.data;
$rootScope.$broadcast(events.loggedIn);
return $q.when(authService.loggedInUser);
});
}
};
return authService;
}); | angular.module('codebrag.auth')
.factory('authService', function($http, httpRequestsBuffer, $q, $rootScope, events) {
var authService = {
loggedInUser: undefined,
login: function(user) {
var loginRequest = $http.post('rest/users', user, {bypassQueue: true});
return loginRequest.then(function(response) {
authService.loggedInUser = response.data;
httpRequestsBuffer.retryAllRequest();
});
},
logout: function() {
var logoutRequest = $http.get('rest/users/logout');
return logoutRequest.then(function() {
authService.loggedInUser = undefined;
})
},
isAuthenticated: function() {
return !angular.isUndefined(authService.loggedInUser);
},
isNotAuthenticated: function() {
return !authService.isAuthenticated();
},
requestCurrentUser: function() {
if (authService.isAuthenticated()) {
return $q.when(authService.loggedInUser);
}
var promise = $http.get('rest/users');
return promise.then(function(response) {
authService.loggedInUser = response.data;
$rootScope.$broadcast(events.loggedIn);
return $q.when(authService.loggedInUser);
});
}
};
return authService;
}); |
Use random_element instead of random.choice | # -*- coding: utf-8 -*-
from faker.providers import BaseProvider
from .mimetypes import mime_types
class WebProvider(BaseProvider):
"""
A Provider for web-related test data.
>>> from faker import Faker
>>> from faker_web import WebProvider
>>> fake = Faker()
>>> fake.add_provider(WebProvider)
"""
all_mime_types = mime_types
popular_mime_types = {
'application/javascript': ['js'],
'application/json': ['json'],
'application/pdf': ['pdf'],
'image/jpeg': ['jpeg', 'jpg', 'jpe'],
'image/gif': ['gif'],
'image/png': ['png'],
'image/svg+xml': ['svg', 'svgz'],
'text/css': ['css'],
'text/html': ['html', 'htm'],
'text/plain': ['txt', 'text', 'conf', 'def', 'list', 'log', 'in'],
}
def mime_type(self):
"""
Returns a mime-type from the list of types understood by the Apache
http server.
>>> fake.mime_type()
application/mxf
:return: content-type/mime-type
:rtype: str
"""
return self.random_element(self.all_mime_types.keys())
def mime_type_popular(self):
"""
Returns a popular mime-type.
>>> fake.mime_type_popular()
text/html
:return: content-type/mime-type
:rtype: str
"""
return self.random_element(self.popular_mime_types.keys())
| # -*- coding: utf-8 -*-
from random import choice
from faker.providers import BaseProvider
from .mimetypes import mime_types
class WebProvider(BaseProvider):
"""
A Provider for web-related test data.
>>> from faker import Faker
>>> from faker_web import WebProvider
>>> fake = Faker()
>>> fake.add_provider(WebProvider)
"""
all_content = mime_types
popular_content = {
'application/javascript': ['js'],
'application/json': ['json'],
'application/pdf': ['pdf'],
'image/jpeg': ['jpeg', 'jpg', 'jpe'],
'image/gif': ['gif'],
'image/png': ['png'],
'image/svg+xml': ['svg', 'svgz'],
'text/css': ['css'],
'text/html': ['html', 'htm'],
'text/plain': ['txt', 'text', 'conf', 'def', 'list', 'log', 'in'],
}
def mime_type(self):
"""
Returns a mime-type from the list of types understood by the Apache
http server.
>>> fake.mime_type()
application/mxf
:return: content-type/mime-type
:rtype: str
"""
return choice(list(self.all_content.keys()))
def mime_type_popular(self):
"""
Returns a popular mime-type.
>>> fake.mime_type_popular()
text/html
:return: content-type/mime-type
:rtype: str
"""
return choice(list(self.popular_content.keys()))
|
Add JSONP notice to API | from flask import jsonify, request
from functools import wraps
import json
jsonp_notice = """
// MediaCrush supports Cross Origin Resource Sharing requests.
// There is no reason to use JSONP; please use CORS instead.
// For more information, see https://mediacru.sh/docs/api"""
def json_output(f):
@wraps(f)
def wrapper(*args, **kwargs):
def jsonify_wrap(obj):
callback = request.args.get('callback', False)
jsonification = jsonify(obj)
if callback:
jsonification.data = "%s(%s);\n%s" % (callback, jsonification.data, jsonp_notice) # Alter the response
return jsonification
result = f(*args, **kwargs)
if isinstance(result, tuple):
return jsonify_wrap(result[0]), result[1]
return jsonify_wrap(result)
return wrapper
def cors(f):
@wraps(f)
def wrapper(*args, **kwargs):
res = f(*args, **kwargs)
if request.headers.get('x-cors-status', False):
if isinstance(res, tuple):
json_text = res[0].data
code = res[1]
else:
json_text = res.data
code = 200
o = json.loads(json_text)
o['x-status'] = code
return jsonify(o)
return res
return wrapper
| from flask import jsonify, request
from functools import wraps
import json
def json_output(f):
@wraps(f)
def wrapper(*args, **kwargs):
def jsonify_wrap(obj):
callback = request.args.get('callback', False)
jsonification = jsonify(obj)
if callback:
jsonification.data = "%s(%s);" % (callback, jsonification.data) # Alter the response
return jsonification
result = f(*args, **kwargs)
if isinstance(result, tuple):
return jsonify_wrap(result[0]), result[1]
return jsonify_wrap(result)
return wrapper
def cors(f):
@wraps(f)
def wrapper(*args, **kwargs):
res = f(*args, **kwargs)
if request.headers.get('x-cors-status', False):
if isinstance(res, tuple):
json_text = res[0].data
code = res[1]
else:
json_text = res.data
code = 200
o = json.loads(json_text)
o['x-status'] = code
return jsonify(o)
return res
return wrapper
|
Update the zip task to dist and correct api task | 'use strict';
module.exports = function (grunt) {
// Load the project's grunt tasks from a directory
require('grunt-config-dir')(grunt, {
configDir: require('path').resolve('tasks')
});
/*
* Register group tasks
*/
//npm install
grunt.registerTask('npm_install', 'install dependencies', function() {
var exec = require('child_process').exec;
var cb = this.async();
exec('npm install', {cwd: './'}, function(err, stdout) {
console.log(stdout);
cb();
});
});
grunt.registerTask('open_coverage', 'open coverage report in default browser', function() {
var exec = require('child_process').exec;
var cb = this.async();
exec('open coverage/lcov-report/index.html', {cwd: './'}, function(err, stdout) {
console.log(stdout);
cb();
});
});
grunt.registerTask('clean_all', [ 'clean:node_modules', 'clean:coverage', 'npm_install' ]);
grunt.registerTask('test', ['env:test', 'clean:coverage', 'jshint', 'mocha_istanbul']);
grunt.registerTask('coverage', ['test', 'open_coverage']);
grunt.registerTask('dist', ['compress:hmda-edit-check-api']);
grunt.registerTask('serve', ['env:sandbox', 'jshint','develop','watch']);
};
| 'use strict';
module.exports = function (grunt) {
// Load the project's grunt tasks from a directory
require('grunt-config-dir')(grunt, {
configDir: require('path').resolve('tasks')
});
/*
* Register group tasks
*/
//npm install
grunt.registerTask('npm_install', 'install dependencies', function() {
var exec = require('child_process').exec;
var cb = this.async();
exec('npm install', {cwd: './'}, function(err, stdout) {
console.log(stdout);
cb();
});
});
grunt.registerTask('open_coverage', 'open coverage report in default browser', function() {
var exec = require('child_process').exec;
var cb = this.async();
exec('open coverage/lcov-report/index.html', {cwd: './'}, function(err, stdout) {
console.log(stdout);
cb();
});
});
grunt.registerTask('clean_all', [ 'clean:node_modules', 'clean:coverage', 'npm_install' ]);
grunt.registerTask('test', ['env:test', 'clean:coverage', 'jshint', 'mocha_istanbul']);
grunt.registerTask('coverage', ['test', 'open_coverage']);
grunt.registerTask('zip', ['compress:icd10-api']);
grunt.registerTask('serve', ['env:sandbox', 'jshint','develop','watch']);
};
|
Update enum value to an is-instance check | from __future__ import absolute_import
from enum import Enum
from typing import TypeVar, Optional, Any, Type # noqa
from odin.exceptions import ValidationError
from . import Field
__all__ = ("EnumField",)
ET = TypeVar("ET", Enum, Enum)
class EnumField(Field):
"""
Field for handling Python enums.
"""
data_type_name = "Enum"
def __init__(self, enum, **options):
# type: (Type[ET], **Any) -> None
# Generate choices structure from choices
choices = options.pop("choices", None)
options["choices"] = tuple((e, e.name) for e in choices or enum)
super(EnumField, self).__init__(**options)
self.enum = enum
@property
def choices_doc_text(self):
"""
Choices converted for documentation purposes.
"""
return tuple((v.value, n) for v, n in self.choices)
def to_python(self, value):
# type: (Any) -> Optional[ET]
if value is None:
return
# Attempt to convert
try:
return self.enum(value)
except ValueError:
# If value is an empty string return None
# Do this check here to support enums that define an option using
# an empty string.
if value == "":
return
raise ValidationError(self.error_messages["invalid_choice"] % value)
def prepare(self, value):
# type: (Optional[ET]) -> Any
if (value is not None) and isinstance(value, self.enum):
return value.value
| from __future__ import absolute_import
from enum import Enum
from typing import TypeVar, Optional, Any, Type # noqa
from odin.exceptions import ValidationError
from . import Field
__all__ = ("EnumField",)
ET = TypeVar("ET", Enum, Enum)
class EnumField(Field):
"""
Field for handling Python enums.
"""
data_type_name = "Enum"
def __init__(self, enum, **options):
# type: (Type[ET], **Any) -> None
# Generate choices structure from choices
choices = options.pop("choices", None)
options["choices"] = tuple((e, e.name) for e in choices or enum)
super(EnumField, self).__init__(**options)
self.enum = enum
@property
def choices_doc_text(self):
"""
Choices converted for documentation purposes.
"""
return tuple((v.value, n) for v, n in self.choices)
def to_python(self, value):
# type: (Any) -> Optional[ET]
if value is None:
return
# Attempt to convert
try:
return self.enum(value)
except ValueError:
# If value is an empty string return None
# Do this check here to support enums that define an option using
# an empty string.
if value == "":
return
raise ValidationError(self.error_messages["invalid_choice"] % value)
def prepare(self, value):
# type: (Optional[ET]) -> Any
if (value is not None) and (value in self.enum):
return value.value
|
Move ViewExceptionMapper to an ExtendedExceptionMapper | package io.dropwizard.views;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.glassfish.jersey.spi.ExtendedExceptionMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* An {@link ExtendedExceptionMapper} that returns a 500 error response with a generic
* HTML error page when a {@link ViewRenderException} is the cause.
*
* @since 1.1.0
*/
@Provider
public class ViewRenderExceptionMapper implements ExtendedExceptionMapper<WebApplicationException> {
private static final Logger LOGGER = LoggerFactory.getLogger(ViewRenderExceptionMapper.class);
/**
* The generic HTML error page template.
*/
public static final String TEMPLATE_ERROR_MSG =
"<html>" +
"<head><title>Template Error</title></head>" +
"<body><h1>Template Error</h1><p>Something went wrong rendering the page</p></body>" +
"</html>";
@Override
public Response toResponse(WebApplicationException exception) {
LOGGER.error("Template Error", exception);
return Response.serverError()
.type(MediaType.TEXT_HTML_TYPE)
.entity(TEMPLATE_ERROR_MSG)
.build();
}
@Override
public boolean isMappable(WebApplicationException e) {
return ExceptionUtils.indexOfThrowable(e, ViewRenderException.class) != -1;
}
}
| package io.dropwizard.views;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* An {@link ExceptionMapper} that returns a 500 error response with a generic
* HTML error page when a {@link ViewRenderException} is thrown.
*
* @since 1.1.0
*/
@Provider
public class ViewRenderExceptionMapper implements ExceptionMapper<WebApplicationException> {
private static final Logger LOGGER = LoggerFactory.getLogger(ViewRenderExceptionMapper.class);
/**
* The generic HTML error page template.
*/
public static final String TEMPLATE_ERROR_MSG =
"<html>" +
"<head><title>Template Error</title></head>" +
"<body><h1>Template Error</h1><p>Something went wrong rendering the page</p></body>" +
"</html>";
@Override
public Response toResponse(WebApplicationException exception) {
Throwable cause = exception.getCause();
if (cause instanceof ViewRenderException) {
LOGGER.error("Template Error", cause);
return Response.serverError()
.type(MediaType.TEXT_HTML_TYPE)
.entity(TEMPLATE_ERROR_MSG)
.build();
}
return exception.getResponse();
}
}
|
Fix a bad call to "writeInfo()" in "bin/phd stop" with no PHABRICATOR_INSTANCE defined
Summary: See <https://discourse.phabricator-community.org/t/phd-status-calls-to-undefined-method-when-theres-no-instance/2918>. This call should be `logInfo()`.
Test Plan:
- Purged `PHABRICATOR_INSTANCE` from my environment. In a Phacility development environment, it comes from loading `services/`.
- Ran `bin/phd stop` with all daemons already stopped.
- Before: bad call.
- After: helpful error.
- Ran some other `bin/phd start`, `bin/phd status`, etc., to kick the tires.
- Grepped for remaining `writeInfo()` calls (found none).
Reviewers: amckinley
Reviewed By: amckinley
Differential Revision: https://secure.phabricator.com/D20649 | <?php
final class PhabricatorDaemonManagementStatusWorkflow
extends PhabricatorDaemonManagementWorkflow {
protected function didConstruct() {
$this
->setName('status')
->setSynopsis(pht('Show daemon processes on this host.'));
}
public function execute(PhutilArgumentParser $args) {
$process_refs = $this->getOverseerProcessRefs();
if (!$process_refs) {
$instance = $this->getInstance();
if ($instance !== null) {
$this->logInfo(
pht('NO DAEMONS'),
pht(
'There are no running daemon processes for the current '.
'instance ("%s").',
$instance));
} else {
$this->logInfo(
pht('NO DAEMONS'),
pht('There are no running daemon processes.'));
}
return 1;
}
$table = id(new PhutilConsoleTable())
->addColumns(
array(
'pid' => array(
'title' => pht('PID'),
),
'command' => array(
'title' => pht('Command'),
),
));
foreach ($process_refs as $process_ref) {
$table->addRow(
array(
'pid' => $process_ref->getPID(),
'command' => $process_ref->getCommand(),
));
}
$table->draw();
return 0;
}
}
| <?php
final class PhabricatorDaemonManagementStatusWorkflow
extends PhabricatorDaemonManagementWorkflow {
protected function didConstruct() {
$this
->setName('status')
->setSynopsis(pht('Show daemon processes on this host.'));
}
public function execute(PhutilArgumentParser $args) {
$process_refs = $this->getOverseerProcessRefs();
if (!$process_refs) {
$instance = $this->getInstance();
if ($instance !== null) {
$this->logInfo(
pht('NO DAEMONS'),
pht(
'There are no running daemon processes for the current '.
'instance ("%s").',
$instance));
} else {
$this->writeInfo(
pht('NO DAEMONS'),
pht('There are no running daemon processes.'));
}
return 1;
}
$table = id(new PhutilConsoleTable())
->addColumns(
array(
'pid' => array(
'title' => pht('PID'),
),
'command' => array(
'title' => pht('Command'),
),
));
foreach ($process_refs as $process_ref) {
$table->addRow(
array(
'pid' => $process_ref->getPID(),
'command' => $process_ref->getCommand(),
));
}
$table->draw();
return 0;
}
}
|
Fix typo in SeedMixin.tearDownClass name | # -*- coding: utf-8 -*-
"""
sqlalchemy_seed.seed_mixin
~~~~~~~~~~~~~~~~~~~~~~~~~~
Mixin class for unittest.
:copyright: (c) 2017 Shinya Ohyanagi, All rights reserved.
:license: BSD, see LICENSE for more details.
"""
from . import (
create_table,
drop_table,
load_fixture_files,
load_fixtures,
)
class SeedMixin(object):
base = None
session = None
fixtures = []
fixtures_setup_class = False
fixtures_paths = None
def _create_fixtures(self):
if self.base is None:
return
if self.session is None:
return
if self.fixtures_paths is None:
return
create_table(self.base, self.session)
fixtures = load_fixture_files(self.fixtures_paths, self.fixtures)
load_fixtures(self.session, fixtures)
def _drop_fixtures(self):
drop_table(self.base, self.session)
@classmethod
def setUpClass(cls):
if cls.fixtures_setup_class is True:
cls._create_fixtures(cls)
@classmethod
def tearDownClass(cls):
if cls.fixtures_setup_class is True:
cls._drop_fixtures(cls)
def setUp(self):
if self.fixtures_setup_class is True:
return
self._create_fixtures()
def tearDown(self):
if self.fixtures_setup_class is True:
return
self._drop_fixtures()
| # -*- coding: utf-8 -*-
"""
sqlalchemy_seed.seed_mixin
~~~~~~~~~~~~~~~~~~~~~~~~~~
Mixin class for unittest.
:copyright: (c) 2017 Shinya Ohyanagi, All rights reserved.
:license: BSD, see LICENSE for more details.
"""
from . import (
create_table,
drop_table,
load_fixture_files,
load_fixtures,
)
class SeedMixin(object):
base = None
session = None
fixtures = []
fixtures_setup_class = False
fixtures_paths = None
def _create_fixtures(self):
if self.base is None:
return
if self.session is None:
return
if self.fixtures_paths is None:
return
create_table(self.base, self.session)
fixtures = load_fixture_files(self.fixtures_paths, self.fixtures)
load_fixtures(self.session, fixtures)
def _drop_fixtures(self):
drop_table(self.base, self.session)
@classmethod
def setUpClass(cls):
if cls.fixtures_setup_class is True:
cls._create_fixtures(cls)
@classmethod
def teatDownClass(cls):
if cls.fixtures_setup_class is True:
cls._drop_fixtures(cls)
def setUp(self):
if self.fixtures_setup_class is True:
return
self._create_fixtures()
def tearDown(self):
if self.fixtures_setup_class is True:
return
self._drop_fixtures()
|
Fix crash on game creation | import Queue
import json
import EBQP
from . import world
from . import types
from . import consts
class GameRequestHandler:
def __init__(self):
self.world = None
self.responses = {
EBQP.new: self.respond_new,
}
def process(self, request):
request_pieces = request.split(EBQP.packet_delimiter, 1)
command = request_pieces[0]
params = request_pieces[1].strip() if len(request_pieces) > 1 else ''
try:
json_args = json.loads(params)
except Exception as e:
return "process:failure:bad json"
if command in self.responses:
return self.responses[command](json_args)
else:
return "process:failure:unsupported command"
def respond_new(self, args):
uids = args['uids']
self.world = world.World(uids)
self.world.add_unit(uids[0], types.new_unit('Tank', consts.RED))
self.responses = {
EBQP.view: self.respond_view,
EBQP.move: self.respond_move,
}
return 'new:success'
def respond_view(self, args):
return 'view:success:%s' % self.world.to_json()
#TODO
def respond_move(self, args):
return 'move:failure:unimplemented'
| import Queue
import json
import EBQP
from . import world
from . import types
from . import consts
class GameRequestHandler:
def __init__(self):
self.world = None
self.responses = {
EBQP.new: self.respond_new,
}
def process(self, request):
request_pieces = request.split(EBQP.packet_delimiter, 1)
command = request_pieces[0]
params = request_pieces[1].strip() if len(request_pieces) > 1 else ''
try:
json_args = json.loads(params)
except Exception as e:
return "process:failure:bad json"
if command in self.responses:
return self.responses[command](json_args)
else:
return "process:failure:unsupported command"
def respond_new(self, args):
uids = args['uids']
self.world = world.World(uids)
self.world.add_unit(uid1, types.new_unit('Tank', consts.RED))
self.responses = {
EBQP.view: self.respond_view,
EBQP.move: self.respond_move,
}
return 'new:success'
def respond_view(self, args):
return 'view:success:%s' % self.world.to_json()
#TODO
def respond_move(self, args):
return 'move:failure:unimplemented'
|
fix: Create tmp dir inside homedir | const chalk = require('chalk');
const fs = require('mz/fs');
const run = require('./run');
const homedir = require('os').homedir();
async function importFromGit({
db,
repo,
branch = 'master',
tmpDir = `${homedir}/__tmp-mongo-git-backup`,
checkout,
}) {
console.log(chalk.yellow('Starting mongodb import'));
console.log(chalk.cyan('Cleaning up (in case of errors)'));
await run(`rm -rf ${tmpDir}`);
console.log(chalk.cyan('Cloning backup repository'));
try {
await run(`eval \`ssh-agent -s\` &&
ssh-add ~/.ssh/id_rsa`);
} catch (e) {} // eslint-disable-line no-empty
console.log(await run(`
git clone -b ${branch} ${repo} ${tmpDir} &&
cd ${tmpDir} ${checkout ? `&& git checkout ${checkout}` : ''}
`));
const fileNames = await fs.readdir(tmpDir);
for (const fileName of fileNames.filter(f => /\.json$/.test(f))) {
const [collection] = fileName.split('.');
console.log(checkout);
console.log(await run(`
cd ${tmpDir} &&
mongoimport --db ${db} --file ${fileName} --collection ${collection} --mode upsert
`));
}
console.log(chalk.cyan(`Applied changes to "${db}" database`));
console.log(chalk.cyan('Cleaning up'));
await run(`rm -rf ${tmpDir}`);
console.log(chalk.green('Done!'));
}
module.exports = importFromGit;
| const chalk = require('chalk');
const fs = require('mz/fs');
const run = require('./run');
async function importFromGit({
db,
repo,
branch = 'master',
tmpDir = `${__dirname}/__tmp`,
checkout,
}) {
console.log(chalk.yellow('Starting mongodb import'));
console.log(chalk.cyan('Cleaning up (in case of errors)'));
await run(`rm -rf ${tmpDir}`);
console.log(chalk.cyan('Cloning backup repository'));
try {
await run(`eval \`ssh-agent -s\` &&
ssh-add ~/.ssh/id_rsa`);
} catch (e) {} // eslint-disable-line no-empty
console.log(await run(`
git clone -b ${branch} ${repo} ${tmpDir} &&
cd ${tmpDir} ${checkout ? `&& git checkout ${checkout}` : ''}
`));
const fileNames = await fs.readdir(tmpDir);
for (const fileName of fileNames.filter(f => /\.json$/.test(f))) {
const [collection] = fileName.split('.');
console.log(checkout);
console.log(await run(`
cd ${tmpDir} &&
mongoimport --db ${db} --file ${fileName} --collection ${collection} --mode upsert
`));
}
console.log(chalk.cyan(`Applied changes to "${db}" database`));
console.log(chalk.cyan('Cleaning up'));
await run(`rm -rf ${tmpDir}`);
console.log(chalk.green('Done!'));
}
module.exports = importFromGit;
|
Fix optional duration for connection accesses | const { DataTypes } = require('sequelize');
module.exports = function (sequelize) {
const ConnectionAccesses = sequelize.define(
'ConnectionAccesses',
{
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
connectionId: {
type: DataTypes.STRING,
allowNull: false,
},
connectionName: {
type: DataTypes.STRING,
allowNull: false,
},
userId: {
type: DataTypes.STRING,
allowNull: false,
},
userEmail: {
type: DataTypes.STRING,
allowNull: false,
},
// Number of seconds connection access is valid from creation
// Used to set expiryDate
duration: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 0,
validate: {
min: 0,
max: 86400,
},
},
expiryDate: {
type: DataTypes.DATE,
allowNull: false,
},
createdAt: {
type: DataTypes.DATE,
allowNull: false,
},
updatedAt: {
type: DataTypes.DATE,
allowNull: false,
},
},
{
tableName: 'connection_accesses',
underscored: true,
}
);
return ConnectionAccesses;
};
| const { DataTypes } = require('sequelize');
module.exports = function (sequelize) {
const ConnectionAccesses = sequelize.define(
'ConnectionAccesses',
{
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
connectionId: {
type: DataTypes.STRING,
allowNull: false,
},
connectionName: {
type: DataTypes.STRING,
allowNull: false,
},
userId: {
type: DataTypes.STRING,
allowNull: false,
},
userEmail: {
type: DataTypes.STRING,
allowNull: false,
},
duration: {
type: DataTypes.INTEGER,
allowNull: false,
validate: {
min: 0,
max: 86400,
},
},
expiryDate: {
type: DataTypes.DATE,
allowNull: false,
},
createdAt: {
type: DataTypes.DATE,
allowNull: false,
},
updatedAt: {
type: DataTypes.DATE,
allowNull: false,
},
},
{
tableName: 'connection_accesses',
underscored: true,
}
);
return ConnectionAccesses;
};
|
Allow specification of GALAPAGOS bands | # coding: utf-8
def galapagos_to_pandas(in_filename='/home/ppzsb1/quickdata/GAMA_9_all_combined_gama_only_bd6.fits',
out_filename=None, bands='RUGIZYJHK'):
"""Convert a GALAPAGOS multi-band catalogue to a pandas-compatible HDF5 file"""
from astropy.io import fits
import pandas as pd
import re
import tempfile
if out_filename is None:
out_filename = re.sub('.fits$', '', in_filename)+'.h5'
data = fits.getdata(in_filename, 1)
with tempfile.NamedTemporaryFile() as tmp:
with pd.get_store(tmp.name, mode='w') as tmpstore:
for n in data.names:
d = data[n]
if len(d.shape) == 1:
new_cols = pd.DataFrame(d, columns=[n])
else:
new_cols = pd.DataFrame(d, columns=['{}_{}'.format(n,b) for b in bands])
tmpstore[n] = new_cols
with pd.get_store(out_filename, mode='w', complib='blosc', complevel=5) as store:
# Use format='table' on next line to save as a pytables table
store.put('data', pd.concat([tmpstore[n] for n in data.names], axis=1))
return pd.HDFStore(out_filename)
| # coding: utf-8
def galapagos_to_pandas(in_filename='/home/ppzsb1/quickdata/GAMA_9_all_combined_gama_only_bd6.fits',
out_filename=None):
"""Convert a GALAPAGOS multi-band catalogue to a pandas-compatible HDF5 file"""
from astropy.io import fits
import pandas as pd
import re
import tempfile
if out_filename is None:
out_filename = re.sub('.fits$', '', in_filename)+'.h5'
data = fits.getdata(in_filename, 1)
with tempfile.NamedTemporaryFile() as tmp:
with pd.get_store(tmp.name, mode='w') as tmpstore:
for n in data.names:
d = data[n]
if len(d.shape) == 1:
new_cols = pd.DataFrame(d, columns=[n])
else:
new_cols = pd.DataFrame(d, columns=['{}_{}'.format(n,b) for b in 'RUGIZYJHK'])
tmpstore[n] = new_cols
with pd.get_store(out_filename, mode='w', complib='blosc', complevel=5) as store:
# Use format='table' on next line to save as a pytables table
store.put('data', pd.concat([tmpstore[n] for n in data.names], axis=1))
return pd.HDFStore(out_filename)
|
indexes: Fix acceptance test for MongoDB 2.0
There were some minor changes for the test to work properly
with 2.0:
- The index versions are now 1 instead of 0
Don't bother checking the version of index since scalymongo has no
control over it.
- The `unique` key is now only provided when ``True`` | from tests.acceptance.base_acceptance_test import BaseAcceptanceTest
from scalymongo import Document
class IndexTestDocument(Document):
structure = {
'number': int,
'name': unicode,
'descending': int,
'ascending': int,
}
indexes = [
{'fields': 'number'},
{'fields': 'name', 'unique': True},
{'fields': [('descending', -1), ('ascending', 1)]}
]
__database__ = 'test'
__collection__ = 'IndexTestDocument'
class TestEnsureIndex(BaseAcceptanceTest):
@classmethod
def setup_class(cls):
BaseAcceptanceTest.setup_class()
cls.connected_document = cls.connection.models.IndexTestDocument
cls.connected_document.collection.drop()
cls.connected_document.ensure_indexes()
cls.indexes = cls.connected_document.collection.index_information()
def should_create_index_on_number(self):
index = self.indexes['number_1']
assert index['key'] == [('number', 1)]
assert index.get('unique', False) is False
def should_create_unique_index_on_name(self):
index = self.indexes['name_1']
assert index['key'] == [('name', 1)]
assert index['unique'] is True
def should_create_descending_ascending_index(self):
index = self.indexes['descending_-1_ascending_1']
assert index['key'] == [('descending', -1), ('ascending', 1)]
assert index.get('unique', False) is False
| from tests.acceptance.base_acceptance_test import BaseAcceptanceTest
from scalymongo import Document
class IndexTestDocument(Document):
structure = {
'number': int,
'name': unicode,
'descending': int,
'ascending': int,
}
indexes = [
{'fields': 'number'},
{'fields': 'name', 'unique': True},
{'fields': [('descending', -1), ('ascending', 1)]}
]
__database__ = 'test'
__collection__ = 'IndexTestDocument'
class TestEnsureIndex(BaseAcceptanceTest):
@classmethod
def setup_class(cls):
BaseAcceptanceTest.setup_class()
cls.connected_document = cls.connection.models.IndexTestDocument
cls.connected_document.collection.drop()
cls.connected_document.ensure_indexes()
cls.indexes = cls.connected_document.collection.index_information()
def should_create_index_on_number(self):
assert self.indexes['number_1'] == {
'key': [('number', 1)],
'unique': False,
'v': 0,
}
def should_create_unique_index_on_name(self):
assert self.indexes['name_1'] == {
'key': [('name', 1)],
'unique': True,
'v': 0,
}
def should_create_descending_ascending_index(self):
assert self.indexes['descending_-1_ascending_1'] == {
'key': [('descending', -1), ('ascending', 1)],
'unique': False,
'v': 0,
}
|
Raise RuntimeError if __version__ is not found | from setuptools import setup
def get_version():
import re
with open('lastpass/__init__.py', 'r') as f:
for line in f:
m = re.match(r'__version__ = [\'"]([^\'"]*)[\'"]', line)
if m:
return m.group(1)
raise RuntimeError('Cannot find version information')
setup(
name='lastpass-python',
version=get_version(),
description='LastPass Python API (unofficial)',
long_description=open('README.rst').read(),
license='MIT',
author='konomae',
author_email='[email protected]',
url='https://github.com/konomae/lastpass-python',
packages=['lastpass'],
install_requires=[
"requests>=1.2.1,<=3.0.0",
"pycrypto>=2.6.1",
],
classifiers=[
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: MIT License',
'Intended Audience :: Developers',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: Implementation :: CPython',
],
) | from setuptools import setup
def get_version():
import re
with open('lastpass/__init__.py', 'r') as f:
for line in f:
m = re.match(r'__version__ = [\'"]([^\'"]*)[\'"]', line)
if m:
return m.group(1)
return ''
setup(
name='lastpass-python',
version=get_version(),
description='LastPass Python API (unofficial)',
long_description=open('README.rst').read(),
license='MIT',
author='konomae',
author_email='[email protected]',
url='https://github.com/konomae/lastpass-python',
packages=['lastpass'],
install_requires=[
"requests>=1.2.1,<=3.0.0",
"pycrypto>=2.6.1",
],
classifiers=[
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: MIT License',
'Intended Audience :: Developers',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: Implementation :: CPython',
],
) |
Change that line to see if maybe that's the culprit | <h3>Change Access</h3>
<form class="form-horizontal">
<!-- Select Basic -->
<div class="form-group">
<label class="col-md-8 control-label" for="access-type">Select Access Type</label>
<div class="col-md-8">
<?php
$types = $dal->getAccessTypes();
$selected_user = $_GET['for'];
$curr = $dal->getUserAccessLevel($selected_user);
$level_options = '';
?>
<select id="access-type" name="access-type" class="form-control">
<option disabled>Select Access Type</option>
<?php
foreach ($types as $row) {
$level_options .= '';
//$level_options .= "<option value=".$row['id'].">".$row['type']."</option>";
}
echo $level_options;
/*
if ($types) {
foreach ($types as $row) {
$option = "<option value='".$row['type']."' ";
if ($row['type'] == $curr) {
$option .= "selected>$row['type']</option>";
} else {
$option .= ">$row['type']</option>";
}
echo $option;
}
}
*/
?>
</select>
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-8 control-label" for="submit"></label>
<div class="col-md-8">
<button id="submit" name="submit" class="btn btn-primary">Update</button>
</div>
</div>
</form>
| <h3>Change Access</h3>
<form class="form-horizontal">
<!-- Select Basic -->
<div class="form-group">
<label class="col-md-8 control-label" for="access-type">Select Access Type</label>
<div class="col-md-8">
<?php
$types = $dal->getAccessTypes();
$selected_user = $_GET['for'];
$curr = $dal->getUserAccessLevel($selected_user);
$level_options = '';
?>
<select id="access-type" name="access-type" class="form-control">
<option disabled>Select Access Type</option>
<?php
foreach ($types as $row) {
return '';
//$level_options .= "<option value=".$row['id'].">".$row['type']."</option>";
}
echo $level_options;
/*
if ($types) {
foreach ($types as $row) {
$option = "<option value='".$row['type']."' ";
if ($row['type'] == $curr) {
$option .= "selected>$row['type']</option>";
} else {
$option .= ">$row['type']</option>";
}
echo $option;
}
}
*/
?>
</select>
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-8 control-label" for="submit"></label>
<div class="col-md-8">
<button id="submit" name="submit" class="btn btn-primary">Update</button>
</div>
</div>
</form>
|
Clean up response to no queries. | """
This prints the state of a facet query.
It is used for debugging the faceting system.
"""
from django.core.management.base import BaseCommand
from haystack.query import SearchQuerySet
from hs_core.discovery_parser import ParseSQ
class Command(BaseCommand):
help = "Print debugging information about logical files."
def add_arguments(self, parser):
# a list of resource id's: none does nothing.
parser.add_argument('queries', nargs='*', type=str)
def handle(self, *args, **options):
if len(options['queries']) > 0: # an array of resource short_id to check.
query = ' '.join(options['queries'])
sqs = SearchQuerySet().all()
parser = ParseSQ()
parsed = parser.parse(query)
sqs = sqs.filter(parsed)
print("QUERY '{}' PARSED {}".format(query, str(parsed)))
for result in list(sqs):
stored = result.get_stored_fields()
print(" {}: {} {} {} {}".format(
unicode(stored['short_id']).encode('ascii', 'replace'),
unicode(stored['title']).encode('ascii', 'replace'),
unicode(stored['author']).encode('ascii', 'replace'),
unicode(stored['created']).encode('ascii', 'replace'),
unicode(stored['modified']).encode('ascii', 'replace')))
else:
print("no queries to try")
| """
This prints the state of a facet query.
It is used for debugging the faceting system.
"""
from django.core.management.base import BaseCommand
from haystack.query import SearchQuerySet
from hs_core.discovery_parser import ParseSQ
class Command(BaseCommand):
help = "Print debugging information about logical files."
def add_arguments(self, parser):
# a list of resource id's: none does nothing.
parser.add_argument('queries', nargs='*', type=str)
def handle(self, *args, **options):
if len(options['queries']) > 0: # an array of resource short_id to check.
query = ' '.join(options['queries'])
sqs = SearchQuerySet().all()
parser = ParseSQ()
parsed = parser.parse(query)
sqs = sqs.filter(parsed)
print("QUERY '{}' PARSED {}".format(query, str(parsed)))
for result in list(sqs):
stored = result.get_stored_fields()
print(" {}: {} {} {} {}".format(
unicode(stored['short_id']).encode('ascii', 'replace'),
unicode(stored['title']).encode('ascii', 'replace'),
unicode(stored['author']).encode('ascii', 'replace'),
unicode(stored['created']).encode('ascii', 'replace'),
unicode(stored['modified']).encode('ascii', 'replace')))
else:
print("no queries to try")
query = 'author:"Tarboton, David"'
parser = ParseSQ()
parsed = parser.parse(query)
print("QUERY '{}' PARSED {}".format(query, str(parsed)))
|
Update script for explicit call to EM algorithm optimization | #!/usr/bin/env python
# Standard packages
import sys
import argparse
# Third-party packages
from toil.job import Job
# Package methods
from ddb import configuration
from ddb_ngsflow import pipeline
from ddb_ngsflow.rna import salmon
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--samples_file', help="Input configuration file for samples")
parser.add_argument('-c', '--configuration', help="Configuration file for various settings")
Job.Runner.addToilOptions(parser)
args = parser.parse_args()
args.logLevel = "INFO"
sys.stdout.write("Parsing configuration data\n")
config = configuration.configure_runtime(args.configuration)
sys.stdout.write("Parsing sample data\n")
samples = configuration.configure_samples(args.samples_file, config)
# Workflow Graph definition. The following workflow definition should create a valid Directed Acyclic Graph (DAG)
root_job = Job.wrapJobFn(pipeline.spawn_batch_jobs, cores=1)
# Per sample jobs
for sample in samples:
# Alignment and Refinement Stages
align_job = Job.wrapJobFn(salmon.salmonEM_paired, config, sample, samples,
cores=int(config['salmon']['num_cores']),
memory="{}G".format(config['salmon']['max_mem']))
# Create workflow from created jobs
root_job.addChild(align_job)
# Start workflow execution
Job.Runner.startToil(root_job, args)
| #!/usr/bin/env python
# Standard packages
import sys
import argparse
# Third-party packages
from toil.job import Job
# Package methods
from ddb import configuration
from ddb_ngsflow import pipeline
from ddb_ngsflow.rna import salmon
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--samples_file', help="Input configuration file for samples")
parser.add_argument('-c', '--configuration', help="Configuration file for various settings")
Job.Runner.addToilOptions(parser)
args = parser.parse_args()
args.logLevel = "INFO"
sys.stdout.write("Parsing configuration data\n")
config = configuration.configure_runtime(args.configuration)
sys.stdout.write("Parsing sample data\n")
samples = configuration.configure_samples(args.samples_file, config)
# Workflow Graph definition. The following workflow definition should create a valid Directed Acyclic Graph (DAG)
root_job = Job.wrapJobFn(pipeline.spawn_batch_jobs, cores=1)
# Per sample jobs
for sample in samples:
# Alignment and Refinement Stages
align_job = Job.wrapJobFn(salmon.salmon_paired, config, sample, samples,
cores=int(config['salmon']['num_cores']),
memory="{}G".format(config['salmon']['max_mem']))
# Create workflow from created jobs
root_job.addChild(align_job)
# Start workflow execution
Job.Runner.startToil(root_job, args)
|
Create or recreate sequence counters for Monogo database objects | // Create (or recreate) ID counters for our various entities
db.counters.insert(
{
_id: "cemetery",
seq: 0,
}
)
db.counters.insert(
{
_id: "geolocation",
seq: 0,
}
)
db.counters.insert(
{
_id: "marker",
seq: 0,
}
)
db.counters.insert(
{
_id: "person",
seq: 0,
}
)
db.counters.insert(
{
_id: "reading",
seq: 0,
}
)
| db.counters.insert(
{
_id: "cemetery",
seq: 0,
}
)
db.counters.insert(
{
_id: "geolocation",
seq: 0,
}
)
db.counters.insert(
{
_id: "marker",
seq: 0,
}
)
db.counters.insert(
{
_id: "person",
seq: 0,
}
)
db.counters.insert(
{
_id: "reading",
seq: 0,
}
)
|
Fix NOTICE error on PHP 7.4: Trying to access array offset on value of type null | <?php
namespace Hmaus\Reynaldo\Elements;
class HttpResponseElement extends BaseElement implements ApiElement, ApiHttpResponse
{
public function getStatusCode()
{
return isset($this->attributes['statusCode']) ? (int)$this->attributes['statusCode'] : 0;
}
public function getHeaders()
{
$headersFromAttributes = $this->getAttribute('headers');
if (!$headersFromAttributes) {
return [];
}
$headers = [];
foreach ($headersFromAttributes['content'] as $header) {
$headers[$header['content']['key']['content']] = $header['content']['value']['content'];
}
return $headers;
}
public function hasMessageBody()
{
return $this->getMessageBodyAsset() !== null;
}
public function getMessageBodyAsset()
{
return $this->getFirstAssetByClass('messageBody');
}
/**
* @param $className
* @return AssetElement|null
*/
private function getFirstAssetByClass($className)
{
$assets = $this->getElementsByType(AssetElement::class);
/** @var AssetElement $asset */
foreach ($assets as $asset) {
if ($asset->hasClass($className)) {
return $asset;
}
}
return null;
}
public function hasMessageBodySchema()
{
return $this->getMessageBodySchemaAsset() !== null;
}
public function getMessageBodySchemaAsset()
{
return $this->getFirstAssetByClass('messageBodySchema');
}
public function getDataStructure()
{
return $this->getFirstElementByType(DataStructureElement::class);
}
} | <?php
namespace Hmaus\Reynaldo\Elements;
class HttpResponseElement extends BaseElement implements ApiElement, ApiHttpResponse
{
public function getStatusCode()
{
return (int)$this->attributes['statusCode'];
}
public function getHeaders()
{
$headersFromAttributes = $this->getAttribute('headers');
if (!$headersFromAttributes) {
return [];
}
$headers = [];
foreach ($headersFromAttributes['content'] as $header) {
$headers[$header['content']['key']['content']] = $header['content']['value']['content'];
}
return $headers;
}
public function hasMessageBody()
{
return $this->getMessageBodyAsset() !== null;
}
public function getMessageBodyAsset()
{
return $this->getFirstAssetByClass('messageBody');
}
/**
* @param $className
* @return AssetElement|null
*/
private function getFirstAssetByClass($className)
{
$assets = $this->getElementsByType(AssetElement::class);
/** @var AssetElement $asset */
foreach ($assets as $asset) {
if ($asset->hasClass($className)) {
return $asset;
}
}
return null;
}
public function hasMessageBodySchema()
{
return $this->getMessageBodySchemaAsset() !== null;
}
public function getMessageBodySchemaAsset()
{
return $this->getFirstAssetByClass('messageBodySchema');
}
public function getDataStructure()
{
return $this->getFirstElementByType(DataStructureElement::class);
}
} |
Set a starting point for the datatables | <?php
namespace MindOfMicah\LaravelDatatables;
use Illuminate\Http\JsonResponse;
class Datatable
{
protected $model;
protected $columns;
public function __construct($a) {
$this->a = $a;
}
public function asJsonResponse()
{
$data = [];
$total = $amount_displayed = 0;
if ($this->model) {
$model_name = $this->model;
if ($this->columns) {
}
$sql = $model_name::query()->select($this->columns ?: '*');
$total = ($sql->count());
$sql->skip($this->a->input('start'));
$models = $sql->take($this->a->input('length'))->get();
$data = $models->toArray();
$total = $total;
$amount_displayed = count($models);
}
$data = ([
'aaData'=>$data,
'iTotalRecords'=>$total,
'iTotalDisplayRecords'=>$amount_displayed
]);
return new JsonResponse($data, 200);
}
public function forEloquentModel($model)
{
$this->model = $model;
return $this;
}
public function pluckColumns($argument1)
{
$this->columns[] = $argument1;
return $this;
}
}
| <?php
namespace MindOfMicah\LaravelDatatables;
use Illuminate\Http\JsonResponse;
class Datatable
{
protected $model;
protected $columns;
public function __construct($a) {
$this->a = $a;
}
public function asJsonResponse()
{
$data = [];
$total = $amount_displayed = 0;
if ($this->model) {
$model_name = $this->model;
if ($this->columns) {
}
$sql = $model_name::query()->select($this->columns ?: '*');
$total = ($sql->count());
$models = $sql->take($this->a->input('length'))->get();
$data = $models->toArray();
$total = $total;
$amount_displayed = count($models);
}
$data = ([
'aaData'=>$data,
'iTotalRecords'=>$total,
'iTotalDisplayRecords'=>$amount_displayed
]);
return new JsonResponse($data, 200);
}
public function forEloquentModel($model)
{
$this->model = $model;
return $this;
}
public function pluckColumns($argument1)
{
$this->columns[] = $argument1;
return $this;
}
}
|
Fix: Add missing $ before parameter name in docblock | <?php
namespace League\Route;
trait RouteConditionTrait
{
/**
* @var string
*/
protected $host;
/**
* @var string
*/
protected $name;
/**
* @var string
*/
protected $scheme;
/**
* Get the host.
*
* @return string
*/
public function getHost()
{
return $this->host;
}
/**
* Set the host.
*
* @param string $host
*
* @return \League\Route\Route
*/
public function setHost($host)
{
$this->host = $host;
return $this;
}
/**
* Get the name.
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set the name.
*
* @param string $name
*
* @return \League\Route\Route
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get the scheme.
*
* @return string
*/
public function getScheme()
{
return $this->scheme;
}
/**
* Set the scheme.
*
* @param string $scheme
*
* @return \League\Route\Route
*/
public function setScheme($scheme)
{
$this->scheme = $scheme;
return $this;
}
}
| <?php
namespace League\Route;
trait RouteConditionTrait
{
/**
* @var string
*/
protected $host;
/**
* @var string
*/
protected $name;
/**
* @var string
*/
protected $scheme;
/**
* Get the host.
*
* @return string
*/
public function getHost()
{
return $this->host;
}
/**
* Set the host.
*
* @param string $host
*
* @return \League\Route\Route
*/
public function setHost($host)
{
$this->host = $host;
return $this;
}
/**
* Get the name.
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set the name.
*
* @param string name
*
* @return \League\Route\Route
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get the scheme.
*
* @return string
*/
public function getScheme()
{
return $this->scheme;
}
/**
* Set the scheme.
*
* @param string $scheme
*
* @return \League\Route\Route
*/
public function setScheme($scheme)
{
$this->scheme = $scheme;
return $this;
}
}
|
Include logger name for java util log handler
When using the log4j java util logger bridge handler, logs now show
`asciidoctor` instead of `unknown.jul.logger` for logger name.
fixes #833 | package org.asciidoctor.jruby.log.internal;
import org.asciidoctor.log.LogHandler;
import org.asciidoctor.log.LogRecord;
import org.asciidoctor.log.Severity;
import java.util.logging.Level;
import java.util.logging.Logger;
public class JULLogHandler implements LogHandler {
private final static String LOGGER_NAME = "asciidoctor";
private final static Logger LOGGER = Logger.getLogger(LOGGER_NAME);
@Override
public void log(LogRecord logRecord) {
final java.util.logging.LogRecord julLogRecord =
new java.util.logging.LogRecord(
mapSeverity(logRecord.getSeverity()),
logRecord.getCursor() != null ? logRecord.getCursor().toString() + ": " + logRecord.getMessage() : logRecord.getMessage());
julLogRecord.setSourceClassName(logRecord.getSourceFileName());
julLogRecord.setSourceMethodName(logRecord.getSourceMethodName());
julLogRecord.setParameters(new Object[] { logRecord.getCursor() });
julLogRecord.setLoggerName(LOGGER_NAME);
LOGGER.log(julLogRecord);
}
private static Level mapSeverity(Severity severity) {
switch (severity) {
case DEBUG:
return Level.FINEST;
case INFO:
return Level.INFO;
case WARN:
return Level.WARNING;
case ERROR:
return Level.SEVERE;
case FATAL:
return Level.SEVERE;
case UNKNOWN:
default:
return Level.INFO;
}
}
}
| package org.asciidoctor.jruby.log.internal;
import org.asciidoctor.log.LogHandler;
import org.asciidoctor.log.LogRecord;
import org.asciidoctor.log.Severity;
import java.util.logging.Level;
import java.util.logging.Logger;
public class JULLogHandler implements LogHandler {
private final static Logger LOGGER = Logger.getLogger("asciidoctor");
@Override
public void log(LogRecord logRecord) {
final java.util.logging.LogRecord julLogRecord =
new java.util.logging.LogRecord(
mapSeverity(logRecord.getSeverity()),
logRecord.getCursor() != null ? logRecord.getCursor().toString() + ": " + logRecord.getMessage() : logRecord.getMessage());
julLogRecord.setSourceClassName(logRecord.getSourceFileName());
julLogRecord.setSourceMethodName(logRecord.getSourceMethodName());
julLogRecord.setParameters(new Object[] { logRecord.getCursor() });
LOGGER.log(julLogRecord);
}
private static Level mapSeverity(Severity severity) {
switch (severity) {
case DEBUG:
return Level.FINEST;
case INFO:
return Level.INFO;
case WARN:
return Level.WARNING;
case ERROR:
return Level.SEVERE;
case FATAL:
return Level.SEVERE;
case UNKNOWN:
default:
return Level.INFO;
}
}
} |
Repair some merge errors before do somethink. | <?php
use yii\helpers\Html;
//use yii\widgets\ActiveForm;
use kartik\form\ActiveForm;
/* @var $this yii\web\View */
/* @var $model frontend\models\Queen */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="queen-form">
<?php $form = ActiveForm::begin(); ?>
<div class="row">
<div class="col-xs-6">
<?= $form->field($model, 'mark_disk_color')->dropDownList(frontend\models\Status::dropDown($model->tableName(),'mark_disk_color'),['maxlength' => true]) ?>
</div>
<div class="col-xs-6">
<?= $form->field($model, 'mark_disk_number')->textInput() ?>
</div>
</div>
<?= $form->field($model, 'variety')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'reproductive_hive_id')->textInput() ?>
<?= $form->field($model, 'hive_id')->textInput() ?>
<?= $form->field($model, 'hive_time')->textInput() ?>
<?= $form->field($model, 'matting_box_id')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'matting_box_time')->textInput() ?>
<div class="form-group">
<?= Html::submitButton(Yii::t('app', 'Save'), ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
| <?php
use yii\helpers\Html;
//use yii\widgets\ActiveForm;
use kartik\form\ActiveForm;
/* @var $this yii\web\View */
/* @var $model frontend\models\Queen */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="queen-form">
<?php $form = ActiveForm::begin(); ?>
<div class="row">
<div class="col-xs-6">
<?= $form->field($model, 'mark_disk_color')->dropDownList(frontend\models\Status::dropDown($model->tableName(),'mark_disk_color'),['maxlength' => true]) ?>
</div>
<div class="col-xs-6">
<?= $form->field($model, 'mark_disk_number')->textInput() ?>
</div>
</div>
<?= $form->field($model, 'variety')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'reproductive_hive_id')->textInput() ?>
<?= $form->field($model, 'hive_id')->textInput() ?>
<?= $form->field($model, 'hive_time')->textInput() ?>
<?= $form->field($model, 'matting_box_id')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'matting_box_time')->textInput() ?>
<div class="form-group">
<?= Html::submitButton(Yii::t('app', 'Save'), ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
|
Check for badly formatted props | 'use strict'
module.exports = {
description: "A basic React component",
generateReplacements(args) {
let propTypes = "";
let defaultProps = "";
if(args.length) {
propTypes = "__name__.propTypes = {";
defaultProps = "\n getDefaultProps: function() {";
for(let index in args) {
let prop = args[index];
let parts = prop.split(':');
if(parts.length != 2) {
throw new Error(`Prop ${prop} is formatted incorrectly`);
}
propTypes += `\n ${parts[0]}: ${this.reactPropTypeFrom(parts[1])},`;
defaultProps += `\n ${parts[0]}: ${this.reactDefaultPropFrom(parts[1])},`;
}
propTypes += "\n}\n";
defaultProps += "\n },\n";
}
return {'__proptypes__': propTypes, '__defaultprops__': defaultProps };
},
reactPropTypeFrom(prop) {
return 'React.PropTypes.' + prop;
},
reactDefaultPropFrom(prop) {
switch(prop) {
case 'number':
return '0';
case 'string':
return "''";
case 'array':
return '[]';
case 'bool':
return 'false';
case 'func':
case 'object':
case 'shape':
return 'null';
default:
throw new Error(`Unsupported propType ${prop}`);
}
}
}
| 'use strict'
module.exports = {
description: "A basic React component",
generateReplacements(args) {
let propTypes = "";
let defaultProps = "";
if(args.length) {
propTypes = "__name__.propTypes = {";
defaultProps = "\n getDefaultProps: function() {";
for(let index in args) {
let prop = args[index];
let parts = prop.split(':');
propTypes += `\n ${parts[0]}: ${this.reactPropTypeFrom(parts[1])},`;
defaultProps += `\n ${parts[0]}: ${this.reactDefaultPropFrom(parts[1])},`;
}
propTypes += "\n}\n";
defaultProps += "\n },\n";
}
return {'__proptypes__': propTypes, '__defaultprops__': defaultProps };
},
reactPropTypeFrom(prop) {
return 'React.PropTypes.' + prop;
},
reactDefaultPropFrom(prop) {
switch(prop) {
case 'number':
return '0';
case 'string':
return "''";
case 'array':
return '[]';
case 'bool':
return 'false';
case 'func':
case 'object':
case 'shape':
return 'null';
default:
throw new Error(`Unsupported propType ${prop}`);
}
}
}
|
Fix possible problem with middleware | from functools import update_wrapper, wraps
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.http import HttpResponse, HttpResponseRedirect
from django.utils.decorators import available_attrs
from django.utils.http import urlquote
def facebook_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME):
"""
Decorator for views that checks that the user is logged in, redirecting
to the log-in page if necessary.
"""
def _passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
if not login_url:
from django.conf import settings
login_url = settings.LOGIN_URL
def decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
if test_func(request):
return view_func(request, *args, **kwargs)
path = urlquote(request.get_full_path())
tup = login_url, redirect_field_name, path
return HttpResponseRedirect('%s?%s=%s' % tup)
return wraps(view_func, assigned=available_attrs(view_func))(_wrapped_view)
return decorator
actual_decorator = _passes_test(
lambda r: r.facebook,
redirect_field_name=redirect_field_name
)
if function:
return actual_decorator(function)
return actual_decorator
| from functools import update_wrapper, wraps
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.http import HttpResponse, HttpResponseRedirect
from django.utils.decorators import available_attrs
from django.utils.http import urlquote
def facebook_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME):
"""
Decorator for views that checks that the user is logged in, redirecting
to the log-in page if necessary.
"""
def _passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
if not login_url:
from django.conf import settings
login_url = settings.LOGIN_URL
def decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
if test_func(request):
return view_func(request, *args, **kwargs)
path = urlquote(request.get_full_path())
tup = login_url, redirect_field_name, path
return HttpResponseRedirect('%s?%s=%s' % tup)
return wraps(view_func, assigned=available_attrs(view_func))(_wrapped_view)
return decorator
actual_decorator = _passes_test(
lambda r: r.facebook.uid,
redirect_field_name=redirect_field_name
)
if function:
return actual_decorator(function)
return actual_decorator
|
TST: Clean up parent temporary directory | # coding: utf-8
import logging
import os
import shutil
import sys
import tempfile
import unittest
import six
import fiona
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
class UnicodePathTest(unittest.TestCase):
def setUp(self):
tempdir = tempfile.mkdtemp()
self.dir = os.path.join(tempdir, 'français')
shutil.copytree('docs/data/', self.dir)
def tearDown(self):
shutil.rmtree(os.path.dirname(self.dir))
def test_unicode_path(self):
path = self.dir + '/test_uk.shp'
if sys.version_info < (3,):
path = path.decode('utf-8')
with fiona.open(path) as c:
assert len(c) == 48
def test_unicode_path_layer(self):
path = self.dir
layer = 'test_uk'
if sys.version_info < (3,):
path = path.decode('utf-8')
layer = layer.decode('utf-8')
with fiona.open(path, layer=layer) as c:
assert len(c) == 48
def test_utf8_path(self):
path = self.dir + '/test_uk.shp'
if sys.version_info < (3,):
with fiona.open(path) as c:
assert len(c) == 48
| # coding: utf-8
import logging
import os
import shutil
import sys
import tempfile
import unittest
import six
import fiona
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
class UnicodePathTest(unittest.TestCase):
def setUp(self):
tempdir = tempfile.mkdtemp()
self.dir = os.path.join(tempdir, 'français')
shutil.copytree('docs/data/', self.dir)
def tearDown(self):
shutil.rmtree(self.dir)
def test_unicode_path(self):
path = self.dir + '/test_uk.shp'
if sys.version_info < (3,):
path = path.decode('utf-8')
with fiona.open(path) as c:
assert len(c) == 48
def test_unicode_path_layer(self):
path = self.dir
layer = 'test_uk'
if sys.version_info < (3,):
path = path.decode('utf-8')
layer = layer.decode('utf-8')
with fiona.open(path, layer=layer) as c:
assert len(c) == 48
def test_utf8_path(self):
path = self.dir + '/test_uk.shp'
if sys.version_info < (3,):
with fiona.open(path) as c:
assert len(c) == 48
|
Fix decision unsupported operation on execute | package com.uxxu.konashi.lib.action;
import android.bluetooth.BluetoothGattService;
import com.uxxu.konashi.lib.KonashiErrorType;
import java.util.UUID;
import info.izumin.android.bletia.BletiaErrorType;
import info.izumin.android.bletia.BletiaException;
import info.izumin.android.bletia.action.WriteCharacteristicAction;
import info.izumin.android.bletia.wrapper.BluetoothGattWrapper;
/**
* Created by izumin on 9/17/15.
*/
public abstract class KonashiWriteCharacteristicAction extends WriteCharacteristicAction {
protected KonashiWriteCharacteristicAction(BluetoothGattService service, UUID uuid) {
super(service, uuid);
}
@Override
public boolean execute(BluetoothGattWrapper gattWrapper) {
if (getCharacteristic() == null) {
rejectIfParamsAreInvalid(KonashiErrorType.UNSUPPORTED_OPERATION);
return false;
}
BletiaErrorType errorType = validate();
if (errorType == KonashiErrorType.NO_ERROR) {
setValue();
return super.execute(gattWrapper);
} else {
rejectIfParamsAreInvalid(errorType);
return false;
}
}
protected void rejectIfParamsAreInvalid(BletiaErrorType errorType) {
getDeferred().reject(new BletiaException(this, errorType));
}
protected abstract void setValue();
protected abstract BletiaErrorType validate();
}
| package com.uxxu.konashi.lib.action;
import android.bluetooth.BluetoothGattService;
import com.uxxu.konashi.lib.KonashiErrorType;
import java.util.UUID;
import info.izumin.android.bletia.BletiaErrorType;
import info.izumin.android.bletia.BletiaException;
import info.izumin.android.bletia.action.WriteCharacteristicAction;
import info.izumin.android.bletia.wrapper.BluetoothGattWrapper;
/**
* Created by izumin on 9/17/15.
*/
public abstract class KonashiWriteCharacteristicAction extends WriteCharacteristicAction {
protected KonashiWriteCharacteristicAction(BluetoothGattService service, UUID uuid) {
super(service, uuid);
}
@Override
public boolean execute(BluetoothGattWrapper gattWrapper) {
if (getCharacteristic() != null) {
rejectIfParamsAreInvalid(KonashiErrorType.UNSUPPORTED_OPERATION);
return false;
}
BletiaErrorType errorType = validate();
if (errorType == KonashiErrorType.NO_ERROR) {
setValue();
return super.execute(gattWrapper);
} else {
rejectIfParamsAreInvalid(errorType);
return false;
}
}
protected void rejectIfParamsAreInvalid(BletiaErrorType errorType) {
getDeferred().reject(new BletiaException(this, errorType));
}
protected abstract void setValue();
protected abstract BletiaErrorType validate();
}
|
Fix and readd old tests | "use strict";
var assert = require('chai').assert;
var xdTesting = require('../../lib/index')
var templates = require('../../lib/templates');
describe('MultiDevice - WebdriverIO commands', function () {
var test = this;
test.baseUrl = "http://localhost:8090/";
it('should be supported on multiple devices @large', function () {
var options = {A: templates.devices.chrome(), B: templates.devices.chrome()};
return xdTesting.multiremote(options)
.init()
.url(test.baseUrl)
.getText('#counter').then((textA, textB) => [textA, textB].forEach(text => assert.equal(text, '-')))
.click('#button')
.getText('#counter').then((textA, textB) => [textA, textB].forEach(text => assert.equal(text, '1')))
.end();
});
it('should be supported on a single device @large', function () {
var options = {A: templates.devices.chrome()};
return xdTesting.multiremote(options)
.init()
.url(test.baseUrl)
.getText('#counter').then(text => text => assert.equal(text, '-'))
.click('#button')
.getText('#counter').then(text => text => assert.equal(text, '1'))
.end();
});
});
| "use strict";
var assert = require('chai').assert;
var xdTesting = require('../../lib/index')
var templates = require('../../lib/templates');
describe.skip('MultiDevice - WebdriverIO commands', function () {
var test = this;
test.devices = {};
test.baseUrl = "http://localhost:8090/";
afterEach(function () {
// Close browsers before completing a test
return test.devices.endAll();
});
it('should be supported on multiple devices @large', function () {
var options = {A: templates.devices.chrome(), B: templates.devices.chrome()};
return test.devices = xdTesting.multiremote(options)
.init()
.url(test.baseUrl)
.getText('#counter').then((textA, textB) => [textA, textB].forEach(text => assert.equal(text, '-')))
.click('#button')
.getText('#counter').then((textA, textB) => [textA, textB].forEach(text => assert.equal(text, '1')))
.end();
});
it.skip('should be supported on a single device @large', function () {
var options = {A: templates.devices.chrome()};
return test.devices = xdTesting.multiremote(options)
.init()
.url(test.baseUrl)
.getText('#counter').then((textA, textB) => [textA, textB].forEach(text => assert.equal(text, '-')))
.click('#button')
.getText('#counter').then((textA, textB) => [textA, textB].forEach(text => assert.equal(text, '1')))
.end();
});
});
|
Add update user income to server | 'use strict';
module.exports = function(data) {
return {
getUserAccountsDetails(req, res) {
let currentUserId = req.user.id;
return data.getAccountsByUserId(currentUserId)
.then((accountsData) => {
if (accountsData.accounts.length == 0) {
res.status(400).json({message: 'No accounts'});
}
res.status(200).json(accounts);
})
.catch((err) => {
res.status(400).json({ message: err.message });
});
},
addNewAccount(req, res) {
let currentUserId = req.user.id;
let accountToAdd = req.body;
let username = req.user.username;
let response = {
sucsess: true,
username: username
};
return data.getAccountsByUserId(currentUserId)
.then((resObject) => {
data.addNewAccountToCurrentUser(accountToAdd, currentUserId)
.then((userWithAccounts) => {
res.status(200).json(response);
});
});
}
}
};
| 'use strict';
module.exports = function(data) {
return {
getUserAccountsDetails(req, res) {
let currentUserId = req.user.id;
return data.getAccountsByUserId(currentUserId)
.then((accountsData) => {
if (accountsData.accounts.length == 0) {
res.status(400).json({message: 'No accounts'});
}
res.status(200).json(accounts);
})
.catch((err) => {
res.status(400).json({ message: err });
});
},
addNewAccount(req, res) {
let currentUserId = req.user.id;
let accountToAdd = req.body;
let username = req.user.username;
let response = {
sucsess: true,
username: username
};
return data.getAccountsByUserId(currentUserId)
.then((resObject) => {
data.addNewAccountToCurrentUser(accountToAdd, currentUserId)
.then((userWithAccounts) => {
res.status(200).json(response);
});
});
}
}
};
|
Add verify of current user id on email verification | <?php
namespace Illuminate\Foundation\Auth;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Http\Request;
use Illuminate\Auth\Events\Verified;
trait VerifiesEmails
{
use RedirectsUsers;
/**
* Show the email verification notice.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function show(Request $request)
{
return $request->user()->hasVerifiedEmail()
? redirect($this->redirectPath())
: view('auth.verify');
}
/**
* Mark the authenticated user's email address as verified.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
* @throws AuthorizationException
*/
public function verify(Request $request)
{
if ($request->route('id') != $request->user()->getKey()) {
throw new AuthorizationException();
}
if ($request->user()->markEmailAsVerified()) {
event(new Verified($request->user()));
}
return redirect($this->redirectPath())->with('verified', true);
}
/**
* Resend the email verification notification.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function resend(Request $request)
{
if ($request->user()->hasVerifiedEmail()) {
return redirect($this->redirectPath());
}
$request->user()->sendEmailVerificationNotification();
return back()->with('resent', true);
}
}
| <?php
namespace Illuminate\Foundation\Auth;
use Illuminate\Http\Request;
use Illuminate\Auth\Events\Verified;
trait VerifiesEmails
{
use RedirectsUsers;
/**
* Show the email verification notice.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function show(Request $request)
{
return $request->user()->hasVerifiedEmail()
? redirect($this->redirectPath())
: view('auth.verify');
}
/**
* Mark the authenticated user's email address as verified.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function verify(Request $request)
{
if ($request->route('id') == $request->user()->getKey() &&
$request->user()->markEmailAsVerified()) {
event(new Verified($request->user()));
}
return redirect($this->redirectPath())->with('verified', true);
}
/**
* Resend the email verification notification.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function resend(Request $request)
{
if ($request->user()->hasVerifiedEmail()) {
return redirect($this->redirectPath());
}
$request->user()->sendEmailVerificationNotification();
return back()->with('resent', true);
}
}
|
Change order of operations within migration so breaking schema changes come last | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-05-01 16:41
from __future__ import unicode_literals
from django.db import migrations, models
import temba.utils.models
class Migration(migrations.Migration):
dependencies = [
('msgs', '0093_populate_translatables'),
]
operations = [
migrations.AlterField(
model_name='broadcast',
name='base_language',
field=models.CharField(help_text='The language used to send this to contacts without a language',
max_length=4),
),
migrations.AlterField(
model_name='broadcast',
name='translations',
field=temba.utils.models.TranslatableField(help_text='The localized versions of the message text',
max_length=640, verbose_name='Translations'),
),
migrations.RemoveField(
model_name='broadcast',
name='language_dict',
),
migrations.RemoveField(
model_name='broadcast',
name='media_dict',
),
migrations.RemoveField(
model_name='broadcast',
name='text',
),
migrations.RenameField(
model_name='broadcast',
old_name='translations',
new_name='text',
),
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-05-01 16:41
from __future__ import unicode_literals
from django.db import migrations, models
import temba.utils.models
class Migration(migrations.Migration):
dependencies = [
('msgs', '0093_populate_translatables'),
]
operations = [
migrations.RemoveField(
model_name='broadcast',
name='language_dict',
),
migrations.RemoveField(
model_name='broadcast',
name='media_dict',
),
migrations.RemoveField(
model_name='broadcast',
name='text',
),
migrations.AlterField(
model_name='broadcast',
name='base_language',
field=models.CharField(help_text='The language used to send this to contacts without a language',
max_length=4),
),
migrations.AlterField(
model_name='broadcast',
name='translations',
field=temba.utils.models.TranslatableField(help_text='The localized versions of the message text',
max_length=640, verbose_name='Translations'),
),
migrations.RenameField(
model_name='broadcast',
old_name='translations',
new_name='text',
),
]
|
Fix exception on api login | "use strict";
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const usr = require('../models/user');
// Passport session set-up
passport.serializeUser((user, done) => {
done(null, user.user_id);
});
passport.deserializeUser(async (req, id, done) => {
const queryRes = await usr.getUserByField('user_id', id);
if (queryRes.rowCount === 0) {
done(null, {});
} else {
done(null, queryRes.rows[0]);
}
});
passport.use(new LocalStrategy({usernameField: 'username', passwordField: 'password', passReqToCallback: true},
async (req, username, password, done) => {
const queryRes = await usr.getUserByField('username', username);
if (queryRes.rowCount === 0) {
// No sessions with API logins, so don't store flash message and save sessions
try {
req.flash('error', 'No such user');
req.session.save(() => {
return done(null, false);
});
} catch (err) {
return done(null, false);
}
} else {
const authOK = await usr.checkPassword(queryRes.rows[0], password);
if (authOK) {
return done(null, queryRes.rows[0]);
} else {
// No sessions with API logins, so don't store flash message and save sessions
try {
req.flash('error', 'Wrong password');
req.session.save(() => {
return done(null, false);
});
} catch (err) {
return done(null, false);
}
}
}
})
);
module.exports = passport;
| "use strict";
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const usr = require('../models/user');
// Passport session set-up
passport.serializeUser((user, done) => {
done(null, user.user_id);
});
passport.deserializeUser(async (req, id, done) => {
const queryRes = await usr.getUserByField('user_id', id);
if (queryRes.rowCount === 0) {
done(null, {});
} else {
done(null, queryRes.rows[0]);
}
});
passport.use(new LocalStrategy({usernameField: 'username', passwordField: 'password', passReqToCallback: true},
async (req, username, password, done) => {
const queryRes = await usr.getUserByField('username', username);
if (queryRes.rowCount === 0) {
req.flash('error', 'No such user');
req.session.save(() => {
return done(null, false);
});
} else {
const authOK = await usr.checkPassword(queryRes.rows[0], password);
if (authOK) {
return done(null, queryRes.rows[0]);
} else {
req.flash('error', 'Wrong password');
req.session.save(() => {
return done(null, false);
});
}
}
})
);
module.exports = passport;
|
Stop watchnig so many files, fixes errors | module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
options: {
jshintrc: '.jshintrc'
},
all: [
'Gruntfile.js',
'lib/**/*.js',
'public/javascripts/lib/**/*.js',
'test/**/*.js'
]
},
cafemocha: {
options: {
ui: 'bdd',
reporter: 'dot'
},
src: 'test/unit/**/*.js'
},
// NOTE: need to start karma server first in
// separate window with `grunt karma:unit`
karma: {
unit: {
configFile: 'karma.conf.js'
}
},
watch: {
files: ['<%= jshint.all %>'],
tasks: ['jshint', 'cafemocha', 'karma:unit:run'],
options: {interrupt: true}
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-cafe-mocha');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-karma');
grunt.registerTask('default', ['jshint', 'cafemocha', 'karma:unit:run']);
};
| module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
options: {
jshintrc: '.jshintrc'
},
all: [
'Gruntfile.js',
'lib/**/*.js',
'public/javascripts/lib/**/*.js',
'test/**/*.js'
]
},
cafemocha: {
options: {
ui: 'bdd',
reporter: 'dot'
},
src: 'test/unit/**/*.js'
},
// NOTE: need to start karma server first in
// separate window with `grunt karma:unit`
karma: {
unit: {
configFile: 'karma.conf.js'
}
},
watch: {
files: '**/*.js',
tasks: ['jshint', 'cafemocha', 'karma:unit:run']
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-cafe-mocha');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-karma');
grunt.registerTask('default', ['jshint', 'cafemocha', 'karma:unit:run']);
};
|
Fix very 1st startup when user has no data: there is no _rev to dereference. | /*! Task Slayer | (c) 2014 Eric Mountain | https://github.com/EricMountain/TaskSlayer */
// LocalStorage layer
define(["angular"],
function() {
(function(window, angular, undefined) {
'use strict';
angular.module('localstorage', [])
.factory('localstorage', ['$http', function($http) {
function save(data) {
console.log("Saving to local storage: " + data._rev);
localStorage.storageService = angular.toJson(data);
}
function load() {
var json = localStorage.storageService;
var data = angular.fromJson(json);
var dataInfo = "no data";
if (!(typeof data === 'undefined'))
dataInfo = data._rev;
console.log("Loaded from local storage: " + dataInfo);
return data;
}
return {
save: save,
load: load
};
}]);
})(window, window.angular);
});
| /*! Task Slayer | (c) 2014 Eric Mountain | https://github.com/EricMountain/TaskSlayer */
// LocalStorage layer
define(["angular"],
function() {
(function(window, angular, undefined) {
'use strict';
angular.module('localstorage', [])
.factory('localstorage', ['$http', function($http) {
function save(data) {
console.log("Saving to local storage: " + data._rev);
localStorage.storageService = angular.toJson(data);
}
function load() {
var json = localStorage.storageService;
var data = angular.fromJson(json);
console.log("Loaded from local storage: " + data._rev);
return data;
}
return {
save: save,
load: load
};
}]);
})(window, window.angular);
});
|
Change wrong variable name cv_term_id to correct one type_cvterm_id | <?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'];
$result['type_cvterm_id'] = $row['type_cvterm_id'];
$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;
$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'];
$result['cv_term_id'] = $row['type_cvterm_id'];
$data[] = $result;
}
return $data;
}
}
?>
|
Add pretend to the test requirements | import sys
from setuptools import setup
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
#import here, cause outside the eggs aren't loaded
import pytest
sys.exit(pytest.main(self.test_args))
setup(
name="Flask-Redistore",
version="1.0",
url="",
license="BSD",
author="Donald Stufft",
author_email="[email protected]",
description="Adds Redis support to your Flask applications",
long_description=open("README.rst").read(),
py_modules=["flask_redistore"],
zip_safe=False,
include_package_data=True,
platforms="any",
install_requires=[
"Flask",
"redis",
],
extras_require={"tests": ["pytest", "pretend"]},
tests_require=["pytest", "pretend"],
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
],
cmdclass={"test": PyTest},
)
| import sys
from setuptools import setup
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
#import here, cause outside the eggs aren't loaded
import pytest
sys.exit(pytest.main(self.test_args))
setup(
name="Flask-Redistore",
version="1.0",
url="",
license="BSD",
author="Donald Stufft",
author_email="[email protected]",
description="Adds Redis support to your Flask applications",
long_description=open("README.rst").read(),
py_modules=["flask_redistore"],
zip_safe=False,
include_package_data=True,
platforms="any",
install_requires=[
"Flask",
"redis",
],
extras_require={"tests": ["pytest"]},
tests_require=["pytest"],
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
],
cmdclass={"test": PyTest},
)
|
Add index for image metainformation | import uuid
from django.conf import settings
from django.contrib.postgres.fields import JSONField
from django.contrib.postgres.indexes import GinIndex
from django.db import models
from django.utils.translation import ugettext_lazy as _
from ..models import UpdatedMixin
from .storages import image_storage
class Image(UpdatedMixin, models.Model):
author = models.ForeignKey(
settings.AUTH_USER_MODEL, related_name='images',
verbose_name=_('Author'), on_delete=models.PROTECT)
uuid = models.UUIDField(_('UUID'), primary_key=True)
image = models.ImageField(storage=image_storage)
mime_type = models.CharField(_('content type'), max_length=99, blank=True)
meta = JSONField(_('meta-information'), default={}, blank=True)
class Meta:
verbose_name = _('image')
verbose_name_plural = _('images')
ordering = ('-created_at',)
indexes = [GinIndex(fields=['meta'])]
def __str__(self):
return self.image.name
def save(self, force_insert=False, force_update=False, using=None,
update_fields=None):
if not self.uuid:
uid = uuid.uuid4()
self.uuid = uid
self.image.name = image_storage.get_available_name(
self.image.name, uuid=uid)
super(Image, self).save(force_insert=force_insert,
force_update=force_update,
using=using,
update_fields=update_fields)
| import uuid
from django.conf import settings
from django.contrib.postgres.fields import JSONField
from django.db import models
from django.utils.translation import ugettext_lazy as _
from ..models import UpdatedMixin
from .storages import image_storage
class Image(UpdatedMixin, models.Model):
author = models.ForeignKey(
settings.AUTH_USER_MODEL, related_name='images',
verbose_name=_('Author'), on_delete=models.PROTECT)
uuid = models.UUIDField(_('UUID'), primary_key=True)
image = models.ImageField(storage=image_storage)
mime_type = models.CharField(_('content type'), max_length=99, blank=True)
meta = JSONField(_('meta-information'), default={}, blank=True)
class Meta:
verbose_name = _('image')
verbose_name_plural = _('images')
ordering = ('-created_at',)
def __str__(self):
return self.image.name
def save(self, force_insert=False, force_update=False, using=None,
update_fields=None):
if not self.uuid:
uid = uuid.uuid4()
self.uuid = uid
self.image.name = image_storage.get_available_name(
self.image.name, uuid=uid)
super(Image, self).save(force_insert=force_insert,
force_update=force_update,
using=using,
update_fields=update_fields)
|
Fix format in linechat code | import React, {Component} from 'react';
import {connect} from 'react-redux';
import {Avatar, Chip} from 'material-ui';
const mapStateToProps = (state, ownProps) => ({
line: ownProps.line,
user: state.auth.user,
});
const LineChat = ({line, user}) => {
return (
<div>
{user.id === line.studentid ? (
<div style={{float: 'right', clear: 'both'}} >
<Chip>
<Avatar src={line.studentavatar} />
<div style={{fontSize: 'smaller', color: 'red'}}>
You says
</div>
<div>
<p>{line.text}</p>
</div>
</Chip>
<br />
</div>
) : (
<div style={{float: 'left', clear: 'both'}}>
<Chip>
<Avatar src={line.studentavatar} />
<div style={{fontSize: 'smaller', color: 'red'}}>
{line.studentname} says
</div>
<div>
<p>{line.text}</p>
</div>
</Chip>
<br />
</div>
) }
</div>
);
};
export default connect(mapStateToProps)(LineChat);
| import React, {Component} from 'react';
import {connect} from 'react-redux';
import {Avatar, Chip} from 'material-ui';
const mapStateToProps = (state, ownProps) => ({
line: ownProps.line,
user: state.auth.user,
});
const LineChat = ({line, user}) => {
const divStyleRight = {
float: 'rigth',
color: 'red',
};
return (
<div>
{ user.id === line.studentid ? (
<div style={{float: 'right', clear: 'both'}} >
<Chip>
<Avatar src={line.studentavatar} />
<div style={{fontSize: 'smaller', color: 'red'}}>
You says
</div>
<div>
<p>{line.text}</p>
</div>
</Chip>
<br/>
</div>
): (
<div style={{float: 'left', clear: 'both'}}>
<Chip>
<Avatar src={line.studentavatar} />
<div style={{fontSize: 'smaller', color: 'red'}}>
{line.studentname} says
</div>
<div>
<p>{line.text}</p>
</div>
</Chip>
<br/>
</div>
) }
</div>
);
};
export default connect(mapStateToProps)(LineChat);
|
Update setdefault to ensure commit is called | import yaml
class _Storage:
def __getitem__(self, key):
pass
def __setitem__(self, key, value):
pass
def __delitem__(self, key):
pass
class _DictionaryStorage(_Storage):
def __init__(self):
self.data = {}
def __del__(self):
self.commit()
def commit(self):
pass
def get(self, key, default=None):
return self.data.get(key, default)
def setdefault(self, key, default=None):
if key not in self.data:
self[key] = default
return self[key]
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key, value):
self.data[key] = value
self.commit()
def __delitem__(self, key):
del self.data[key]
class Memory(_DictionaryStorage):
pass
class YAML(_DictionaryStorage):
def __init__(self, filename="storage.yaml"):
super().__init__()
self.filename = filename
try:
with open(self.filename) as fd:
self.data = yaml.load(fd.read())
except FileNotFoundError:
pass
if not self.data:
self.data = {}
def commit(self):
with open(self.filename, "w") as fd:
fd.write(yaml.dump(self.data))
| import yaml
class _Storage:
def __getitem__(self, key):
pass
def __setitem__(self, key, value):
pass
def __delitem__(self, key):
pass
class _DictionaryStorage(_Storage):
def __init__(self):
self.data = {}
def __del__(self):
self.commit()
def commit(self):
pass
def get(self, key, default=None):
return self.data.get(key, default)
def setdefault(self, key, default=None):
return self.data.setdefault(key, default)
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key, value):
self.data[key] = value
self.commit()
def __delitem__(self, key):
del self.data[key]
class Memory(_DictionaryStorage):
pass
class YAML(_DictionaryStorage):
def __init__(self, filename="storage.yaml"):
super().__init__()
self.filename = filename
try:
with open(self.filename) as fd:
self.data = yaml.load(fd.read())
except FileNotFoundError:
pass
if not self.data:
self.data = {}
def commit(self):
with open(self.filename, "w") as fd:
fd.write(yaml.dump(self.data))
|
Use range instead of xrange | import os
import tempfile
from subprocess import call
class SlidePresenter(object):
def __init__(self):
pass
def present(self, slides):
for sno, slide in enumerate(slides):
with open(os.path.join(tempfile.gettempdir(), str(sno)+".md"), 'w') as f:
f.write(slide)
class VimPresenter(SlidePresenter):
def __init__(self, vim_rc_generator, vim_args=[]):
super(VimPresenter, self).__init__()
self.vim_args = vim_args
self.vim_rc_generator = vim_rc_generator
def withRC(self):
temp_rc = self.vim_rc_generator.generateFile()
self.vim_args += ['-u', temp_rc]
return self
def _get_command(self, num_slides):
self.withRC()
return ['vim'] + self.vim_args + [os.path.join(tempfile.gettempdir(), str(num)+".md") for num in range(num_slides)]
def present(self, slides):
super(VimPresenter, self).present(slides)
call(self._get_command(len(slides)))
class VimRCGenerator(object):
def __init__(self):
self.rc_string = "set nonu"
def generateFile(self):
temp_vimrc = os.path.join(tempfile.gettempdir(), 'rand.vimrc')
with open(temp_vimrc, 'w') as f:
f.write(self.rc_string)
return temp_vimrc
| import os
import tempfile
from subprocess import call
class SlidePresenter(object):
def __init__(self):
pass
def present(self, slides):
for sno, slide in enumerate(slides):
with open(os.path.join(tempfile.gettempdir(), str(sno)+".md"), 'w') as f:
f.write(slide)
class VimPresenter(SlidePresenter):
def __init__(self, vim_rc_generator, vim_args=[]):
super(VimPresenter, self).__init__()
self.vim_args = vim_args
self.vim_rc_generator = vim_rc_generator
def withRC(self):
temp_rc = self.vim_rc_generator.generateFile()
self.vim_args += ['-u', temp_rc]
return self
def _get_command(self, num_slides):
self.withRC()
return ['vim'] + self.vim_args + [os.path.join(tempfile.gettempdir(), str(num)+".md") for num in xrange(num_slides)]
def present(self, slides):
super(VimPresenter, self).present(slides)
call(self._get_command(len(slides)))
class VimRCGenerator(object):
def __init__(self):
self.rc_string = "set nonu"
def generateFile(self):
temp_vimrc = os.path.join(tempfile.gettempdir(), 'rand.vimrc')
with open(temp_vimrc, 'w') as f:
f.write(self.rc_string)
return temp_vimrc
|
Include template snippets and retab code | <!DOCTYPE html>
<html <?php language_attributes(); ?> class="no-js no-svg">
<head>
<meta charset="<?php bloginfo('charset'); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="profile" href="http://gmpg.org/xfn/11">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
<div class="container-bg">
<div class="<?php
if (is_home()) : echo 'container';
else : echo 'container-fluid';
endif;
?>">
<header class="main-navbar content-block">
<div class="row">
<div class="col-sm-3 col-md-4 col-lg-3">
<?php get_template_part(SNIPPETS_DIR . '/header/logo'); ?>
</div>
<div class="col-sm-9 col-md-8 col-lg-9">
<?php get_template_part(SNIPPETS_DIR . '/navigation/main', 'menu'); ?>
</div>
</div>
</header>
</div>
</div>
<?php get_template_part(SNIPPETS_DIR . '/navigation/breadcrumb'); ?>
<?php
if (is_home()):
get_template_part(SNIPPETS_DIR . '/header/hero');
endif; | <!DOCTYPE html>
<html <?php language_attributes(); ?> class="no-js no-svg">
<head>
<meta charset="<?php bloginfo('charset'); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="profile" href="http://gmpg.org/xfn/11">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
<div class="container-bg">
<div class="<?php
if (is_home()) : echo 'container';
else : echo 'container-fluid';
endif;
?>">
<header class="main-navbar content-block">
<div class="row">
<div class="col-sm-3 col-md-4 col-lg-3">
<?php get_template_part('templates/header/logo'); ?>
</div>
<div class="col-sm-9 col-md-8 col-lg-9">
<?php get_template_part('templates/navigation/main', 'menu'); ?>
</div>
</div>
</header>
</div>
</div>
<?php
if (is_home()):
get_template_part('templates/header/hero');
endif; |
Add semver version limit due to compat changes
The semver library stopped working for legacy Python versions after the
2.9.1 release. This adds a less than 2.10 restriction to the abstract
dependency requirements so that folks don't need to all add a pin to
their requirements.txt. | """Setuptools configuration for rpmvenv."""
from setuptools import setup
from setuptools import find_packages
with open('README.rst', 'r') as readmefile:
README = readmefile.read()
setup(
name='rpmvenv',
version='0.23.0',
url='https://github.com/kevinconway/rpmvenv',
description='RPM packager for Python virtualenv.',
author="Kevin Conway",
author_email="[email protected]",
long_description=README,
license='MIT',
packages=find_packages(exclude=['tests', 'build', 'dist', 'docs']),
install_requires=[
'jinja2',
'venvctrl',
'argparse',
'confpy',
'ordereddict',
'semver<2.10', # semver dropped support for legacy Python at 2.10.
],
entry_points={
'console_scripts': [
'rpmvenv = rpmvenv.cli:main',
],
'rpmvenv.extensions': [
'core = rpmvenv.extensions.core:Extension',
'file_permissions = rpmvenv.extensions.files.permissions:Extension',
'file_extras = rpmvenv.extensions.files.extras:Extension',
'python_venv = rpmvenv.extensions.python.venv:Extension',
'blocks = rpmvenv.extensions.blocks.generic:Extension',
]
},
package_data={
"rpmvenv": ["templates/*"],
},
)
| """Setuptools configuration for rpmvenv."""
from setuptools import setup
from setuptools import find_packages
with open('README.rst', 'r') as readmefile:
README = readmefile.read()
setup(
name='rpmvenv',
version='0.23.0',
url='https://github.com/kevinconway/rpmvenv',
description='RPM packager for Python virtualenv.',
author="Kevin Conway",
author_email="[email protected]",
long_description=README,
license='MIT',
packages=find_packages(exclude=['tests', 'build', 'dist', 'docs']),
install_requires=[
'jinja2',
'venvctrl',
'argparse',
'confpy',
'ordereddict',
'semver',
],
entry_points={
'console_scripts': [
'rpmvenv = rpmvenv.cli:main',
],
'rpmvenv.extensions': [
'core = rpmvenv.extensions.core:Extension',
'file_permissions = rpmvenv.extensions.files.permissions:Extension',
'file_extras = rpmvenv.extensions.files.extras:Extension',
'python_venv = rpmvenv.extensions.python.venv:Extension',
'blocks = rpmvenv.extensions.blocks.generic:Extension',
]
},
package_data={
"rpmvenv": ["templates/*"],
},
)
|
Update Axe Cop plugin for 1.7.9 compatibility | <?php
class Af_AxeCop extends Plugin {
function about() {
return array(0.1, "Fetch image from the Axe Cop webcomic", "Markus Wiik");
}
function init($host) {
$host->add_hook($host::HOOK_ARTICLE_FILTER, $this);
}
function hook_article_filter($article) {
$owner_uid = $article["owner_uid"];
if (strpos($article["link"], "axecop.com") !== FALSE) {
if (strpos($article["plugin_data"], "axecop,$owner_uid:") === FALSE) {
$url = parse_url($article["link"]);
$matches = array();
$result = preg_match("/episode_([0-9]+)\/$/", $url["path"], $matches);
if ($result === FALSE || $result == 0) {
return $article;
}
$image_name = "axecop" . $matches[1] . ".jpg";
$image_path = "/images/uploads/" . $image_name;
$article["content"] = '<img src="http://' . $url["host"] . '/' . $image_path . '"/>';
$article["plugin_data"] = "axecop,$owner_uid:" . $article["plugin_data"];
}
else if (isset($article["stored"]["content"])) {
$article["content"] = $article["stored"]["content"];
}
}
return $article;
}
function api_version() {
return 2;
}
}
?>
| <?php
class Af_AxeCop extends Plugin {
function about() {
return array(0.1, "Fetch image from the Axe Cop webcomic", "Markus Wiik");
}
function init($host) {
$host->add_hook($host::HOOK_ARTICLE_FILTER, $this);
}
function hook_article_filter($article) {
$owner_uid = $article["owner_uid"];
if (strpos($article["link"], "axecop.com") !== FALSE) {
if (strpos($article["plugin_data"], "axecop,$owner_uid:") === FALSE) {
$url = parse_url($article["link"]);
$matches = array();
$result = preg_match("/episode_([0-9]+)\/$/", $url["path"], $matches);
if ($result === FALSE || $result == 0) {
return $article;
}
$image_name = "axecop" . $matches[1] . ".jpg";
$image_path = "/images/uploads/" . $image_name;
$article["content"] = '<img src="http://' . $url["host"] . '/' . $image_path . '"/>';
$article["plugin_data"] = "axecop,$owner_uid:" . $article["plugin_data"];
}
else if (isset($article["stored"]["content"])) {
$article["content"] = $article["stored"]["content"];
}
}
return $article;
}
}
?>
|
Remove unecessary imported component makeStyles | import React from 'react'
import { Box, Grid, Typography, Card, CardContent } from '@material-ui/core'
import { Edit, Delete } from '@material-ui/icons'
export default function TravelObject(props) {
let content = null;
switch (props.type) {
case 'event':
content = <Typography variant="h4" gutterBottom>Event!</Typography>
break;
case 'flight':
content = <Typography variant="h4" gutterBottom>Flight!</Typography>
break;
case 'hotel':
content = <Typography variant="h4" gutterBottom>Hotel!</Typography>
break;
default:
console.log("Invalid type");
break;
}
return (
<Card>
<CardContent>
<Grid container direction="row" justify="flex-end" alignItems="center">
<Box mr={10} width="100%" height="100%">
{content}
</Box>
<Grid item>
<Grid container direction="column">
<Edit
onClick={() => console.log("editing")}
/>
<Delete
onClick={() => console.log("deleting")}
/>
</Grid>
</Grid>
</Grid>
</CardContent>
</Card>
)
} | import React from 'react'
import { Box, Grid, Typography, Card, CardContent } from '@material-ui/core'
import { makeStyles } from '@material-ui/core/styles'
import { Edit, Delete } from '@material-ui/icons'
export default function TravelObject(props) {
let content = null;
switch (props.type) {
case 'event':
content = <Typography variant="h4" gutterBottom>Event!</Typography>
break;
case 'flight':
content = <Typography variant="h4" gutterBottom>Flight!</Typography>
break;
case 'hotel':
content = <Typography variant="h4" gutterBottom>Hotel!</Typography>
break;
default:
console.log("Invalid type");
break;
}
return (
<Card>
<CardContent>
<Grid container direction="row" justify="flex-end" alignItems="center">
<Box mr={10} width="100%" height="100%">
{content}
</Box>
<Grid item>
<Grid container direction="column">
<Edit
onClick={() => console.log("editing")}
/>
<Delete
onClick={() => console.log("deleting")}
/>
</Grid>
</Grid>
</Grid>
</CardContent>
</Card>
)
} |
Set default lambda value to 0 | #!/usr/bin/python3
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
import numpy as np
DATASET_PATH = 'data/fashion'
def load_dataset():
"""Loads fashion dataset
Returns:
Datasets object
"""
data = input_data.read_data_sets(DATASET_PATH, one_hot=True)
return data
def get_hparams(hparams_str):
"""Parses hparams_str to HParams object.
Arguments:
hparams_str: String of comma separated param=value pairs.
Returns:
hparams: tf.contrib.training.HParams object from hparams_str. If
hparams_str is None, then a default HParams object is returned.
"""
hparams = tf.contrib.training.HParams(learning_rate=0.001, conv1_depth=32, conv2_depth=128,
dense_layer_units=1024, batch_size=128,
keep_prob=0.5, lambd=0.0, num_epochs=1, augment_percent=0.0)
if hparams_str:
hparams.parse(hparams_str)
return hparams
def shuffle_dataset(images, labels):
num_examples = images.shape[0]
permutation = list(np.random.permutation(num_examples))
return (images[permutation, :], labels[permutation, :])
| #!/usr/bin/python3
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
import numpy as np
DATASET_PATH = 'data/fashion'
def load_dataset():
"""Loads fashion dataset
Returns:
Datasets object
"""
data = input_data.read_data_sets(DATASET_PATH, one_hot=True)
return data
def get_hparams(hparams_str):
"""Parses hparams_str to HParams object.
Arguments:
hparams_str: String of comma separated param=value pairs.
Returns:
hparams: tf.contrib.training.HParams object from hparams_str. If
hparams_str is None, then a default HParams object is returned.
"""
hparams = tf.contrib.training.HParams(learning_rate=0.001, conv1_depth=32, conv2_depth=128,
dense_layer_units=1024, batch_size=128,
keep_prob=0.5, lambd=0.01, num_epochs=1, augment_percent=0.0)
if hparams_str:
hparams.parse(hparams_str)
return hparams
def shuffle_dataset(images, labels):
num_examples = images.shape[0]
permutation = list(np.random.permutation(num_examples))
return (images[permutation, :], labels[permutation, :])
|
Check that fullpath is a regular file before continuing | # This file is part of the File Deduper project. It is subject to
# the the revised 3-clause BSD license terms as set out in the LICENSE
# file found in the top-level directory of this distribution. No part of this
# project, including this file, may be copied, modified, propagated, or
# distributed except according to the terms contained in the LICENSE fileself.
import os
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
from .models import ImageFile
from .util import Util
def ScanFiles(session, FOLDER):
for root, dirs, files in os.walk(FOLDER):
if root.split('/')[-1].startswith('.'):
continue
for count, filename in enumerate(files, start=1):
if filename.startswith('.'):
continue
fullpath = os.path.join(root, filename)
if not os.path.isfile(fullpath):
continue
if Util.file_record_exists(session, fullpath):
print('{count} of {length}: Skipping {filename}'.format(
count=count, length=len(files), filename=filename))
else:
print('{count} of {length}: Processing {filename}'.format(
count=count, length=len(files), filename=filename))
new_file = ImageFile(name=filename, fullpath=fullpath,
filehash=Util.hash_file(fullpath))
session.add(new_file)
session.commit()
session.close()
| # This file is part of the File Deduper project. It is subject to
# the the revised 3-clause BSD license terms as set out in the LICENSE
# file found in the top-level directory of this distribution. No part of this
# project, including this file, may be copied, modified, propagated, or
# distributed except according to the terms contained in the LICENSE fileself.
import os
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
from .models import ImageFile
from .util import Util
def ScanFiles(session, FOLDER):
for root, dirs, files in os.walk(FOLDER):
if root.split('/')[-1].startswith('.'):
continue
for count, filename in enumerate(files, start=1):
if filename.startswith('.'):
continue
fullpath = os.path.join(root, filename)
if Util.file_record_exists(session, fullpath):
print('{count} of {length}: Skipping {filename}'.format(
count=count, length=len(files), filename=filename))
else:
print('{count} of {length}: Processing {filename}'.format(
count=count, length=len(files), filename=filename))
new_file = ImageFile(name=filename, fullpath=fullpath,
filehash=Util.hash_file(fullpath))
session.add(new_file)
session.commit()
session.close()
|
Add access to list of elements | package com.grayben.riskExtractor.htmlScorer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ScoredText {
private List<ScoredTextElement> text;
public ScoredText() {
super();
text = new ArrayList<>();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (ScoredTextElement element : text) {
sb.append(element.getTextElement());
sb.append(" ");
}
return sb.toString().trim();
}
public void add(ScoredTextElement st) {
if(st.getScores() == null){
throw new NullPointerException(
"param.getScores() must not be null"
);
}
if(st.getScores().isEmpty()){
throw new IllegalArgumentException(
"param.getScores() must not be empty"
);
}
if(st.getTextElement() == null){
throw new NullPointerException(
"param.getTextElement() must not be null"
);
}
if(st.getTextElement().isEmpty()){
throw new IllegalArgumentException(
"param.getTextElement() must not be empty"
);
}
text.add(st);
}
public List<ScoredTextElement> getList(){
return Collections.unmodifiableList(this.text);
}
}
| package com.grayben.riskExtractor.htmlScorer;
import java.util.ArrayList;
import java.util.List;
public class ScoredText {
private List<ScoredTextElement> text;
public ScoredText() {
super();
text = new ArrayList<>();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (ScoredTextElement element : text) {
sb.append(element.getTextElement());
sb.append(" ");
}
return sb.toString().trim();
}
public void add(ScoredTextElement st) {
if(st.getScores() == null){
throw new NullPointerException(
"param.getScores() must not be null"
);
}
if(st.getScores().isEmpty()){
throw new IllegalArgumentException(
"param.getScores() must not be empty"
);
}
if(st.getTextElement() == null){
throw new NullPointerException(
"param.getTextElement() must not be null"
);
}
if(st.getTextElement().isEmpty()){
throw new IllegalArgumentException(
"param.getTextElement() must not be empty"
);
}
text.add(st);
}
}
|
Refactor occurrence of name to description | package seedu.emeraldo.model.task;
import seedu.emeraldo.commons.exceptions.IllegalValueException;
/**
* Represents a Task's description in Emeraldo.
* Guarantees: immutable; is valid as declared in {@link #isValidDescription(String)}
*/
public class Description {
public static final String MESSAGE_DESCRIPTION_CONSTRAINTS = "Task description can contain anything except for \"";
public static final String DESCRIPTION_VALIDATION_REGEX = "[^\"]+";
public final String fullDescription;
/**
* Validates given description.
*
* @throws IllegalValueException if given description string is invalid.
*/
public Description(String description) throws IllegalValueException {
assert description != null;
description = description.trim();
if(description.isEmpty()){
this.fullDescription = "";
}
else if (!isValidDescription(description)) {
throw new IllegalValueException(MESSAGE_DESCRIPTION_CONSTRAINTS);
}
else{
this.fullDescription = description;
}
}
/**
* Returns true if a given string is a valid task description.
*/
public static boolean isValidDescription(String test) {
return test.matches(DESCRIPTION_VALIDATION_REGEX);
}
@Override
public String toString() {
return fullDescription;
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof Description // instanceof handles nulls
&& this.fullDescription.equals(((Description) other).fullDescription)); // state check
}
@Override
public int hashCode() {
return fullDescription.hashCode();
}
}
| package seedu.emeraldo.model.task;
import seedu.emeraldo.commons.exceptions.IllegalValueException;
/**
* Represents a Task's description in Emeraldo.
* Guarantees: immutable; is valid as declared in {@link #isValidDescription(String)}
*/
public class Description {
public static final String MESSAGE_NAME_CONSTRAINTS = "Task description should be spaces or alphanumeric characters";
public static final String NAME_VALIDATION_REGEX = "[\\p{Alnum} ]+";
public final String fullDescription;
/**
* Validates given description.
*
* @throws IllegalValueException if given description string is invalid.
*/
public Description(String description) throws IllegalValueException {
assert description != null;
description = description.trim();
if(description.isEmpty()){
this.fullDescription = "";
}
else if (!isValidDescription(description)) {
throw new IllegalValueException(MESSAGE_NAME_CONSTRAINTS);
}
else{
this.fullDescription = description;
}
}
/**
* Returns true if a given string is a valid task description.
*/
public static boolean isValidDescription(String test) {
return test.matches(NAME_VALIDATION_REGEX);
}
@Override
public String toString() {
return fullDescription;
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof Description // instanceof handles nulls
&& this.fullDescription.equals(((Description) other).fullDescription)); // state check
}
@Override
public int hashCode() {
return fullDescription.hashCode();
}
}
|
Enable the user confirmation by default | <?php
return [
'route' => [
'prefix' => 'authorization',
],
'database' => [
'connection' => config('database.default'),
],
'users' => [
'table' => 'users',
'model' => Arcanesoft\Auth\Models\User::class,
],
'roles' => [
'table' => 'roles',
'model' => Arcanesoft\Auth\Models\Role::class,
],
'permissions' => [
'table' => 'permissions',
'model' => Arcanesoft\Auth\Models\Permission::class,
],
'user-confirmation' => [
'enabled' => true,
'length' => 30,
],
'throttles' => [
'enabled' => true,
'table' => 'throttles',
],
'slug-separator' => '.',
'seeds' => [
'users' => [
[
'username' => 'admin',
'email' => env('ADMIN_USER_EMAIL', '[email protected]'),
'password' => env('ADMIN_USER_PASSWORD', 'password'),
],
],
],
];
| <?php
return [
'route' => [
'prefix' => 'authorization',
],
'database' => [
'connection' => config('database.default'),
],
'users' => [
'table' => 'users',
'model' => Arcanesoft\Auth\Models\User::class,
],
'roles' => [
'table' => 'roles',
'model' => Arcanesoft\Auth\Models\Role::class,
],
'permissions' => [
'table' => 'permissions',
'model' => Arcanesoft\Auth\Models\Permission::class,
],
'user-confirmation' => [
'enabled' => false,
'length' => 30,
],
'throttles' => [
'enabled' => true,
'table' => 'throttles',
],
'slug-separator' => '.',
'seeds' => [
'users' => [
[
'username' => 'admin',
'email' => env('ADMIN_USER_EMAIL', '[email protected]'),
'password' => env('ADMIN_USER_PASSWORD', 'password'),
],
],
],
];
|
Add esdoc documentation and change the github change job to run once an hour | /** @ignore */
const Job = require('./Job');
/** @ignore */
const request = require('request');
/**
* Github change job, this job runs once an hour, every cycle
* the job will fetch the latest commits from the public
* github repository and store them in the file cache.
*
* @extends {Job}
*/
class GithubChangeJob extends Job {
/**
* The jobs constructor, this will check if the cache
* already exists, if it doesn't it will create
* it by calling the run method.
*/
constructor() {
super();
if (! app.cache.has('github.commits')) {
this.run();
}
}
/**
* This method determines when the job should be execcuted.
*
* @param {RecurrenceRule} rule A node-schedule CRON recurrence rule instance
* @return {mixed}
*/
runCondition(rule) {
return '0 * * * *';
}
/**
* The jobs main logic method, this method is executed
* whenever the {#runCondition()} method returns true.
*
* @override
*/
run() {
request({
headers: { 'User-Agent': 'AvaIre-Discord-Bot' },
url: 'https://api.github.com/repos/senither/AvaIre/commits',
method: 'GET'
}, function (error, response, body) {
if (! error && response.statusCode === 200) {
try {
let parsed = JSON.parse(body);
app.cache.forever('github.commits', parsed);
} catch (e) {
app.logger.error('Github Changes job: The API returned an unconventional response.');
app.logger.error(e);
}
}
})
}
}
module.exports = GithubChangeJob;
| /** @ignore */
const Job = require('./Job');
/** @ignore */
const request = require('request');
class GithubChangeJob extends Job {
/**
* This method determines when the job should be execcuted.
*
* @param {RecurrenceRule} rule A node-schedule CRON recurrence rule instance
* @return {mixed}
*/
runCondition(rule) {
return '*/15 * * * *';
}
/**
* The jobs main logic method, this method is executed
* whenever the {#runCondition()} method returns true.
*
* @override
*/
run() {
request({
headers: { 'User-Agent': 'AvaIre-Discord-Bot' },
url: 'https://api.github.com/repos/senither/AvaIre/commits',
method: 'GET'
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
try {
let parsed = JSON.parse(body);
app.cache.forever('github.commits', parsed);
} catch (e) {
app.logger.error('Github Changes job: The API returned an unconventional response.');
app.logger.error(e);
}
}
})
}
}
module.exports = GithubChangeJob;
|
Stop hard-coding the navigation level in the extension | from django.utils.text import capfirst
from django.utils.translation import ugettext_lazy as _
from feincms.module.page.extensions.navigation import NavigationExtension, PagePretender
class ZivinetzNavigationExtension(NavigationExtension):
name = _('Zivinetz navigation extension')
def children(self, page, **kwargs):
url = page.get_navigation_url()
return [
PagePretender(
title=capfirst(_('drudges')),
url='%sdrudges/' % url,
level=page.level+1,
tree_id=page.tree_id,
),
PagePretender(
title=capfirst(_('regional offices')),
url='%sregional_offices/' % url,
level=page.level+1,
tree_id=page.tree_id,
),
PagePretender(
title=capfirst(_('scope statements')),
url='%sscope_statements/' % url,
level=page.level+1,
tree_id=page.tree_id,
),
PagePretender(
title=capfirst(_('assignments')),
url='%sassignments/' % url,
level=page.level+1,
tree_id=page.tree_id,
),
PagePretender(
title=capfirst(_('expense reports')),
url='%sexpense_reports/' % url,
level=page.level+1,
tree_id=page.tree_id,
),
]
| from django.utils.text import capfirst
from django.utils.translation import ugettext_lazy as _
from feincms.module.page.extensions.navigation import NavigationExtension, PagePretender
class ZivinetzNavigationExtension(NavigationExtension):
name = _('Zivinetz navigation extension')
def children(self, page, **kwargs):
url = page.get_navigation_url()
return [
PagePretender(
title=capfirst(_('drudges')),
url='%sdrudges/' % url,
level=3,
tree_id=page.tree_id,
),
PagePretender(
title=capfirst(_('regional offices')),
url='%sregional_offices/' % url,
level=3,
tree_id=page.tree_id,
),
PagePretender(
title=capfirst(_('scope statements')),
url='%sscope_statements/' % url,
level=3,
tree_id=page.tree_id,
),
PagePretender(
title=capfirst(_('assignments')),
url='%sassignments/' % url,
level=3,
tree_id=page.tree_id,
),
PagePretender(
title=capfirst(_('expense reports')),
url='%sexpense_reports/' % url,
level=3,
tree_id=page.tree_id,
),
]
|
Adjust deleting cascade for planned liquid transfers | """
Planned worklist member table.
"""
from sqlalchemy import Column
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import Table
from sqlalchemy.schema import PrimaryKeyConstraint
__docformat__ = 'reStructuredText en'
__all__ = ['create_table']
def create_table(metadata, planned_worklist_tbl, planned_liquid_transfer_tbl):
"Table factory."
tbl = Table('planned_worklist_member', metadata,
Column('planned_worklist_id', Integer,
ForeignKey(planned_worklist_tbl.c.planned_worklist_id,
onupdate='CASCADE', ondelete='CASCADE'),
nullable=False),
Column('planned_liquid_transfer_id', Integer,
ForeignKey(planned_liquid_transfer_tbl.c.\
planned_liquid_transfer_id,
onupdate='CASCADE', ondelete='NO ACTION'),
nullable=False),
)
PrimaryKeyConstraint(tbl.c.planned_worklist_id,
tbl.c.planned_liquid_transfer_id)
return tbl
| """
Planned worklist member table.
"""
from sqlalchemy import Column
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import Table
from sqlalchemy.schema import PrimaryKeyConstraint
__docformat__ = 'reStructuredText en'
__all__ = ['create_table']
def create_table(metadata, planned_worklist_tbl, planned_liquid_transfer_tbl):
"Table factory."
tbl = Table('planned_worklist_member', metadata,
Column('planned_worklist_id', Integer,
ForeignKey(planned_worklist_tbl.c.planned_worklist_id,
onupdate='CASCADE', ondelete='CASCADE'),
nullable=False),
Column('planned_liquid_transfer_id', Integer,
ForeignKey(planned_liquid_transfer_tbl.c.\
planned_liquid_transfer_id,
onupdate='CASCADE', ondelete='CASCADE'),
nullable=False),
)
PrimaryKeyConstraint(tbl.c.planned_worklist_id,
tbl.c.planned_liquid_transfer_id)
return tbl
|
Use helpers instead of facade | <?php
namespace Lio\Exceptions;
use Bugsnag;
use Exception;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Bugsnag\BugsnagLaravel\BugsnagExceptionHandler as ExceptionHandler;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
HttpException::class,
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $e
* @return void
*/
public function report(Exception $e)
{
// If a user is logged in, we'll set him as the target user for which the errors will occur.
if (auth()->check()) {
Bugsnag::setUser([
'name' => auth()->user()->name,
'email' => auth()->user()->email,
]);
}
return parent::report($e);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
return parent::render($request, $e);
}
}
| <?php
namespace Lio\Exceptions;
use Auth;
use Bugsnag;
use Exception;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Bugsnag\BugsnagLaravel\BugsnagExceptionHandler as ExceptionHandler;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
HttpException::class,
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $e
* @return void
*/
public function report(Exception $e)
{
// If a user is logged in, we'll set him as the target user for which the errors will occur.
if (Auth::check()) {
Bugsnag::setUser([
'name' => Auth::user()->name,
'email' => Auth::user()->email,
]);
}
return parent::report($e);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
return parent::render($request, $e);
}
}
|
Add back unknown platform type | 'use strict'
module.exports = function (sequelize, DataTypes) {
let Rescue = sequelize.define('Rescue', {
id: {
type: DataTypes.UUID,
primaryKey: true,
defaultValue: DataTypes.UUIDV4
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: true
},
client: {
type: DataTypes.STRING,
allowNull: true
},
codeRed: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},
data: {
type: DataTypes.JSONB,
allowNull: true
},
epic: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},
open: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: true
},
notes: {
type: DataTypes.TEXT,
allowNull: false,
defaultValue: ''
},
platform: {
type: DataTypes.ENUM('xb', 'pc', 'unknown'),
allowNull: true,
defaultValue: 'pc'
},
quotes: {
type: DataTypes.ARRAY(DataTypes.STRING),
allowNull: false
},
successful: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},
system: {
type: DataTypes.STRING,
allowNull: false,
defaultValue: ''
}
}, {
classMethods: {
associate: function (models) {
Rescue.belongsToMany(models.Rat, { as: 'rats', through: 'RescueRats' })
Rescue.belongsTo(models.Rat, { as: 'firstLimpet' })
}
}
})
return Rescue
}
| 'use strict'
module.exports = function (sequelize, DataTypes) {
let Rescue = sequelize.define('Rescue', {
id: {
type: DataTypes.UUID,
primaryKey: true,
defaultValue: DataTypes.UUIDV4
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: true
},
client: {
type: DataTypes.STRING,
allowNull: true
},
codeRed: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},
data: {
type: DataTypes.JSONB,
allowNull: true
},
epic: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},
open: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: true
},
notes: {
type: DataTypes.TEXT,
allowNull: false,
defaultValue: ''
},
platform: {
type: DataTypes.ENUM('xb', 'pc'),
allowNull: true,
defaultValue: 'pc'
},
quotes: {
type: DataTypes.ARRAY(DataTypes.STRING),
allowNull: false
},
successful: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},
system: {
type: DataTypes.STRING,
allowNull: false,
defaultValue: ''
}
}, {
classMethods: {
associate: function (models) {
Rescue.belongsToMany(models.Rat, { as: 'rats', through: 'RescueRats' })
Rescue.belongsTo(models.Rat, { as: 'firstLimpet' })
}
}
})
return Rescue
}
|
Put back changes in observer after unsuccessful commit. | const expect = require('chai').expect;
import { TopicObserver } from "../topic-observer";
describe('topic observer', () => {
const observer = new TopicObserver();
const fn1 = () => {};
it('should observe all', function() {
observer.observe(fn1);
expect(observer.observers['__all__'].length).to.equal(1)
});
it('should remove all', function() {
observer.remove(fn1);
expect(observer.observers['__all__'].length).to.equal(0);
});
it('should receive all', function () {
let subscriberHasBeenCalled = false;
const fn2 = (data) => subscriberHasBeenCalled = data;
observer.observe(fn2);
observer.broadcast(true);
expect(subscriberHasBeenCalled).to.equal(true);
observer.remove(fn2);
});
const fn3 = () => {};
it('should observe topic', function() {
observer.observe(fn3, 'topic');
expect(observer.observers['topic'].length).to.equal(1)
});
it('should remove topic', function() {
observer.remove(fn3, 'topic');
expect(observer.observers['topic'].length).to.equal(0);
});
it('should receive topic', function () {
let subscriberHasBeenCalled = false;
const fn4 = (data) => subscriberHasBeenCalled = data;
observer.observe(fn4, 'topic');
observer.broadcast(true);
expect(subscriberHasBeenCalled).to.equal(true);
observer.observe(fn4, 'topic');
});
});
| const expect = require('chai').expect;
import { TopicObserver } from "../topic-observer";
describe('topic observer', () => {
const observer = new TopicObserver();
const fn1 = () => {};
it('should observe all', function() {
observer.observe(fn1);
expect(observer.observers['__all__'].length).to.equal(1)
});
it('should remove all', function() {
observer.remove(fn1);
expect(observer.observers['__all__'].length).to.equal(0);
});
it('should receive all', function () {
let subscriberHasBeenCalled = false;
const fn2 = (data) => subscriberHasBeenCalled = data;
observer.observe(fn2);
observer.broadcast(true);
expect(subscriberHasBeenCalled).to.equal(true);
observer.remove(fn2);
});
const fn3 = () => {};
it('should observe topic', function() {
observer.observe(fn3, 'topic');
expect(observer.observers['topic'].length).to.equal(1)
});
it('should remove topic', function() {
observer.remove(fn3);
expect(observer.observers['topic'].length).to.equal(0);
});
it('should receive topic', function () {
let subscriberHasBeenCalled = false;
const fn4 = (data) => subscriberHasBeenCalled = data;
observer.observe(fn4, 'topic');
observer.broadcast(true);
expect(subscriberHasBeenCalled).to.equal(true);
observer.observe(fn4, 'topic');
});
});
|
Add random key to generated nodes to simple get same it or not | beforeEach(function() {
function genViewHTML(id, view) {
var html = '';
var clazz = 'ns-view-' + id;
if (view.async) {
clazz += ' ns-async';
}
if (view.collection) {
clazz += ' ns-view-container-desc';
}
if (view.placeholder) {
clazz += ' ns-view-placeholder';
}
html += '<div class="' + clazz + '" data-key="' + view.key + '" data-random="' + Math.random() + '">';
// don't create child views in async state
if (!view.async) {
html += genHTML(view.views);
}
html += '</div>';
return html;
}
function genHTML(views) {
var html = '';
for (var id in views) {
var view = views[id];
// collection
if (Array.isArray(view)) {
view.forEach(function(collectionItem) {
html += genViewHTML(id, collectionItem);
});
} else {
html += genViewHTML(id, view);
}
}
return html;
}
sinon.stub(ns, 'tmpl', function(json) {
return ns.html2node('<div class="root">' + genHTML(json.views) + '</div>');
});
});
afterEach(function() {
ns.tmpl.restore();
});
| beforeEach(function() {
function genViewHTML(id, view) {
var html = '';
var clazz = 'ns-view-' + id;
if (view.async) {
clazz += ' ns-async';
}
if (view.collection) {
clazz += ' ns-view-container-desc';
}
if (view.placeholder) {
clazz += ' ns-view-placeholder';
}
html += '<div class="' + clazz + '" data-key="' + view.key + '">';
// don't create child views in async state
if (!view.async) {
html += genHTML(view.views);
}
html += '</div>';
return html;
}
function genHTML(views) {
var html = '';
for (var id in views) {
var view = views[id];
// collection
if (Array.isArray(view)) {
view.forEach(function(collectionItem) {
html += genViewHTML(id, collectionItem);
});
} else {
html += genViewHTML(id, view);
}
}
return html;
}
sinon.stub(ns, 'tmpl', function(json) {
return ns.html2node('<div class="root">' + genHTML(json.views) + '</div>');
});
});
afterEach(function() {
ns.tmpl.restore();
});
|
Subsets and Splits