text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Add ASTTransformer and StaticFilterCompiler to adapter API
ASTTransformer can be used by adapters which transform filter AST before
processing, e.g. the InfluxDB adapter.
StaticFilterCompiler is the new base class for filter compilers. | 'use strict';
let juttle_utils = require('../runtime/juttle-utils');
//
// The AdapterAPI is the exported interface to the juttle compiler / runtime
// that is expected to be used by all adapters.
//
// The version field corresponds to the juttle version in which the latest
// changes were made to the adapter API.
//
let AdapterAPI = {
version: '0.5.0',
AdapterRead: require('./adapter-read'),
AdapterWrite: require('./adapter-write'),
compiler: {
ASTVisitor: require('../compiler/ast-visitor'),
ASTTransformer: require('../compiler/ast-transformer'),
StaticFilterCompiler: require('../compiler/filters/static-filter-compiler'),
FilterJSCompiler: require('../compiler/filters/filter-js-compiler'),
},
errors: require('../errors'),
getLogger: require('../logger').getLogger,
runtime: {
values: require('../runtime/values'),
toNative: juttle_utils.toNative,
parseTime: juttle_utils.parseTime,
reducerDefaultValue: require('../runtime/reducers').default_value
},
types: require('../runtime/types')
};
module.exports = AdapterAPI;
| 'use strict';
let juttle_utils = require('../runtime/juttle-utils');
//
// The AdapterAPI is the exported interface to the juttle compiler / runtime
// that is expected to be used by all adapters.
//
// The version field corresponds to the juttle version in which the latest
// changes were made to the adapter API.
//
let AdapterAPI = {
version: '0.5.0',
AdapterRead: require('./adapter-read'),
AdapterWrite: require('./adapter-write'),
compiler: {
ASTVisitor: require('../compiler/ast-visitor'),
FilterJSCompiler: require('../compiler/filters/filter-js-compiler')
},
errors: require('../errors'),
getLogger: require('../logger').getLogger,
runtime: {
values: require('../runtime/values'),
toNative: juttle_utils.toNative,
parseTime: juttle_utils.parseTime,
reducerDefaultValue: require('../runtime/reducers').default_value
},
types: require('../runtime/types')
};
module.exports = AdapterAPI;
|
Increase pagination size for careeropportunity api | # -*- coding: utf-8 -*-
from django.shortcuts import render
from django.utils import timezone
# API v1
from rest_framework import mixins, viewsets
from rest_framework.permissions import AllowAny
from rest_framework.pagination import PageNumberPagination
from apps.careeropportunity.models import CareerOpportunity
from apps.careeropportunity.serializers import CareerSerializer
def index(request, id=None):
return render(request, 'careeropportunity/index.html')
class HundredItemsPaginator(PageNumberPagination):
page_size = 100
class CareerViewSet(viewsets.GenericViewSet, mixins.RetrieveModelMixin, mixins.ListModelMixin):
"""
Viewset for Career serializer
"""
queryset = CareerOpportunity.objects.filter(
start__lte=timezone.now(),
end__gte=timezone.now()
).order_by('-featured', '-start')
serializer_class = CareerSerializer
permission_classes = (AllowAny,)
pagination_class = HundredItemsPaginator
| # -*- coding: utf-8 -*-
from django.shortcuts import render
from django.utils import timezone
# API v1
from rest_framework import mixins, viewsets
from rest_framework.permissions import AllowAny
from apps.careeropportunity.models import CareerOpportunity
from apps.careeropportunity.serializers import CareerSerializer
def index(request, id=None):
return render(request, 'careeropportunity/index.html')
class CareerViewSet(viewsets.GenericViewSet, mixins.RetrieveModelMixin, mixins.ListModelMixin):
"""
Viewset for Career serializer
"""
queryset = CareerOpportunity.objects.filter(
start__lte=timezone.now(),
end__gte=timezone.now()
).order_by('-featured', '-start')
serializer_class = CareerSerializer
permission_classes = (AllowAny,)
|
Fix a busted import statement in our TemplateController | from myfedora.lib.base import *
class TemplateController(BaseController):
def view(self, url):
"""By default, the final controller tried to fulfill the request
when no other routes match. It may be used to display a template
when all else fails, e.g.::
def view(self, url):
return render('/%s' % url)
Or if you're using Mako and want to explicitly send a 404 (Not
Found) response code when the requested template doesn't exist::
import mako.exceptions
def view(self, url):
try:
return render('/%s' % url)
except mako.exceptions.TopLevelLookupException:
abort(404)
By default this controller aborts the request with a 404 (Not
Found)
"""
abort(404)
| from ${package}.lib.base import *
class TemplateController(BaseController):
def view(self, url):
"""By default, the final controller tried to fulfill the request
when no other routes match. It may be used to display a template
when all else fails, e.g.::
def view(self, url):
return render('/%s' % url)
Or if you're using Mako and want to explicitly send a 404 (Not
Found) response code when the requested template doesn't exist::
import mako.exceptions
def view(self, url):
try:
return render('/%s' % url)
except mako.exceptions.TopLevelLookupException:
abort(404)
By default this controller aborts the request with a 404 (Not
Found)
"""
abort(404)
|
Fix karma basePath option so coverage can be displayed in IntelliJ | // Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-phantomjs-launcher'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, 'coverage'),
reports: ['html', 'lcovonly'],
fixWebpackSourcePaths: true
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['ChromiumHeadless', 'PhantomJS'],
singleRun: false,
browserNoActivityTimeout: 100000
});
};
| // Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: 'test',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-phantomjs-launcher'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, 'coverage'),
reports: ['html', 'lcovonly'],
fixWebpackSourcePaths: true
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['ChromiumHeadless', 'PhantomJS'],
singleRun: false,
browserNoActivityTimeout: 100000
});
};
|
Bump version again as pip wont let me upload the same file twice | import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
INSTALL_REQUIREMENTS = ["Pillow"]
# Allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name = 'django-initialcon',
version = '0.1.6',
packages = ['initialcon'],
include_package_data = True,
license = 'MIT License',
description = 'A small django application for generating small colourful icons for users profile pictures',
long_description = README,
url = 'https://github.com/bettsmatt/django-initialcon',
author = 'Matthew Betts',
author_email = 'matt.je.betts@gmail.com',
classifiers =[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content'
]
)
| import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
INSTALL_REQUIREMENTS = ["Pillow"]
# Allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name = 'django-initialcon',
version = '0.1.5,
packages = ['initialcon'],
include_package_data = True,
license = 'MIT License',
description = 'A small django application for generating small colourful icons for users profile pictures',
long_description = README,
url = 'https://github.com/bettsmatt/django-initialcon',
author = 'Matthew Betts',
author_email = 'matt.je.betts@gmail.com',
classifiers =[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content'
]
)
|
Add debugContext action for wit.ai | 'use strict';
const Wit = require('node-wit').Wit;
const myActions = require('./my-wit-actions');
/**
* Handles wit.ai integration
* @param event
*/
const init = event => new Promise((resolveMessage, rejectMessage) => {
if (event.sender && event.sender.id && event.message && event.message.text) {
const sessionId = `${event.id}-${event.updated}`;
const context0 = {};
const actions = {
send: (request, response) => new Promise(() => {
resolveMessage(response);
}),
debugContext: (data) => new Promise((resolve, reject) => {
const context = data.context;
console.log('WIT.AI DEBUG:')
console.log(JSON.stringify(data, null, 2));
resolve(context);
})
};
// Copy custom actions to actions
Object.keys(myActions).map((value) => {
actions[value] = myActions[value];
});
const client = new Wit({
accessToken: process.env.WIT_AI_TOKEN,
actions: actions
});
client.runActions(sessionId, event.message.text, context0)
.then(result => resolveMessage(result))
.catch(error => rejectMessage(error));
} else {
rejectMessage('wit ai failed');
}
});
module.exports = init;
| 'use strict';
const Wit = require('node-wit').Wit;
const myActions = require('./my-wit-actions');
/**
* Handles wit.ai integration
* @param event
*/
const init = event => new Promise((resolveMessage, rejectMessage) => {
if (event.sender && event.sender.id && event.message && event.message.text) {
const sessionId = `${event.id}-${event.updated}`;
const context0 = {};
const actions = {
send: (request, response) => new Promise(() => {
resolveMessage(response);
})
};
// Copy custom actions to actions
Object.keys(myActions).map((value) => {
actions[value] = myActions[value];
});
const client = new Wit({
accessToken: process.env.WIT_AI_TOKEN,
actions: actions
});
client.runActions(sessionId, event.message.text, context0)
.then(result => resolveMessage(result))
.catch(error => rejectMessage(error));
} else {
rejectMessage('wit ai failed');
}
});
module.exports = init;
|
Fix GPS103 command unit test | package org.traccar.protocol;
import java.util.HashMap;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import org.traccar.model.Command;
public class Gps103ProtocolEncoderTest {
@Test
public void testDecode() throws Exception {
Gps103ProtocolEncoder encoder = new Gps103ProtocolEncoder();
Command command = new Command();
command.setDeviceId(1);
command.setType(Command.TYPE_POSITION_FIX);
Map<String, Object> other = new HashMap<>();
other.put(Command.KEY_FREQUENCY, 300l);
command.setOther(other);
Assert.assertEquals("**,imei:123456789012345,C,05m;", encoder.encodeCommand(command));
}
}
| package org.traccar.protocol;
import java.util.HashMap;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import org.traccar.model.Command;
public class Gps103ProtocolEncoderTest {
@Test
public void testDecode() throws Exception {
Gps103ProtocolEncoder encoder = new Gps103ProtocolEncoder();
Command command = new Command();
command.setDeviceId(1);
command.setType(Command.TYPE_POSITION_FIX);
Map<String, Object> other = new HashMap<>();
other.put(Command.KEY_FREQUENCY, 300l);
command.setOther(other);
Assert.assertEquals("**,123456789012345,C,05m;", encoder.encodeCommand(command));
}
}
|
Fix goto section at sidebar | import ServerboardView from 'app/components/project'
import store from 'app/utils/store'
import { projects_update_info } from 'app/actions/project'
var Project=store.connect({
state(state){
if (state.project.current != "/" && localStorage.last_project != state.project.current){
localStorage.last_project = state.project.current
}
return {
shortname: state.project.current,
project: state.project.project,
projects_count: (state.project.projects || []).length
}
},
handlers: (dispatch, props) => ({
goto(url){
console.log(url)
store.goto(url.pathname, url.state)
},
onAdd(){ dispatch( store.set_modal("project.add") ) },
onUpdate(){ dispatch( projects_update_info(props.params.project) ) }
}),
store_enter: (state, props) => [
() => projects_update_info(state.project.current),
],
store_exit: (state, props) => [
() => projects_update_info(),
],
subscriptions: ["service.updated"],
watch: ["shortname"]
}, ServerboardView)
export default Project
| import ServerboardView from 'app/components/project'
import store from 'app/utils/store'
import { projects_update_info } from 'app/actions/project'
var Project=store.connect({
state(state){
if (state.project.current != "/" && localStorage.last_project != state.project.current){
localStorage.last_project = state.project.current
}
return {
shortname: state.project.current,
project: state.project.project,
projects_count: (state.project.projects || []).length
}
},
handlers: (dispatch, props) => ({
goto(url){ dispatch( push(url) ) },
onAdd(){ dispatch( store.set_modal("project.add") ) },
onUpdate(){ dispatch( projects_update_info(props.params.project) ) }
}),
store_enter: (state, props) => [
() => projects_update_info(state.project.current),
],
store_exit: (state, props) => [
() => projects_update_info(),
],
subscriptions: ["service.updated"],
watch: ["shortname"]
}, ServerboardView)
export default Project
|
Fix initial query params not getting passed into recursive calls. | import Ember from 'ember';
export default function loadAll(model, relationship, dest, options = {}) {
var page = options.page || 1;
var query = {
'page[size]': 10,
page: page
};
query = Ember.merge(query, options || {});
return model.query(relationship, query).then(results => {
dest.pushObjects(results.toArray());
var total = results.meta.pagination.total;
var pageSize = results.meta.pagination.per_page;
var remaining = total - (page * pageSize);
if (remaining > 0) {
query.page = page + 1;
query['page[size]'] = pageSize;
return loadAll(model, relationship, dest, query);
}
});
}
| import Ember from 'ember';
export default function loadAll(model, relationship, dest, options = {}) {
var page = options.page || 1;
var query = {
'page[size]': 10,
page: page
};
query = Ember.merge(query, options || {});
return model.query(relationship, query).then(results => {
dest.pushObjects(results.toArray());
var total = results.meta.pagination.total;
var pageSize = results.meta.pagination.per_page;
var remaining = total - (page * pageSize);
if (remaining > 0) {
return loadAll(model, relationship, dest, {
'page[size]': pageSize,
page: page + 1
});
}
});
}
|
Return empty result rather than graphql error | import graphene
from django.http import Http404
from graphql import GraphQLError
from wagtail.core.models import Page
from . import types
class Query(graphene.ObjectType):
page = graphene.Field(types.Page, path=graphene.String())
all_pages = graphene.List(types.Page, path=graphene.String())
def resolve_page(self, info, **kwargs):
path = kwargs.get('path')
path = path[1:] if path.startswith('/') else path
path = path[:-1] if path.endswith('/') else path
root_page = info.context.site.root_page
try:
result = root_page.route(info.context, path.split('/'))
return result.page
except Http404:
return None
def resolve_all_pages(self, info):
return Page.objects.specific().live()
| import graphene
from django.http import Http404
from graphql import GraphQLError
from wagtail.core.models import Page
from . import types
class Query(graphene.ObjectType):
page = graphene.Field(types.Page, path=graphene.String())
all_pages = graphene.List(types.Page, path=graphene.String())
def resolve_page(self, info, **kwargs):
path = kwargs.get('path')
path = path[1:] if path.startswith('/') else path
path = path[:-1] if path.endswith('/') else path
root_page = info.context.site.root_page
try:
result = root_page.route(info.context, path.split('/'))
return result.page
except Http404:
raise GraphQLError(f'404: Page not found for {path}')
def resolve_all_pages(self, info):
return Page.objects.specific().live()
|
Fix global variable name for browser usage | (function(){
function random(a,b) {
return Math.floor(Math.random() * b) + a;
};
function obfuscateEmail(email) {
if (!email) return email;
var re = /^(.*)(@)(.*?)(\.)(.*)$/;
return email.replace(re, function(m,username,at,hostname,dot,tld) {
function obs(s) {
var a = [];
var n = s.length;
while (n--) {
if (random(0,3) !== 0) {
a.push('*');
} else {
a.push(s[s.length-1-n]);
}
}
return a.join('');
}
return obs(username) + at + obs(hostname) + dot + obs(tld);
});
}
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
module.exports = obfuscateEmail;
} else if (typeof exports !== 'undefined') {
exports.obfuscateEmail = obfuscateEmail;
} else {
window.obfuscateEmail = obfuscateEmail;
}
})();
| (function(){
function random(a,b) {
return Math.floor(Math.random() * b) + a;
};
function obfuscateEmail(email) {
if (!email) return email;
var re = /^(.*)(@)(.*?)(\.)(.*)$/;
return email.replace(re, function(m,username,at,hostname,dot,tld) {
function obs(s) {
var a = [];
var n = s.length;
while (n--) {
if (random(0,3) !== 0) {
a.push('*');
} else {
a.push(s[s.length-1-n]);
}
}
return a.join('');
}
return obs(username) + at + obs(hostname) + dot + obs(tld);
});
}
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
module.exports = obfuscateEmail;
} else if (typeof exports !== 'undefined') {
exports.obfuscateEmail = obfuscateEmail;
} else {
window.hasprop = obfuscateEmail;
}
})();
|
Move device/tenant profile entitiy type enums to the end of list. | /**
* Copyright Β© 2016-2020 The Thingsboard Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.thingsboard.server.common.data;
/**
* @author Andrew Shvayka
*/
public enum EntityType {
TENANT, CUSTOMER, USER, DASHBOARD, ASSET, DEVICE, ALARM, RULE_CHAIN, RULE_NODE, ENTITY_VIEW, WIDGETS_BUNDLE, WIDGET_TYPE, TENANT_PROFILE, DEVICE_PROFILE
}
| /**
* Copyright Β© 2016-2020 The Thingsboard Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.thingsboard.server.common.data;
/**
* @author Andrew Shvayka
*/
public enum EntityType {
TENANT, TENANT_PROFILE, CUSTOMER, USER, DASHBOARD, ASSET, DEVICE, DEVICE_PROFILE, ALARM, RULE_CHAIN, RULE_NODE, ENTITY_VIEW, WIDGETS_BUNDLE, WIDGET_TYPE
}
|
Test 2.11: Turn list into generator. | import random
import string
import unittest
from Crypto.Cipher import AES
import padlib
def encryption_oracle(input):
key = ''.join(random.sample(string.printable, 16))
mode = random.choice((AES.MODE_CBC, AES.MODE_ECB))
prepad = ''.join(random.sample(string.printable, random.randint(5, 10)))
sufpad = ''.join(random.sample(string.printable, random.randint(5, 10)))
if mode == AES.MODE_CBC:
iv = ''.join(random.sample(string.printable, 16))
cipher = AES.new(key, AES.MODE_CBC, iv)
else:
cipher = AES.new(key, AES.MODE_ECB)
plaintext = padlib.pad_pkcs7(prepad + input + sufpad, 16)
return cipher.encrypt(plaintext), mode
def solve():
plaintext = "a" * (16 * 10)
ciphertext, mode = encryption_oracle(plaintext)
block_cnt = len(ciphertext) // 16
blocks = (ciphertext[16*k : 16*(k+1)] for k in range(block_cnt))
s = set(blocks)
guess_mode = AES.MODE_ECB if len(s) < 5 else AES.MODE_CBC
return guess_mode == mode
class Test(unittest.TestCase):
def test_solve(self):
repetitions = 20
for i in range(repetitions):
self.assertTrue(solve())
| import random
import string
import unittest
from Crypto.Cipher import AES
import padlib
def encryption_oracle(input):
key = ''.join(random.sample(string.printable, 16))
mode = random.choice((AES.MODE_CBC, AES.MODE_ECB))
prepad = ''.join(random.sample(string.printable, random.randint(5, 10)))
sufpad = ''.join(random.sample(string.printable, random.randint(5, 10)))
if mode == AES.MODE_CBC:
iv = ''.join(random.sample(string.printable, 16))
cipher = AES.new(key, AES.MODE_CBC, iv)
else:
cipher = AES.new(key, AES.MODE_ECB)
plaintext = padlib.pad_pkcs7(prepad + input + sufpad, 16)
return cipher.encrypt(plaintext), mode
def solve():
plaintext = "a" * (16 * 10)
ciphertext, mode = encryption_oracle(plaintext)
block_cnt = len(ciphertext) // 16
blocks = [ciphertext[16*k : 16*(k+1)] for k in range(block_cnt)]
s = set(blocks)
guess_mode = AES.MODE_ECB if len(s) < 5 else AES.MODE_CBC
return guess_mode == mode
class Test(unittest.TestCase):
def test_solve(self):
repetitions = 20
for i in range(repetitions):
self.assertTrue(solve())
|
Check that the company is valid in select ajax | <!-- Company -->
<div id="{{ $fieldname }}" class="form-group{{ $errors->has($fieldname) ? ' has-error' : '' }}">
{{ Form::label($fieldname, $translated_name, array('class' => 'col-md-3 control-label')) }}
<div class="col-md-7">
<select class="js-data-ajax" data-endpoint="companies" name="{{ $fieldname }}" style="width: 100%" id="company_select">
@if ($company_id = Input::old($fieldname, (isset($item)) ? $item->{$fieldname} : ''))
<option value="{{ $company_id }}" selected="selected">
{{ (\App\Models\Company::find($company_id)) ? \App\Models\Company::find($company_id)->name : '' }}
</option>
@else
<option value="">{{ trans('general.select_company') }}</option>
@endif
</select>
</div>
{!! $errors->first($fieldname, '<div class="col-md-8 col-md-offset-3"><span class="alert-msg"><i class="fa fa-times"></i> :message</span></div>') !!}
</div>
| <!-- Company -->
<div id="{{ $fieldname }}" class="form-group{{ $errors->has($fieldname) ? ' has-error' : '' }}">
{{ Form::label($fieldname, $translated_name, array('class' => 'col-md-3 control-label')) }}
<div class="col-md-7">
<select class="js-data-ajax" data-endpoint="companies" name="{{ $fieldname }}" style="width: 100%" id="company_select">
@if ($company_id = Input::old($fieldname, (isset($item)) ? $item->{$fieldname} : ''))
<option value="{{ $company_id }}" selected="selected">
{{ \App\Models\Company::find($company_id)->name }}
</option>
@else
<option value="">{{ trans('general.select_company') }}</option>
@endif
</select>
</div>
{!! $errors->first($fieldname, '<div class="col-md-8 col-md-offset-3"><span class="alert-msg"><i class="fa fa-times"></i> :message</span></div>') !!}
</div>
|
Convert description in setup.py to rest format for better display in Cheeseshop
--HG--
extra : convert_revision : svn%3A77541ad4-5f01-0410-9ede-a1b63cd9a898/trunk%403340 | """TurboGears project related information"""
version = "2.0a1"
description = "Next generation TurboGears built on Pylons"
long_description="""
TurboGears brings together a variety of best of breed python tools
to create an easy to install, easy to use web megaframework.
It provides and integrated and well tested set of tools for
everything you need to build dynamic, database driven applications.
TurboGears 2 provides you with everything you need from the
javascript programming tools, like ToscaWidgets and automatic
JSON generation, to one of the world's most powerful Object
Relational Mappers (SQLAlchemy).
The latest development version is available in the
`TurboGears subversion repository`_.
.. _TurboGears subversion repository:
http://svn.turbogears.org/trunk#egg=turbogears-dev
"""
url="http://www.turbogears.org"
author='Alberto Valverde, Mark Ramm'
email = "alberto@toscat.net, mark.ramm@gmail.com"
copyright = """Copyright 2005-2007 Kevin Dangoor,
Alberto Valverde, Mark Ramm and contributors"""
license = "MIT"
| """TurboGears project related information"""
version = "2.0a1"
description = "Next generation TurboGears built on Pylons"
long_description="""
TurboGears brings together a variety of best of breed python tools
to create an easy to install, easy to use web megaframework.
It provides and integrated and well tested set of tools for
everything you need to build dynamic, database driven applications.
TurboGears 2 provides you with everything you need from the
javascript programming tools, like ToscaWidgets and automatic
JSON generation, to one of the world's most powerful Object
Relational Mappers (SQLAlchemy).
The latest development version is available in
<a href="http://svn.turbogears.org/trunk#egg=turbogears-dev"
>the TurboGears subversion repository</a>."""
url="http://www.turbogears.org"
author='Alberto Valverde, Mark Ramm'
email = "alberto@toscat.net, mark.ramm@gmail.com"
copyright = """Copyright 2005-2007 Kevin Dangoor,
Alberto Valverde, Mark.Ramm and contributors"""
license = "MIT"
|
feat(AnnotationStoreProvider): Add a delete method, and also improve method names on publicAPI | import CompositeClosureHelper from '../../../Common/Core/CompositeClosureHelper';
// ----------------------------------------------------------------------------
// Annotation Store Provider
// ----------------------------------------------------------------------------
function annotationStoreProvider(publicAPI, model) {
if (!model.annotationStore) {
model.annotationStore = {};
}
publicAPI.getStoredAnnotationNames = () => {
const val = Object.keys(model.annotationStore);
val.sort();
return val;
};
publicAPI.getStoredAnnotation = (name) => model.annotationStore[name];
publicAPI.getStoredAnnotations = () => model.annotationStore;
publicAPI.setStoredAnnotation = (name, annotation) => {
model.annotationStore[name] = annotation;
publicAPI.fireStoreAnnotationChange(name, annotation);
};
publicAPI.deleteStoredAnnotation = name => {
delete model.annotationStore[name];
publicAPI.fireStoreAnnotationChange(name);
};
}
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
const DEFAULT_VALUES = {
// annotationStore: null,
};
// ----------------------------------------------------------------------------
export function extend(publicAPI, model, initialValues = {}) {
Object.assign(model, DEFAULT_VALUES, initialValues);
CompositeClosureHelper.destroy(publicAPI, model);
CompositeClosureHelper.isA(publicAPI, model, 'AnnotationStoreProvider');
CompositeClosureHelper.event(publicAPI, model, 'StoreAnnotationChange');
annotationStoreProvider(publicAPI, model);
}
// ----------------------------------------------------------------------------
export const newInstance = CompositeClosureHelper.newInstance(extend);
// ----------------------------------------------------------------------------
export default { newInstance, extend };
| import CompositeClosureHelper from '../../../Common/Core/CompositeClosureHelper';
// ----------------------------------------------------------------------------
// Annotation Store Provider
// ----------------------------------------------------------------------------
function annotationStoreProvider(publicAPI, model) {
if (!model.annotationStore) {
model.annotationStore = {};
}
publicAPI.getStoreAnnotationNames = () => {
const val = Object.keys(model.annotationStore);
val.sort();
return val;
};
publicAPI.getStoreAnnotation = (name) => model.annotationStore[name];
publicAPI.getStoreAnnotations = () => model.annotationStore;
publicAPI.setStoreAnnotation = (name, annotation) => {
model.annotationStore[name] = annotation;
publicAPI.fireStoreAnnotationChange(name, annotation);
};
}
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
const DEFAULT_VALUES = {
// annotationStore: null,
};
// ----------------------------------------------------------------------------
export function extend(publicAPI, model, initialValues = {}) {
Object.assign(model, DEFAULT_VALUES, initialValues);
CompositeClosureHelper.destroy(publicAPI, model);
CompositeClosureHelper.isA(publicAPI, model, 'AnnotationStoreProvider');
CompositeClosureHelper.event(publicAPI, model, 'StoreAnnotationChange');
annotationStoreProvider(publicAPI, model);
}
// ----------------------------------------------------------------------------
export const newInstance = CompositeClosureHelper.newInstance(extend);
// ----------------------------------------------------------------------------
export default { newInstance, extend };
|
chore(fork): Add "Fork me on GitHub" ribbon | import React, { Component, PropTypes } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import InvitationDialog from '../components/InvitationDialog';
import * as inviteActions from '../actions/invite';
import * as bootstrapUtils from 'react-bootstrap/lib/utils/bootstrapUtils';
import Button from 'react-bootstrap/lib/Button';
import Panel from 'react-bootstrap/lib/Panel';
bootstrapUtils.addStyle(Button, 'clear');
bootstrapUtils.bsSizes(['fab', 'fab-mini'], Button);
bootstrapUtils.addStyle(Panel, 'clear');
let ConnectedInvitation = connect(state => {
return {
invitation: state.invite.received
};
}, dispatch => {
return bindActionCreators({respondToInvitation: inviteActions.answer}, dispatch);
})(InvitationDialog);
export default class Main extends Component {
static contextTypes = {
store: PropTypes.object
};
render() {
return (
<div className='fullScreen'>
<a href="https://github.com/webcom-components/visio-sample">
<img
style={{position: 'absolute', top: 0, left: 0, border: 0}}
alt="Fork me on GitHub"
src="https://s3.amazonaws.com/github/ribbons/forkme_left_orange_ff7600.png"
/>
</a>
{/* this will render the child routes */}
{this.props.children}
<ConnectedInvitation />
</div>
);
}
}
| import React, { Component, PropTypes } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import InvitationDialog from '../components/InvitationDialog';
import * as inviteActions from '../actions/invite';
import * as bootstrapUtils from 'react-bootstrap/lib/utils/bootstrapUtils';
import Button from 'react-bootstrap/lib/Button';
import Panel from 'react-bootstrap/lib/Panel';
bootstrapUtils.addStyle(Button, 'clear');
bootstrapUtils.bsSizes(['fab', 'fab-mini'], Button);
bootstrapUtils.addStyle(Panel, 'clear');
let ConnectedInvitation = connect(state => {
return {
invitation: state.invite.received
};
}, dispatch => {
return bindActionCreators({respondToInvitation: inviteActions.answer}, dispatch);
})(InvitationDialog);
export default class Main extends Component {
static contextTypes = {
store: PropTypes.object
};
render() {
return (
<div className='fullScreen'>
{/* this will render the child routes */}
{this.props.children}
<ConnectedInvitation />
</div>
);
}
}
|
Sort out the mess with the version | #
# Initially copied from:
# https://raw.githubusercontent.com/pypa/sampleproject/master/setup.py
#
from setuptools import setup, find_packages
import os
import codecs
import __active_directory_version__ as _version
here = os.path.abspath(os.path.dirname(__file__))
with codecs.open(os.path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='active_directory',
version=_version.__VERSION__,
description='Active Directory',
long_description=long_description,
url='https://github.com/tjguk/active_directory',
author='Tim Golden',
author_email='mail@timgolden.me.uk',
license='MIT',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Win32 (MS Windows)',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
'License :: PSF',
'Natural Language :: English',
'Operating System :: Microsoft :: Windows :: Windows 95/98/2000',
'Topic :: System :: Systems Administration'
],
py_modules=["active_directory", "__active_directory_version__"],
)
| #
# Initially copied from:
# https://raw.githubusercontent.com/pypa/sampleproject/master/setup.py
#
from setuptools import setup, find_packages
import os
import codecs
import __active_directory_version__ as __version__
here = os.path.abspath(os.path.dirname(__file__))
with codecs.open(os.path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='active_directory',
version=__version__,
description='Active Directory',
long_description=long_description,
url='https://github.com/tjguk/active_directory',
author='Tim Golden',
author_email='mail@timgolden.me.uk',
license='MIT',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Win32 (MS Windows)',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
'License :: PSF',
'Natural Language :: English',
'Operating System :: Microsoft :: Windows :: Windows 95/98/2000',
'Topic :: System :: Systems Administration'
],
py_modules=["active_directory", "__active_directory_version__"],
)
|
Clone the default page data for every package to prevent problems with async tasks | const buildBaseCss = require(`./build/base-css.js`);
const buildBaseHtml = require(`./build/base-html.js`);
const buildPackageCss = require(`./build/package-css.js`);
const buildPackageHtml = require(`./build/package-html.js`);
const getDirectories = require(`./lib/get-directories.js`);
const packages = getDirectories(`avalanche/packages`);
const defaultData = {
css: `<link rel="stylesheet" href="/base/css/global.css">`
};
buildBaseHtml(defaultData);
buildBaseCss();
packages.forEach((packageName) => {
const packageData = JSON.parse(JSON.stringify(defaultData));
packageData.title = packageName;
packageData.css = [
`<link rel="stylesheet" href="/base/css/global.css">`,
`<link rel="stylesheet" href="/packages/${packageName}/css/index.css">`
].join(`\n`);
buildPackageHtml(packageName, packageData);
buildPackageCss(packageName);
});
| const buildBaseCss = require(`./build/base-css.js`);
const buildBaseHtml = require(`./build/base-html.js`);
const buildPackageCss = require(`./build/package-css.js`);
const buildPackageHtml = require(`./build/package-html.js`);
const getDirectories = require(`./lib/get-directories.js`);
const packages = getDirectories(`avalanche/packages`);
const data = {
css: `<link rel="stylesheet" href="/base/css/global.css">`
};
buildBaseHtml(data);
buildBaseCss();
packages.forEach((packageName) => {
data.title = packageName;
data.css = [
`<link rel="stylesheet" href="/base/css/global.css">`,
`<link rel="stylesheet" href="/packages/${packageName}/css/index.css">`
].join(`\n`);
buildPackageHtml(packageName, data);
buildPackageCss(packageName);
});
|
Fix unused variable and missing end newline
Fix a few diffs lost in pre-submission testing shuffle.
-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=148222135 | // Copyright 2017 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package google.registry.config;
import static com.google.common.truth.Truth.assertThat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class RegistryConfigTest {
public RegistryConfigTest() {}
@Test
public void test_clientSecretFilename() {
RegistryConfigSettings unused = YamlUtils.getConfigSettings();
// Verify that we're pulling this from the default.
assertThat(RegistryConfig.getClientSecretFilename()).isEqualTo(
"/google/registry/tools/resources/client_secret.json");
}
}
| // Copyright 2017 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package google.registry.config;
import static com.google.common.truth.Truth.assertThat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class RegistryConfigTest {
public RegistryConfigTest() {}
@Test
public void test_clientSecretFilename() {
RegistryConfigSettings config = YamlUtils.getConfigSettings();
// Verify that we're pulling this from the default.
assertThat(RegistryConfig.getClientSecretFilename()).isEqualTo(
"/google/registry/tools/resources/client_secret.json");
}
} |
Remove unused static URL pathing | """csunplugged URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.conf.urls.i18n import i18n_patterns
from django.contrib import admin
urlpatterns = i18n_patterns(
url(r'', include('general.urls', namespace='general')),
url(r'^topics/', include('topics.urls', namespace='topics')),
url(r'^resources/', include('resources.urls', namespace='resources')),
url(r'^admin/', include(admin.site.urls)),
)
| """csunplugged URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.conf.urls.i18n import i18n_patterns
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = i18n_patterns(
url(r'', include('general.urls', namespace='general')),
url(r'^topics/', include('topics.urls', namespace='topics')),
url(r'^resources/', include('resources.urls', namespace='resources')),
url(r'^admin/', include(admin.site.urls)),
)
# ] + static(settings.STATIC_URL, documnet_root=settings.STATIC_ROOT)
|
Fix history chain of DB migrations. | """alter table challenge
Revision ID: 307a4fbe8a05
Revises: 1edda52b619f
Create Date: 2017-04-19 14:39:20.255958
"""
# revision identifiers, used by Alembic.
revision = '307a4fbe8a05'
down_revision = '1edda52b619f'
from alembic import op
def upgrade():
try:
op.create_index(op.f('ix_challenge_serial'), 'challenge', ['serial'],
unique=False)
except Exception as exx:
print("Could not add index to 'challenge.serial'")
print (exx)
try:
op.drop_index('ix_challenge_transaction_id', table_name='challenge')
op.create_index(op.f('ix_challenge_transaction_id'), 'challenge',
['transaction_id'], unique=False)
except Exception as exx:
print("Could not remove uniqueness from 'challenge.transaction_id'")
print (exx)
def downgrade():
op.drop_index(op.f('ix_challenge_transaction_id'), table_name='challenge')
op.create_index('ix_challenge_transaction_id', 'challenge',
['transaction_id'], unique=1)
op.drop_index(op.f('ix_challenge_serial'), table_name='challenge')
| """alter table challenge
Revision ID: 307a4fbe8a05
Revises: d6b40a745e5
Create Date: 2017-04-19 14:39:20.255958
"""
# revision identifiers, used by Alembic.
revision = '307a4fbe8a05'
down_revision = 'd6b40a745e5'
from alembic import op
def upgrade():
try:
op.create_index(op.f('ix_challenge_serial'), 'challenge', ['serial'],
unique=False)
except Exception as exx:
print("Could not add index to 'challenge.serial'")
print (exx)
try:
op.drop_index('ix_challenge_transaction_id', table_name='challenge')
op.create_index(op.f('ix_challenge_transaction_id'), 'challenge',
['transaction_id'], unique=False)
except Exception as exx:
print("Could not remove uniqueness from 'challenge.transaction_id'")
print (exx)
def downgrade():
op.drop_index(op.f('ix_challenge_transaction_id'), table_name='challenge')
op.create_index('ix_challenge_transaction_id', 'challenge',
['transaction_id'], unique=1)
op.drop_index(op.f('ix_challenge_serial'), table_name='challenge')
|
Mark String hash methods as boundary
Signed-off-by: Stefan Marr <46f1a0bd5592a2f9244ca321b129902a06b53e03@stefan-marr.de> | package som.primitives;
import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary;
import com.oracle.truffle.api.dsl.GenerateNodeFactory;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.source.SourceSection;
import som.interpreter.nodes.nary.UnaryExpressionNode;
import som.vmobjects.SAbstractObject;
import som.vmobjects.SSymbol;
@GenerateNodeFactory
@Primitive({"objHashcode:", "stringHashcode:"})
public abstract class HashPrim extends UnaryExpressionNode {
public HashPrim(final SourceSection source) { super(false, source); }
@Specialization
@TruffleBoundary
public final long doString(final String receiver) {
return receiver.hashCode();
}
@Specialization
@TruffleBoundary
public final long doSSymbol(final SSymbol receiver) {
return receiver.getString().hashCode();
}
@Specialization
public final long doSAbstractObject(final SAbstractObject receiver) {
return receiver.hashCode();
}
}
| package som.primitives;
import com.oracle.truffle.api.dsl.GenerateNodeFactory;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.source.SourceSection;
import som.interpreter.nodes.nary.UnaryExpressionNode;
import som.vmobjects.SAbstractObject;
import som.vmobjects.SSymbol;
@GenerateNodeFactory
@Primitive({"objHashcode:", "stringHashcode:"})
public abstract class HashPrim extends UnaryExpressionNode {
public HashPrim(final SourceSection source) { super(false, source); }
@Specialization
public final long doString(final String receiver) {
return receiver.hashCode();
}
@Specialization
public final long doSSymbol(final SSymbol receiver) {
return receiver.getString().hashCode();
}
@Specialization
public final long doSAbstractObject(final SAbstractObject receiver) {
return receiver.hashCode();
}
}
|
Add sample url patterns to views for management functions. | # Copyright (C) 2011 by Christopher Adams
# Released under MIT License. See LICENSE.txt in the root of this
# distribution for details.
from django.conf.urls.defaults import *
urlpatterns = patterns('',
url(r'^$', 'manuscript.views.all_works', name="all-works"),
url(r'^(?P<title>[-\w]+)/$', 'manuscript.views.whole_work', name="show-whole-work"),
url(r'^(?P<title>[-\w]+)/list-chapters/$', 'manuscript.views.chapters', name="show-chapters"),
url(r'^(?P<title>[-\w]+)/(?P<page>\d+)/$', 'manuscript.views.page', name="show-page"),
url(r'^(?P<title>[-\w]+)/(?P<chapter>[-\w]+)/$', 'manuscript.views.chapter', name="show-chapter"),
# url(r'^(?P<title>.*)/(?P<model>.*)/?$', 'model_by_work'),
# url(r'^(?P<title>.*)/(?P<model>.*)/(?P<id>\d*)/?$', 'element_by_id'),
# url(r'^img_to_db/run/$', 'wyclif.bin.img_to_db.run_view'),
# url(r'^db/runimport/$', 'wyclif.bin.csv_to_db.run_view'),
)
| # Copyright (C) 2011 by Christopher Adams
# Released under MIT License. See LICENSE.txt in the root of this
# distribution for details.
from django.conf.urls.defaults import *
urlpatterns = patterns('',
url(r'^$', 'manuscript.views.all_works', name="all-works"),
url(r'^(?P<title>[-\w]+)/$', 'manuscript.views.whole_work', name="show-whole-work"),
url(r'^(?P<title>[-\w]+)/list-chapters/$', 'manuscript.views.chapters', name="show-chapters"),
url(r'^(?P<title>[-\w]+)/(?P<page>\d+)/$', 'manuscript.views.page', name="show-page"),
url(r'^(?P<title>[-\w]+)/(?P<chapter>[-\w]+)/$', 'manuscript.views.chapter', name="show-chapter"),
# url(r'^(?P<title>.*)/(?P<model>.*)/?$', 'model_by_work'),
# url(r'^(?P<title>.*)/(?P<model>.*)/(?P<id>\d*)/?$', 'element_by_id'),
)
|
Fix so right user token is created | <?php
namespace Isotop\Cargo\Content;
use WP_User;
class User extends Abstract_Content {
/**
* User constructor.
*
* @param WP_User|int $user
*/
public function __construct( $user ) {
if ( is_numeric( $user ) ) {
$user = get_user_by( 'ID', $user );
}
if ( empty( $user ) ) {
return;
}
if ( ! isset( $user->data->ID ) ) {
return;
}
$this->create( 'user', [
'token' => cargo_user_token( $user ),
'user' => [
'id' => intval( $user->data->ID ),
'user' => $user->data->user_login
]
] );
// Add extra data.
$this->add( 'extra', [
'site_id' => get_current_blog_id()
] );
}
}
| <?php
namespace Isotop\Cargo\Content;
use WP_User;
class User extends Abstract_Content {
/**
* User constructor.
*
* @param WP_User|int $user
*/
public function __construct( $user ) {
if ( is_numeric( $user ) ) {
$user = get_user_by( 'ID', $user );
}
if ( empty( $user ) ) {
return;
}
if ( ! isset( $user->data->ID ) ) {
return;
}
$this->create( 'user', [
'token' => cargo_user_token(),
'user' => [
'id' => intval( $user->data->ID ),
'user' => $user->data->user_login
]
] );
// Add extra data.
$this->add( 'extra', [
'site_id' => get_current_blog_id()
] );
}
}
|
Revert "Suppress data_type option for proxy"
This reverts commit 366dd5d28c012a12f37aba4639d847a24456b271. | <?php
return [
// Proxy settings
'proxy' => [
'default_url' => 'home',
'prefixes' => [],
'prefix_options' => [],
'data_type' => 'query_string',
'auto_trim' => true,
'auto_null' => true
],
// Auth settings
'auth' => [
'cookie_lifetime' => 86400,
'session_lifetime' => 3600,
'update_gap' => 1800,
'pull_user' => false
],
// LDAP settings
'ldap' => [
'hostname' => 'ldap.example.com',
'port' => 389,
'domain' => 'example.com'
],
// Translator settings
'translator' => [
'default_locale' => 'en'
],
]; | <?php
return [
// Proxy settings
'proxy' => [
'default_url' => 'home',
'prefixes' => [],
'prefix_options' => [],
'auto_trim' => true,
'auto_null' => true
],
// Auth settings
'auth' => [
'cookie_lifetime' => 86400,
'session_lifetime' => 3600,
'update_gap' => 1800,
'pull_user' => false
],
// LDAP settings
'ldap' => [
'hostname' => 'ldap.example.com',
'port' => 389,
'domain' => 'example.com'
],
// Translator settings
'translator' => [
'default_locale' => 'en'
],
]; |
[api] Set param theme precedence over hook theme module scope ( for now ) | var config = require('../../../config');
var fs = require("fs");
module['exports'] = function attemptToRequireUntrustedHook (opts, callback) {
var username = opts.username,
script = opts.script;
var untrustedHook;
var isStreamingHook;
var untrustedTemplate;
var err = null;
// At this stage, the hook source code is untrusted ( and should be validated )
try {
var _script = require.resolve(__dirname + '/../../../temp/' + username + "/" + opts.req.hook.name + "/" + script + '.js');
delete require.cache[_script];
untrustedHook = require(_script);
opts.req.hook = opts.req.hook || {};
untrustedHook.schema = untrustedHook.schema || {};
untrustedHook.theme = opts.req.hook.theme || untrustedHook.theme || config.defaultTheme;
untrustedHook.presenter = opts.req.hook.presenter || untrustedHook.presenter || config.defaultPresenter;
} catch (e) {
err = e;
}
if (err) {
return fs.readFile(__dirname + '/../../../temp/' + username + "/" + script + '.js', function(_err, _source){
if (_err) {
throw _err;
return callback(_err);
}
// unable to require Hook as commonjs module,
// the Hook is invalid
return callback(err, _source);
});
}
return callback(null, untrustedHook)
};
| var config = require('../../../config');
var fs = require("fs");
module['exports'] = function attemptToRequireUntrustedHook (opts, callback) {
var username = opts.username,
script = opts.script;
var untrustedHook;
var isStreamingHook;
var untrustedTemplate;
var err = null;
// At this stage, the hook source code is untrusted ( and should be validated )
try {
var _script = require.resolve(__dirname + '/../../../temp/' + username + "/" + opts.req.hook.name + "/" + script + '.js');
delete require.cache[_script];
untrustedHook = require(_script);
opts.req.hook = opts.req.hook || {};
untrustedHook.schema = untrustedHook.schema || {};
untrustedHook.theme = untrustedHook.theme || opts.req.hook.theme || config.defaultTheme;
untrustedHook.presenter = untrustedHook.presenter || opts.req.hook.presenter || config.defaultPresenter;
} catch (e) {
err = e;
}
if (err) {
return fs.readFile(__dirname + '/../../../temp/' + username + "/" + script + '.js', function(_err, _source){
if (_err) {
throw _err;
return callback(_err);
}
// unable to require Hook as commonjs module,
// the Hook is invalid
return callback(err, _source);
});
}
return callback(null, untrustedHook)
};
|
Add updated flags for default setter | "use strict";
var utils = require('./../../utils');
function define(name, prop, priv) {
var descriptor = {enumerable: true};
var getter = prop.get;
var setter = prop.set;
if (getter !== false) {
if (!utils.is.fun(getter) && getter !== false) {
getter = function() {
return this[priv.symbl][name];
};
}
descriptor.get = getter;
}
if (setter !== false) {
if (!utils.is.fun(setter)) {
setter = function(value) {
if (value) {
this[priv.symbl][name] = value;
this[priv.flags][name] = this[priv.shado][name] !== value;
}
return this;
};
}
descriptor.set = setter;
}
return descriptor;
}
module.exports = function(priv) {
return function(name, prop) {
return define(name, prop, priv);
};
}; | "use strict";
var utils = require('./../../utils');
function define(name, prop, priv) {
var descriptor = {enumerable: true};
var getter = prop.get;
var setter = prop.set;
if (getter !== false) {
if (!utils.is.fun(getter) && getter !== false) {
getter = function() {
return this[priv.symbl][name];
};
}
descriptor.get = getter;
}
if (setter !== false) {
if (!utils.is.fun(setter)) {
setter = function(value) {
if (value) {
this[priv.symbl][name] = value;
}
return this;
};
}
descriptor.set = setter;
}
return descriptor;
}
module.exports = function(priv) {
return function(name, prop) {
return define(name, prop, priv);
};
}; |
[xwalkdriver] Update activity name for crosswalk android package rule changed |
import ConfigParser
import json
import os
import unittest
from webserver import Httpd
from network import get_lan_ip
from selenium import webdriver
class WebDriverBaseTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.driver = create_driver()
cls.webserver = Httpd(host=get_lan_ip())
cls.webserver.start()
@classmethod
def tearDownClass(cls):
cls.webserver.stop()
if cls.driver:
cls.driver.quit()
def create_driver():
capabilities = {
'xwalkOptions': {
'androidPackage': 'org.xwalk.xwalkdrivertest',
'androidActivity': '.XwalkdrivertestActivity',
}
}
return webdriver.Remote('http://localhost:9515', capabilities)
|
import ConfigParser
import json
import os
import unittest
from webserver import Httpd
from network import get_lan_ip
from selenium import webdriver
class WebDriverBaseTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.driver = create_driver()
cls.webserver = Httpd(host=get_lan_ip())
cls.webserver.start()
@classmethod
def tearDownClass(cls):
cls.webserver.stop()
if cls.driver:
cls.driver.quit()
def create_driver():
capabilities = {
'xwalkOptions': {
'androidPackage': 'org.xwalk.xwalkdrivertest',
'androidActivity': '.XwalkDriverTestActivity',
}
}
return webdriver.Remote('http://localhost:9515', capabilities)
|
Handle Android RN 0.47 breaking change | /**
* Copyright (c) 2017-present, Wyatt Greenway. All rights reserved.
*
* This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package org.th317erd.react;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class DynamicFontsPackage implements ReactPackage {
//@Override
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
return Arrays.<NativeModule>asList(new DynamicFontsModule(reactContext));
}
}
| /**
* Copyright (c) 2017-present, Wyatt Greenway. All rights reserved.
*
* This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package org.th317erd.react;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class DynamicFontsPackage implements ReactPackage {
@Override
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
return Arrays.<NativeModule>asList(new DynamicFontsModule(reactContext));
}
}
|
Use log2 instead of log10. | #! /usr/bin/python2
from __future__ import division
import numpy
# JAKE
def calc_perplexity(test_counts_dict, trigram_probs_dict):
'''
# Calculates perplexity of contents of file_string
# according to probabilities in trigram_probs_dict.
'''
test_probs = []
for trigram, count in test_counts_dict.items():
for n in range(count):
logprob = numpy.log2(trigram_probs_dict[trigram])
test_probs.append(logprob)
logprob = sum(test_probs)
print "LOGPROB: {0}" .format(logprob)
entropy = logprob / len(test_probs)
perplexity = numpy.power(2, -entropy)
return perplexity
| #! /usr/bin/python2
from __future__ import division
import numpy
# JAKE
def calc_perplexity(test_counts_dict, trigram_probs_dict):
'''
# Calculates perplexity of contents of file_string
# according to probabilities in trigram_probs_dict.
'''
test_probs = []
for trigram, count in test_counts_dict.items():
for n in range(count):
logprob = numpy.log10(trigram_probs_dict[trigram])
test_probs.append(logprob)
logprob = sum(test_probs)
print "LOGPROB: {0}" .format(logprob)
norm = logprob / len(test_probs)
perplexity = numpy.power(2, -norm)
return perplexity
|
Fix issue with wrong features format in .yo-rc file | 'use strict';
var _ = require('lodash');
module.exports = function (answers) {
this.prompts = {};
this.prompts.projectName = answers.projectName;
this.prompts.authorName = answers.useBranding ? 'XHTMLized' : answers.authorName;
this.prompts.useBranding = answers.useBranding;
this.prompts.reloader = answers.reloader;
this.prompts.devServer = answers.devServer;
this.prompts.cssPreprocessor = answers.cssPreprocessor;
this.prompts.ignoreDist = answers.ignoreDist;
this.prompts.isWP = answers.isWP;
this.prompts.extension = answers.extension;
this.prompts.proxy = answers.proxy;
this.prompts.features = {};
if (Array.isArray(answers.features)) {
for (var i in answers.features) {
this.prompts.features[answers.features[i]] = true;
}
} else if (typeof answers.features === 'object') {
this.prompts.features = answers.features;
}
if (this.prompts.isWP) {
this.prompts.wpFolder = 'wp';
this.prompts.wpThemeFolder = this.prompts.wpFolder + '/wp-content/themes/' + _.kebabCase(this.prompts.projectName);
}
};
| 'use strict';
var _ = require('lodash');
module.exports = function (answers) {
this.prompts = {};
this.prompts.projectName = answers.projectName;
this.prompts.authorName = answers.useBranding ? 'XHTMLized' : answers.authorName;
this.prompts.useBranding = answers.useBranding;
this.prompts.reloader = answers.reloader;
this.prompts.devServer = answers.devServer;
this.prompts.cssPreprocessor = answers.cssPreprocessor;
this.prompts.ignoreDist = answers.ignoreDist;
this.prompts.isWP = answers.isWP;
this.prompts.extension = answers.extension;
this.prompts.proxy = answers.proxy;
this.prompts.features = {};
for (var i in answers.features) {
this.prompts.features[answers.features[i]] = true;
}
if (this.prompts.isWP) {
this.prompts.wpFolder = 'wp';
this.prompts.wpThemeFolder = this.prompts.wpFolder + '/wp-content/themes/' + _.kebabCase(this.prompts.projectName);
}
};
|
Fix blog page when no image is set | <?php defined('C5_EXECUTE') or die("Access Denied.");
$dh = Loader::helper('concrete/dashboard');
$im = Loader::helper('image');
$this->inc('elements/header.php');
$headImage = $c->getAttribute("main_image");
?>
<body class="blog <?php echo ($dh->canRead()) ? "logged_in" : ""; ?>">
<?php $this->inc('elements/navbar.php'); ?>
<div id="central">
<header <?php echo is_object($headImage) ? 'style="background-image:url('.$headImage->getURL() .')"' : "" ?>>
<?php $ai = new Area('Blog Post Header'); $ai->display($c); ?>
<h1><?php echo $c->getCollectionName(); ?></h1>
<p class="description"><?php echo $c->getCollectionDescription(); ?></p>
<p class="meta"><?php
echo t('%s <em>on</em> <strong>%s</strong>',
$c->getVersionObject()->getVersionAuthorUserName(),
$c->getCollectionDatePublic(DATE_APP_GENERIC_MDY_FULL));
?></p>
</header>
<div id="body">
<article>
<?php $as = new Area('Main'); $as->display($c); ?>
</article>
</div>
</div>
<?php $this->inc('elements/footer.php'); ?>
| <?php defined('C5_EXECUTE') or die("Access Denied.");
$dh = Loader::helper('concrete/dashboard');
$im = Loader::helper('image');
$this->inc('elements/header.php');
$headImage = $c->getAttribute("main_image");
?>
<body class="blog <?php echo ($dh->canRead()) ? "logged_in" : ""; ?>">
<?php $this->inc('elements/navbar.php'); ?>
<div id="central">
<header <?php echo isset($headImage) ? 'style="background-image:url('.$headImage->getURL() .')"' : "" ?>>
<?php $ai = new Area('Blog Post Header'); $ai->display($c); ?>
<h1><?php echo $c->getCollectionName(); ?></h1>
<p class="description"><?php echo $c->getCollectionDescription(); ?></p>
<p class="meta"><?php
echo t('%s <em>on</em> <strong>%s</strong>',
$c->getVersionObject()->getVersionAuthorUserName(),
$c->getCollectionDatePublic(DATE_APP_GENERIC_MDY_FULL));
?></p>
</header>
<div id="body">
<article>
<?php $as = new Area('Main'); $as->display($c); ?>
</article>
</div>
</div>
<?php $this->inc('elements/footer.php'); ?>
|
Use entry as an array instead of data | const webpack = require("webpack");
const webpackDevServer = require('webpack-dev-server');
const path = require('path');
const baseConfig = require('../config/webpack.config.dist');
const port = 8080;
const serverURI = `webpack-dev-server/client?http://localhost:${port}/`;
let browser = baseConfig();
browser.output.libraryTarget = "var";
browser.output.filename = "./dist/seng-boilerplate.js";
browser.output.path = path.join(__dirname, '../dist');
if(typeof browser.entry === 'string')
{
const { entry } = browser;
browser.entry = [serverURI, entry];
}
else if(typeof browser.entry === 'object')
{
browser.entry.unshift(serverURI)
}
browser.devtool = 'source-map';
browser.watch = true;
browser.progress = true;
browser.keepalive = true;
const compiler = webpack(browser);
const server = new webpackDevServer(compiler, {
contentBase: "example/"
});
server.listen(port, function (err) {
if (err) {
console.log(err);
return
}
console.log(`Listening at http://localhost:${port}\n`);
});
| const webpack = require("webpack");
const webpackDevServer = require('webpack-dev-server');
const path = require('path');
const baseConfig = require('../config/webpack.config.dist');
const port = 8080;
const serverURI = `webpack-dev-server/client?http://localhost:${port}/`;
let browser = baseConfig();
browser.output.libraryTarget = "var";
browser.output.filename = "./dist/seng-boilerplate.js";
browser.output.path = path.join(__dirname, '../dist');
if(typeof browser.entry === 'string')
{
const { entry } = browser;
browser.entry = { app: [serverURI, entry]};
}
else if(typeof browser.entry.app === 'object')
{
browser.entry.app.unshift(serverURI)
}
browser.devtool = 'source-map';
browser.watch = true;
browser.progress = true;
browser.keepalive = true;
const compiler = webpack(browser);
const server = new webpackDevServer(compiler, {
contentBase: "example/"
});
server.listen(port, function (err) {
if (err) {
console.log(err);
return
}
console.log(`Listening at http://localhost:${port}\n`);
});
|
Add flake8-debugger to list of flake8 checks | from setuptools import setup
setup(
name='flake8-config-4catalyzer',
version='0.2.1',
url='https://github.com/4Catalyzer/python/tree/packages/flake8-config-4catalyzer',
author="Alex Rothberg",
author_email='arothberg@4catalyzer.com',
license='MIT',
classifiers=(
'Development Status :: 3 - Alpha',
'Environment :: Console',
'Framework :: Flake8',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Software Development :: Quality Assurance',
),
keywords='flake8',
install_requires=(
'flake8',
'flake8-commas',
'flake8-debugger',
'flake8-import-order',
),
extras_require={
':python_version>="3.5"': ('flake8-bugbear',),
},
)
| from setuptools import setup
setup(
name='flake8-config-4catalyzer',
version='0.2.1',
url='https://github.com/4Catalyzer/python/tree/packages/flake8-config-4catalyzer',
author="Alex Rothberg",
author_email='arothberg@4catalyzer.com',
license='MIT',
classifiers=(
'Development Status :: 3 - Alpha',
'Environment :: Console',
'Framework :: Flake8',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Software Development :: Quality Assurance',
),
keywords='flake8',
install_requires=(
'flake8',
'flake8-commas',
'flake8-import-order',
),
extras_require={
':python_version>="3.5"': ('flake8-bugbear',),
},
)
|
Add failing test for "cannot update concurrency mid-process" | var tape = require('tape')
var queue = require('../')
tape('concurrent', function (t) {
t.plan(6)
var actual = []
var q = queue()
q.concurrency = 2
q.push(function (cb) {
setTimeout(function () {
actual.push('two')
cb()
}, 20)
})
q.push(function (cb) {
setTimeout(function () {
actual.push('one')
cb()
}, 0)
})
q.push(function (cb) {
q.concurrency = 1
setTimeout(function () {
actual.push('three')
cb()
}, 30)
})
q.push(function (cb) {
setTimeout(function () {
actual.push('four')
cb()
}, 10)
})
q.push(function (cb) {
setTimeout(function () {
actual.push('five')
cb()
}, 0)
})
q.start(function () {
var expected = [ 'one', 'two', 'three', 'four', 'five' ]
t.equal(actual.length, expected.length)
for (var i in actual) {
var a = actual[i]
var e = expected[i]
t.equal(a, e)
}
})
})
| var tape = require('tape')
var queue = require('../')
tape('concurrent', function (t) {
t.plan(4)
var actual = []
var q = queue()
q.push(function (cb) {
setTimeout(function () {
actual.push('one')
cb()
}, 0)
})
q.push(function (cb) {
setTimeout(function () {
actual.push('three')
cb()
}, 20)
})
q.push(function (cb) {
setTimeout(function () {
actual.push('two')
cb()
}, 10)
})
q.start(function () {
var expected = [ 'one', 'two', 'three' ]
t.equal(actual.length, expected.length)
for (var i in actual) {
var a = actual[i]
var e = expected[i]
t.equal(a, e)
}
})
})
|
addFieldsDict: Add all at once so multi-part fields work | import Users from 'meteor/vulcan:users';
export const generateIdResolverSingle = ({collectionName, fieldName}) => {
return async (doc, args, context) => {
if (!doc[fieldName]) return null
const { currentUser } = context
const collection = context[collectionName]
const { checkAccess } = collection
const resolvedDoc = await collection.loader.load(doc[fieldName])
if (checkAccess && !checkAccess(currentUser, resolvedDoc)) return null
const restrictedDoc = Users.restrictViewableFields(currentUser, collection, resolvedDoc)
return restrictedDoc
}
}
export const generateIdResolverMulti = ({collectionName, fieldName}) => {
return async (doc, args, context) => {
if (!doc[fieldName]) return []
const { currentUser } = context
const collection = context[collectionName]
const { checkAccess } = collection
const resolvedDocs = await collection.loader.loadMany(doc[fieldName])
const existingDocs = _.filter(resolvedDocs, d=>!!d);
const filteredDocs = checkAccess ? _.filter(existingDocs, d => checkAccess(currentUser, d)) : resolvedDocs
const restrictedDocs = Users.restrictViewableFields(currentUser, collection, filteredDocs)
return restrictedDocs
}
}
export const addFieldsDict = (collection, fieldsDict) => {
let translatedFields = [];
for (let key in fieldsDict) {
translatedFields.push({
fieldName: key,
fieldSchema: fieldsDict[key]
});
}
collection.addField(translatedFields);
} | import Users from 'meteor/vulcan:users';
export const generateIdResolverSingle = ({collectionName, fieldName}) => {
return async (doc, args, context) => {
if (!doc[fieldName]) return null
const { currentUser } = context
const collection = context[collectionName]
const { checkAccess } = collection
const resolvedDoc = await collection.loader.load(doc[fieldName])
if (checkAccess && !checkAccess(currentUser, resolvedDoc)) return null
const restrictedDoc = Users.restrictViewableFields(currentUser, collection, resolvedDoc)
return restrictedDoc
}
}
export const generateIdResolverMulti = ({collectionName, fieldName}) => {
return async (doc, args, context) => {
if (!doc[fieldName]) return []
const { currentUser } = context
const collection = context[collectionName]
const { checkAccess } = collection
const resolvedDocs = await collection.loader.loadMany(doc[fieldName])
const existingDocs = _.filter(resolvedDocs, d=>!!d);
const filteredDocs = checkAccess ? _.filter(existingDocs, d => checkAccess(currentUser, d)) : resolvedDocs
const restrictedDocs = Users.restrictViewableFields(currentUser, collection, filteredDocs)
return restrictedDocs
}
}
export const addFieldsDict = (collection, fieldsDict) => {
for (let key in fieldsDict) {
collection.addField({
fieldName: key,
fieldSchema: fieldsDict[key]
});
}
} |
Change master version information to 0.5.99 (git master)
Todo: We should probably add the smarts to EForge to grab the git
revision for master, at least if Dulwich is installed :-) | # -*- coding: utf-8 -*-
# EForge project management system, Copyright Β© 2010, Element43
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
from eforge.menu import ItemOrder
EFORGE_PLUGIN = {
'name': 'EForge Core',
'credit': 'Copyright © 2010 Element43 and contributors',
'provides': {
'mnu': [('project-page', ItemOrder(000, 'Summary'))],
},
}
VERSION = (0, 5, 99, '(git master)')
def get_version():
return '%d.%d.%d %s' % VERSION | # -*- coding: utf-8 -*-
# EForge project management system, Copyright Β© 2010, Element43
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
from eforge.menu import ItemOrder
EFORGE_PLUGIN = {
'name': 'EForge Core',
'credit': 'Copyright © 2010 Element43 and contributors',
'provides': {
'mnu': [('project-page', ItemOrder(000, 'Summary'))],
},
}
VERSION = (0, 5, 0, 'beta 1')
def get_version():
return '%d.%d.%d %s' % VERSION |
Use own statement to delete user activity events
For performance reasons, we use an own statement to delete likeable recent activity events. | <?php
/**
* This script deletes all recent activity events for likes. Running this script is necessary after an update to version 5.2,
* because with this version the reaction system was introduced and the events there were changed so that they contain the
* reaction type, which is not present in previous fired events. Older events will otherwise throw an error.
*
* @author Joshua Ruesweg
* @copyright 2001-2019 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core
*/
$definitionList = new \wcf\data\object\type\definition\ObjectTypeDefinitionList();
$definitionList->getConditionBuilder()->add('definitionName = ?', ['com.woltlab.wcf.user.recentActivityEvent']);
$definitionList->readObjects();
$definition = $definitionList->current();
$sql = "SELECT objectTypeID
FROM wcf". WCF_N ."_object_type
WHERE objectType LIKE '%likeable%'
AND definitionID = ?";
$statement = \wcf\system\WCF::getDB()->prepareStatement($sql);
$statement->execute([$definition->definitionID]);
$objectTypeIDs = $statement->fetchAll(\PDO::FETCH_COLUMN);
$conditionBuilder = new \wcf\system\database\util\PreparedStatementConditionBuilder();
$conditionBuilder->add('objectTypeID IN (?)', [$objectTypeIDs]);
$sql = "DELETE FROM wcf". WCF_N ."_user_activity_event ".$conditionBuilder;
$statement = \wcf\system\WCF::getDB()->prepareStatement($sql);
$statement->execute($conditionBuilder->getParameters());
| <?php
/**
* This script deletes all recent activity events for likes. Running this script is necessary after an update to version 5.2,
* because with this version the reaction system was introduced and the events there were changed so that they contain the
* reaction type, which is not present in previous fired events. Older events will otherwise throw an error.
*
* @author Joshua Ruesweg
* @copyright 2001-2019 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core
*/
$definitionList = new \wcf\data\object\type\definition\ObjectTypeDefinitionList();
$definitionList->getConditionBuilder()->add('definitionName = ?', ['com.woltlab.wcf.user.recentActivityEvent']);
$definitionList->readObjects();
$definition = $definitionList->current();
$recentActivityList = new \wcf\data\user\activity\event\UserActivityEventList();
$recentActivityList->getConditionBuilder()->add("objectTypeID IN (SELECT objectTypeID FROM wcf". WCF_N ."_object_type WHERE objectType LIKE '%likeable%' AND definitionID = ?)", [$definition->definitionID]);
$recentActivityList->readObjectIDs();
if (count($recentActivityList->getObjectIDs())) {
\wcf\data\user\activity\event\UserActivityEventEditor::deleteAll($recentActivityList->getObjectIDs());
}
|
Use trial logging. Tweak numpy logging output. | #!/usr/bin/env python
import climate
import joblib
import lmj.cubes
import numpy as np
def _check(t):
t.load()
t.add_velocities(smooth=0)
t.add_accelerations(smooth=0)
vel = abs(t.df[t.marker_velocity_columns].values).flatten()
vel = vel[np.isfinite(vel)]
pct = np.percentile(vel, [1, 2, 5, 10, 20, 50, 80, 90, 95, 98, 99])
np.set_printoptions(suppress=True, linewidth=1000, precision=2)
t.log('%s', pct)
def main(root):
trials = lmj.cubes.Experiment(root).trials_matching('*')
check = joblib.delayed(_check)
joblib.Parallel(-1)(check(t) for t in trials)
if __name__ == '__main__':
climate.call(main)
| #!/usr/bin/env python
import climate
import joblib
import lmj.cubes
import numpy as np
def _check(t):
t.load()
t.add_velocities(smooth=0)
vel = abs(t.df[t.marker_velocity_columns].values).flatten()
vel = vel[np.isfinite(vel)]
pct = np.percentile(vel, [1, 2, 5, 10, 20, 50, 80, 90, 95, 98, 99])
print(t.subject.key, t.block.key, t.key, *pct)
def main(root):
trials = lmj.cubes.Experiment(root).trials_matching('*')
check = joblib.delayed(_check)
joblib.Parallel(-1)(check(t) for t in trials)
if __name__ == '__main__':
climate.call(main)
|
Update copyright check to accept a new, more inclusive, copyright.
In order to address concerns over community copyright of the source code they modify. All authors are still subject to the terms of the CLA they sign when contributing.
This new format was approved by Microsoft legal:
```
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft Corporation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
```
In addition to the original format:
```
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
```
The check now allows both so that we don't need to make a disruptive change to every file in the project. The notice can be updated at the author's discretion as they make changes. | #-------------------------------------------------------------------------------------------------------
# Copyright (C) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
#-------------------------------------------------------------------------------------------------------
# Python 2.7 and 3.x compatibility for easier testing regardless of python installation
from __future__ import print_function
import sys
import os.path
import re
copyright_lines = [
r'-------------------------------------------------------------------------------------------------------',
r' Copyright \(C\) Microsoft( Corporation and contributors)?\. All rights reserved\.',
r' Licensed under the MIT license\. See LICENSE\.txt file in the project root for full license information\.'
]
regexes = []
for line in copyright_lines:
pattern = '^.{1,5}%s$' % line
regexes.append(re.compile(pattern))
if len(sys.argv) < 2:
print("Requires passing a filename as an argument.")
exit(1)
file_name = sys.argv[1]
if not os.path.isfile(file_name):
print("File does not exist:", file_name, "(not necessarily an error)")
exit(0)
with open(file_name, 'r') as sourcefile:
for x in range(0,len(copyright_lines)):
# TODO add a check for empty files (dummy.js etc), as they cause the script to crash here
line = next(sourcefile)
line = line.rstrip()
matches = regexes[x].match(line)
if not matches:
print(file_name, "... does not contain a correct Microsoft copyright notice.")
# found a problem so exit and report the problem to the caller
exit(1)
| #-------------------------------------------------------------------------------------------------------
# Copyright (C) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
#-------------------------------------------------------------------------------------------------------
# Python 2.7 and 3.x compatibility for easier testing regardless of python installation
from __future__ import print_function
import sys
import os.path
import re
copyright_lines = [
r'-------------------------------------------------------------------------------------------------------',
r' Copyright \(C\) Microsoft\. All rights reserved\.',
r' Licensed under the MIT license\. See LICENSE\.txt file in the project root for full license information\.'
]
regexes = []
for line in copyright_lines:
pattern = '^.{1,5}%s$' % line
regexes.append(re.compile(pattern))
if len(sys.argv) < 2:
print("Requires passing a filename as an argument.")
exit(1)
file_name = sys.argv[1]
if not os.path.isfile(file_name):
print("File does not exist:", file_name, "(not necessarily an error)")
exit(0)
with open(file_name, 'r') as sourcefile:
for x in range(0,len(copyright_lines)):
# TODO add a check for empty files (dummy.js etc), as they cause the script to crash here
line = next(sourcefile)
line = line.rstrip()
matches = regexes[x].match(line)
if not matches:
print(file_name, "... does not contain a correct Microsoft copyright notice.")
# found a problem so exit and report the problem to the caller
exit(1)
|
Fix wrong name of decorated method of online serializer | import Ember from 'ember';
import isObject from '../../utils/is-object';
/*
* Extend serializer so that we can use local serializer when local adater is
* used.
*/
export default function decorateSerializer(serializer) {
if(serializer.get('flexberry')) {
return serializer;
}
serializer.set('flexberry', true);
var localSerializer = Ember.getOwner(this).lookup('store:local').get('adapter.serializer');
// serialize()
// normalizeResponse()
// normalize() is not used in localforage adapter, so we do not decorate
decorateSerializerMethod(serializer, localSerializer, 'serialize', 0);
decorateSerializerMethod(serializer, localSerializer, 'normalizeResponse', 2);
// decorateSerializerMethod(serializer, localSerializer, 'normalize', 2);
return serializer;
}
function decorateSerializerMethod(serializer, localSerializer, methodName, wrappedArgIndex) {
var originMethod = serializer[methodName];
var backupMethod = function() {
// remove flexberry from arg
var args = Array.prototype.slice.call(arguments);
delete args[wrappedArgIndex].flexberry;
return localSerializer[methodName].apply(localSerializer, args);
};
serializer[methodName] = function() {
var payload = arguments[wrappedArgIndex];
if(isObject(payload) && payload.flexberry) {
return backupMethod.apply(localSerializer, arguments);
} else {
return originMethod.apply(serializer, arguments);
}
};
}
| import Ember from 'ember';
import isObject from '../../utils/is-object';
/*
* Extend serializer so that we can use local serializer when local adater is
* used.
*/
export default function decorateSerializer(serializer) {
if(serializer.get('flexberry')) {
return serializer;
}
serializer.set('flexberry', true);
var localSerializer = Ember.getOwner(this).lookup('store:local').get('adapter.serializer');
// serialize()
// extract()
// normalize() is not used in localforage adapter, so we do not decorate
decorateSerializerMethod(serializer, localSerializer, 'serialize', 0);
decorateSerializerMethod(serializer, localSerializer, 'extract', 2);
// decorateSerializerMethod(serializer, localSerializer, 'normalize', 2);
return serializer;
}
function decorateSerializerMethod(serializer, localSerializer, methodName, wrappedArgIndex) {
var originMethod = serializer[methodName];
var backupMethod = function() {
// remove flexberry from arg
var args = Array.prototype.slice.call(arguments);
delete args[wrappedArgIndex].flexberry;
return localSerializer[methodName].apply(localSerializer, args);
};
serializer[methodName] = function() {
var payload = arguments[wrappedArgIndex];
if(isObject(payload) && payload.flexberry) {
return backupMethod.apply(localSerializer, arguments);
} else {
return originMethod.apply(serializer, arguments);
}
};
}
|
Fix error when there is no git | import os
def git_file_path(view, git_path):
if not git_path:
return False
full_file_path = view.file_name()
git_path_to_file = full_file_path.replace(git_path,'')
if git_path_to_file[0] == "/":
git_path_to_file = git_path_to_file[1:]
return git_path_to_file
def git_root(directory):
if os.path.exists(os.path.join(directory, '.git')):
return directory
else:
parent = os.path.realpath(os.path.join(directory, os.path.pardir))
if parent == directory:
# we have reached root dir
return False
else:
return git_root(parent)
def git_tree(view):
full_file_path = view.file_name()
file_parent_dir = os.path.realpath(os.path.dirname(full_file_path))
return git_root(file_parent_dir)
def git_dir(directory):
if not directory:
return False
return os.path.join(directory, '.git')
| import os
def git_file_path(view, git_path):
if not git_path:
return False
full_file_path = view.file_name()
git_path_to_file = full_file_path.replace(git_path,'')
if git_path_to_file[0] == "/":
git_path_to_file = git_path_to_file[1:]
return git_path_to_file
def git_root(directory):
if os.path.exists(os.path.join(directory, '.git')):
return directory
else:
parent = os.path.realpath(os.path.join(directory, os.path.pardir))
if parent == directory:
# we have reached root dir
return False
else:
return git_root(parent)
def git_tree(view):
full_file_path = view.file_name()
file_parent_dir = os.path.realpath(os.path.dirname(full_file_path))
return git_root(file_parent_dir)
def git_dir(directory):
return os.path.join(directory, '.git')
|
Speed up tests, only register what is required | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.gshell.testsuite;
import org.apache.gshell.registry.CommandRegistrar;
import org.apache.gshell.Shell;
import org.apache.maven.shell.ShellBuilder;
/**
* Builds {@link org.apache.gshell.Shell} instances.
*
* @author <a href="mailto:jason@planet57.com">Jason Dillon</a>
*/
public class TestShellBuilder
extends ShellBuilder
{
protected void registerCommand(final String name, final String type) throws Exception {
CommandRegistrar registrar = getContainer().lookup(CommandRegistrar.class);
registrar.registerCommand(name, type);
}
@Override
public Shell create() throws Exception {
setRegisterCommands(false);
return super.create();
}
} | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.gshell.testsuite;
import org.apache.gshell.registry.CommandRegistrar;
import org.apache.maven.shell.ShellBuilder;
/**
* Builds {@link org.apache.gshell.Shell} instances.
*
* @author <a href="mailto:jason@planet57.com">Jason Dillon</a>
*/
public class TestShellBuilder
extends ShellBuilder
{
protected void registerCommand(final String name, final String type) throws Exception {
CommandRegistrar registrar = getContainer().lookup(CommandRegistrar.class);
registrar.registerCommand(name, type);
}
} |
Remove "+build ignore" from test command
We want to make sure the command still builds in the CI.
Signed-off-by: Ryan O'Leary <32139beaa9c574695821e85473b09a4e33316467@google.com> | // Copyright 2020 the u-root Authors. All rights reserved
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This program was used to generate dir-hard-link.cpio, which is
// an archive containing two directories with the same inode (0).
// Depending on how the cpio package generates inodes in the future,
// it may not reproduce the file.
package main
import (
"log"
"os"
"github.com/u-root/u-root/pkg/cpio"
)
func main() {
archiver, err := cpio.Format("newc")
if err != nil {
log.Fatal(err)
}
rw := archiver.Writer(os.Stdout)
for _, rec := range []cpio.Record{
cpio.Directory("directory1", 0755),
cpio.Directory("directory2", 0755),
} {
rec.UID = uint64(os.Getuid())
rec.GID = uint64(os.Getgid())
if err := rw.WriteRecord(rec); err != nil {
log.Fatal(err)
}
}
if err := cpio.WriteTrailer(rw); err != nil {
log.Fatal(err)
}
}
| // Copyright 2020 the u-root Authors. All rights reserved
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build ignore
// This program was used to generate dir-hard-link.cpio, which is
// an archive containing two directories with the same inode (0).
// Depending on how the cpio package generates inodes in the future,
// it may not reproduce the file.
package main
import (
"log"
"os"
"github.com/u-root/u-root/pkg/cpio"
)
func main() {
archiver, err := cpio.Format("newc")
if err != nil {
log.Fatal(err)
}
rw := archiver.Writer(os.Stdout)
for _, rec := range []cpio.Record{
cpio.Directory("directory1", 0755),
cpio.Directory("directory2", 0755),
} {
rec.UID = uint64(os.Getuid())
rec.GID = uint64(os.Getgid())
if err := rw.WriteRecord(rec); err != nil {
log.Fatal(err)
}
}
if err := cpio.WriteTrailer(rw); err != nil {
log.Fatal(err)
}
}
|
Use JWT secret as defined in config.js instead of hardcoded value | var config = require('../config/config');
var socketioJwt = require('socketio-jwt');
var clients = {};
module.exports = function(io) {
io.sockets.on('connection', socketioJwt.authorize({
secret: config.jwtSecret,
timeout: 15000 // 15s
})).on('authenticated', function(socket) {
console.log(socket.decoded_token.user + ' connected using ' + socket.decoded_token.device);
var room = socket.decoded_token.room;
var device = socket.decoded_token.device;
var unique = socket.decoded_token.iat;
if (!clients[room]) {
clients[room] = {};
}
clients[room][unique] = device;
// Route notifications to clients who are listening
socket.on(room + '-notifications', function(notif) {
notif['device'] = device;
io.emit(room + '-notifications', notif);
});
// Report all known connected devices
socket.on(room + '-devices', function(msg) {
var devices = [];
for (const key of Object.keys(clients[room])) {
const val = clients[room][key];
devices.push(val);
}
socket.emit(room + '-devices', devices);
});
socket.on('disconnect', function(socket) {
delete clients[room][unique];
});
});
}
| var socketioJwt = require("socketio-jwt");
var clients = {};
module.exports = function(io) {
io.sockets.on('connection', socketioJwt.authorize({
secret: 'supersecret',
timeout: 15000 // 15s
})).on('authenticated', function(socket) {
console.log(socket.decoded_token.user + ' connected using ' + socket.decoded_token.device);
var room = socket.decoded_token.room;
var device = socket.decoded_token.device;
var unique = socket.decoded_token.iat;
if (!clients[room]) {
clients[room] = {};
}
clients[room][unique] = device;
// Route notifications to clients who are listening
socket.on(room + '-notifications', function(notif) {
notif['device'] = device;
io.emit(room + '-notifications', notif);
});
// Report all known connected devices
socket.on(room + '-devices', function(msg) {
var devices = [];
for (const key of Object.keys(clients[room])) {
const val = clients[room][key];
devices.push(val);
}
socket.emit(room + '-devices', devices);
});
socket.on('disconnect', function(socket) {
delete clients[room][unique];
});
});
}
|
Use gzip on records dataset
- Didn't know fetch/AJAX natively supported gzip (needs investigation on
other browsers) | fetch('/records.grouped.json.gz')
.then(response => response.json())
.then(records => {
renderData(records)
return records
})
.then(records => {
const handler = _ => {
const query = document.querySelector('input').value
if (!query) return renderData(records)
const queryRegexp = new RegExp(query, 'i')
renderData(records.filter(r =>
r.artist.match(queryRegexp) || r.album.match(queryRegexp)))
}
const throttledHandler = throttle(handler, 200)
document.querySelector('input').addEventListener('keyup', throttledHandler)
})
function renderData(data) {
const template = document.querySelector('#template').innerHTML
Mustache.parse(template)
document.querySelector('#output').innerHTML = Mustache.render(template, {results: data})
}
function throttle(fn, minTime) {
let currentTimer
let callCount = 0
return function () {
if (callCount === 0) {
fn()
}
if (currentTimer) {
clearTimeout(currentTimer)
}
callCount++
currentTimer = window.setTimeout(_ => {
if (callCount > 1) {
fn()
}
currentTimer = null
callCount = 0
}, minTime)
}
}
| fetch('/records2.json')
.then(response => response.json())
.then(records => {
renderData(records)
return records
})
.then(records => {
const handler = _ => {
const query = document.querySelector('input').value
if (!query) return renderData(records)
const queryRegexp = new RegExp(query, 'i')
renderData(records.filter(r =>
r.artist.match(queryRegexp) || r.album.match(queryRegexp)))
}
const throttledHandler = throttle(handler, 200)
document.querySelector('input').addEventListener('keyup', throttledHandler)
})
function renderData(data) {
const template = document.querySelector('#template').innerHTML
Mustache.parse(template)
document.querySelector('#output').innerHTML = Mustache.render(template, {results: data})
}
function throttle(fn, minTime) {
let currentTimer
let callCount = 0
return function () {
if (callCount === 0) {
fn()
}
if (currentTimer) {
clearTimeout(currentTimer)
}
callCount++
currentTimer = window.setTimeout(_ => {
if (callCount > 1) {
fn()
}
currentTimer = null
callCount = 0
}, minTime)
}
}
|
Sort on first name after last name | from __future__ import unicode_literals
from compat import BufferDictWriter
from .models import CSV_ROW_FIELDS
def _candidate_sort_by_name_key(row):
return (
row['name'].split()[-1],
row['name'].rsplit(None, 1)[0],
not row['election_current'],
row['election_date'],
row['election'],
row['post_label']
)
def _candidate_sort_by_post_key(row):
return (
not row['election_current'],
row['election_date'],
row['election'],
row['post_label'],
row['name'].split()[-1],
row['name'].rsplit(None, 1)[0],
)
def list_to_csv(candidates_list, group_by_post=False):
from .election_specific import EXTRA_CSV_ROW_FIELDS
csv_fields = CSV_ROW_FIELDS + EXTRA_CSV_ROW_FIELDS
writer = BufferDictWriter(fieldnames=csv_fields)
writer.writeheader()
if group_by_post:
sorted_rows = sorted(candidates_list, key=_candidate_sort_by_post_key)
else:
sorted_rows = sorted(candidates_list, key=_candidate_sort_by_name_key)
for row in sorted_rows:
writer.writerow(row)
return writer.output
| from __future__ import unicode_literals
from compat import BufferDictWriter
from .models import CSV_ROW_FIELDS
def _candidate_sort_by_name_key(row):
return (
row['name'].split()[-1],
not row['election_current'],
row['election_date'],
row['election'],
row['post_label']
)
def _candidate_sort_by_post_key(row):
return (
not row['election_current'],
row['election_date'],
row['election'],
row['post_label'],
row['name'].split()[-1])
def list_to_csv(candidates_list, group_by_post=False):
from .election_specific import EXTRA_CSV_ROW_FIELDS
csv_fields = CSV_ROW_FIELDS + EXTRA_CSV_ROW_FIELDS
writer = BufferDictWriter(fieldnames=csv_fields)
writer.writeheader()
if group_by_post:
sorted_rows = sorted(candidates_list, key=_candidate_sort_by_post_key)
else:
sorted_rows = sorted(candidates_list, key=_candidate_sort_by_name_key)
for row in sorted_rows:
writer.writerow(row)
return writer.output
|
chore: Fix quoted postcss plugins name | module.exports = () => ({
plugins: {
'postcss-easy-import': {
extensions: [
'.pcss',
'.css',
'.postcss',
'.sss'
]
},
stylelint: {
configFile: '.stylelintrc'
},
'postcss-mixins': {},
'postcss-nesting': {},
'postcss-custom-media': {},
'postcss-selector-not': {},
'postcss-discard-comments': {},
autoprefixer: {
browsers: [
'> 1%',
'last 2 versions',
'Firefox ESR',
'not ie <= 11'
]
},
cssnano: {
preset: 'default'
},
'postcss-reporter': {
clearReportedMessages: true,
noPlugin: true
}
}
});
| module.exports = () => ({
plugins: {
'postcss-easy-import': {
extensions: [
'.pcss',
'.css',
'.postcss',
'.sss'
]
},
'stylelint': {
configFile: '.stylelintrc'
},
'postcss-mixins': {},
'postcss-nesting': {},
'postcss-custom-media': {},
'postcss-selector-not': {},
'postcss-discard-comments': {},
'autoprefixer': {
browsers: [
'> 1%',
'last 2 versions',
'Firefox ESR',
'not ie <= 11'
]
},
'cssnano': {
preset: 'default'
},
'postcss-reporter': {
clearReportedMessages: true,
noPlugin: true
}
}
});
|
Use 10 iteration for bcrypt | "use strict";
var R = require('ramda');
var errors = require('../errors');
var bcrypt = require('bcrypt-nodejs');
var Promise = require('bluebird');
module.exports = {
encryptPassword: function encryptPassword(password) {
return new Promise(function(resolve, reject) {
return bcrypt.genSalt(10, function(err, salt) {
if (err) {
return reject(err);
}
return bcrypt.hash(password, salt, null, function(err, encryptedPassword) {
if (err) {
return reject(err);
}
return resolve(encryptedPassword);
});
});
});
},
comparePassword: function comparePassword(password, encryptedPassword) {
return new Promise(function(resolve, reject) {
return bcrypt.compare(password, encryptedPassword, function(err, match) {
if (err) {
return reject(err);
}
return resolve(match);
});
});
}
}; | "use strict";
var R = require('ramda');
var errors = require('../errors');
var bcrypt = require('bcrypt-nodejs');
var Promise = require('bluebird');
module.exports = {
encryptPassword: function encryptPassword(password) {
return new Promise(function(resolve, reject) {
return bcrypt.genSalt(12, function(err, salt) {
if (err) {
return reject(err);
}
return bcrypt.hash(password, salt, null, function(err, encryptedPassword) {
if (err) {
return reject(err);
}
return resolve(encryptedPassword);
});
});
});
},
comparePassword: function comparePassword(password, encryptedPassword) {
return new Promise(function(resolve, reject) {
return bcrypt.compare(password, encryptedPassword, function(err, match) {
if (err) {
return reject(err);
}
return resolve(match);
});
});
}
}; |
Enable full location for profile | from .models import MakerScienceProfile
from tastypie.resources import ModelResource
from tastypie.authorization import DjangoAuthorization
from tastypie import fields
from tastypie.constants import ALL_WITH_RELATIONS
from dataserver.authentication import AnonymousApiKeyAuthentication
from accounts.api import ProfileResource
from scout.api import PostalAddressResource
class MakerScienceProfileResource(ModelResource):
parent = fields.OneToOneField(ProfileResource, 'parent')
location = fields.ToOneField(PostalAddressResource, 'location', null=True, blank=True, full=True)
class Meta:
queryset = MakerScienceProfile.objects.all()
allowed_methods = ['get', 'post', 'put', 'patch']
resource_name = 'makerscience/profile'
authentication = AnonymousApiKeyAuthentication()
authorization = DjangoAuthorization()
always_return_data = True
filtering = {
'parent' : ALL_WITH_RELATIONS,
}
def dehydrate(self, bundle):
bundle.data["first_name"] = bundle.obj.parent.user.first_name
bundle.data["last_name"] = bundle.obj.parent.user.last_name
return bundle
| from .models import MakerScienceProfile
from tastypie.resources import ModelResource
from tastypie.authorization import DjangoAuthorization
from tastypie import fields
from tastypie.constants import ALL_WITH_RELATIONS
from dataserver.authentication import AnonymousApiKeyAuthentication
from accounts.api import ProfileResource
from scout.api import PostalAddressResource
class MakerScienceProfileResource(ModelResource):
parent = fields.OneToOneField(ProfileResource, 'parent')
location = fields.ToOneField(PostalAddressResource, 'location', null=True, blank=True)
class Meta:
queryset = MakerScienceProfile.objects.all()
allowed_methods = ['get', 'post', 'put', 'patch']
resource_name = 'makerscience/profile'
authentication = AnonymousApiKeyAuthentication()
authorization = DjangoAuthorization()
always_return_data = True
filtering = {
'parent' : ALL_WITH_RELATIONS,
}
def dehydrate(self, bundle):
bundle.data["first_name"] = bundle.obj.parent.user.first_name
bundle.data["last_name"] = bundle.obj.parent.user.last_name
return bundle |
Fix broken import in Sublime Text 2. | # encoding: utf-8
'''This adds a "slugify" command to be invoked by Sublime Text. It is made
available as "Slugify" in the command palette by Default.sublime-commands.
Parts of these commands are borrowed from the sublime-slug package:
https://github.com/madeingnecca/sublime-slug
'''
from __future__ import unicode_literals
import sublime
import sublime_plugin
try:
# This import method works in Sublime Text 2.
from slugify import slugify
except ImportError:
# While this works in Sublime Text 3.
from .slugify import slugify
class SlugifyCommand(sublime_plugin.TextCommand):
separator = '-'
def run(self, edit):
def done(value):
self.separator = value
self.view.run_command('slugify_replace', {'separator': self.separator})
window = self.view.window()
window.show_input_panel('Separator', self.separator, done, None, None)
class SlugifyReplaceCommand(sublime_plugin.TextCommand):
def run(self, edit, separator):
regions = self.view.sel()
# Only run if there is a selection.
if len(regions) > 1 or not regions[0].empty():
for region in regions:
text = self.view.substr(region)
self.view.replace(edit, region, slugify(text, separator))
| # encoding: utf-8
'''This adds a "slugify" command to be invoked by Sublime Text. It is made
available as "Slugify" in the command palette by Default.sublime-commands.
Parts of these commands are borrowed from the sublime-slug package:
https://github.com/madeingnecca/sublime-slug
'''
from __future__ import unicode_literals
import sublime
import sublime_plugin
try:
# This import method works in Sublime Text 2.
import slugify
except ImportError:
# While this works in Sublime Text 3.
from .slugify import slugify
class SlugifyCommand(sublime_plugin.TextCommand):
separator = '-'
def run(self, edit):
def done(value):
self.separator = value
self.view.run_command('slugify_replace', {'separator': self.separator})
window = self.view.window()
window.show_input_panel('Separator', self.separator, done, None, None)
class SlugifyReplaceCommand(sublime_plugin.TextCommand):
def run(self, edit, separator):
regions = self.view.sel()
# Only run if there is a selection.
if len(regions) > 1 or not regions[0].empty():
for region in regions:
text = self.view.substr(region)
self.view.replace(edit, region, slugify(text, separator))
|
Add kwarg to load function to distinguish from full install
The load function is used for a full install and thus always adds
general configuration lines to the loader file, but we don't want that
for plugin installation. | from __future__ import print_function
import os
import sys
import pkg_resources
def load(plugins=(), full_install=True):
try:
version = pkg_resources.get_distribution("virtualfish").version
commands = ["set -g VIRTUALFISH_VERSION {}".format(version)]
except pkg_resources.DistributionNotFound:
commands = []
base_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if full_install:
commands += [
"set -g VIRTUALFISH_PYTHON_EXEC {}".format(sys.executable),
"source {}".format(os.path.join(base_path, "virtual.fish")),
]
else:
commands = []
for plugin in plugins:
path = os.path.join(base_path, plugin + ".fish")
if os.path.exists(path):
commands.append("source {}".format(path))
else:
raise ValueError("Plugin does not exist: " + plugin)
if full_install:
commands.append("emit virtualfish_did_setup_plugins")
return commands
| from __future__ import print_function
import os
import sys
import pkg_resources
def load(plugins=()):
try:
version = pkg_resources.get_distribution("virtualfish").version
commands = ["set -g VIRTUALFISH_VERSION {}".format(version)]
except pkg_resources.DistributionNotFound:
commands = []
base_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
commands += [
"set -g VIRTUALFISH_PYTHON_EXEC {}".format(sys.executable),
"source {}".format(os.path.join(base_path, "virtual.fish")),
]
for plugin in plugins:
path = os.path.join(base_path, plugin + ".fish")
if os.path.exists(path):
commands.append("source {}".format(path))
else:
raise ValueError("Plugin does not exist: " + plugin)
commands.append("emit virtualfish_did_setup_plugins")
return commands
|
[KARAF-1313] Set group argument as required in cluster:group-create command
git-svn-id: 23a5554d8b20ee894ad801d0a5fe136f33ef549e@1330248 13f79535-47bb-0310-9956-ffa450edef68 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.karaf.cellar.shell.group;
import org.apache.karaf.shell.commands.Argument;
import org.apache.karaf.shell.commands.Command;
@Command(scope = "cluster", name = "group-create", description = "Create a cluster group.")
public class GroupCreateCommand extends GroupSupport {
@Argument(index = 0, name = "group", description = "The cluster group name.", required = true, multiValued = false)
String group;
@Override
protected Object doExecute() throws Exception {
return groupManager.createGroup(group);
}
}
| /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.karaf.cellar.shell.group;
import org.apache.karaf.shell.commands.Argument;
import org.apache.karaf.shell.commands.Command;
@Command(scope = "cluster", name = "group-create", description = "Create a cluster group.")
public class GroupCreateCommand extends GroupSupport {
@Argument(index = 0, name = "group", description = "The cluster group name.", required = false, multiValued = false)
String group;
@Override
protected Object doExecute() throws Exception {
return groupManager.createGroup(group);
}
}
|
Allow RSVP after hackathon ends
damn it jared | """
Submit an RSVP for the current user
"""
from django import forms
from hackfsu_com.views.generic import ApiView
from hackfsu_com.util import acl
from api.models import AttendeeStatus, Hackathon
from django.utils import timezone
class RequestForm(forms.Form):
rsvp_answer = forms.BooleanField(required=False)
extra_info = forms.CharField(required=False, max_length=500)
class RsvpView(ApiView):
request_form_class = RequestForm
allowed_after_current_hackathon_ends = True
access_manager = acl.AccessManager(acl_accept=[
acl.group_hacker,
acl.group_mentor,
acl.group_organizer,
acl.group_judge
])
def authenticate(self, request):
if not super().authenticate(request):
return False
# Add check to make sure not already RSVP'd
return AttendeeStatus.objects.filter(
hackathon=Hackathon.objects.current(), user=request.user, rsvp_submitted_at__isnull=True
).exists()
def work(self, request, req, res):
status = AttendeeStatus.objects.get(hackathon=Hackathon.objects.current(), user=request.user)
status.rsvp_result = req['rsvp_answer']
status.rsvp_submitted_at = timezone.now()
status.extra_info = req['extra_info']
status.save()
| """
Submit an RSVP for the current user
"""
from django import forms
from hackfsu_com.views.generic import ApiView
from hackfsu_com.util import acl
from api.models import AttendeeStatus, Hackathon
from django.utils import timezone
class RequestForm(forms.Form):
rsvp_answer = forms.BooleanField(required=False)
extra_info = forms.CharField(required=False, max_length=500)
class RsvpView(ApiView):
request_form_class = RequestForm
allowed_after_current_hackathon_ends = False
access_manager = acl.AccessManager(acl_accept=[
acl.group_hacker,
acl.group_mentor,
acl.group_organizer,
acl.group_judge
])
def authenticate(self, request):
if not super().authenticate(request):
return False
# Add check to make sure not already RSVP'd
return AttendeeStatus.objects.filter(
hackathon=Hackathon.objects.current(), user=request.user, rsvp_submitted_at__isnull=True
).exists()
def work(self, request, req, res):
status = AttendeeStatus.objects.get(hackathon=Hackathon.objects.current(), user=request.user)
status.rsvp_result = req['rsvp_answer']
status.rsvp_submitted_at = timezone.now()
status.extra_info = req['extra_info']
status.save()
|
Set OAuth2Template to use parameter-based client authentication (see SOCIAL-320) since Salesforce does not yet support the spec-recommended HTTP Basic client authentication. | package org.springframework.social.salesforce.connect;
import org.springframework.social.oauth2.AccessGrant;
import org.springframework.social.oauth2.OAuth2Template;
import java.util.Map;
/**
* Salesforce OAuth2Template implementation.
* <p/>
* The reason to extend is to extract non-standard instance_url from Salesforce's oauth token response.
*
* @author Umut Utkan
*/
public class SalesforceOAuth2Template extends OAuth2Template {
private String instanceUrl = null;
public SalesforceOAuth2Template(String clientId, String clientSecret, String authorizeUrl, String accessTokenUrl) {
this(clientId, clientSecret, authorizeUrl, null, accessTokenUrl);
}
public SalesforceOAuth2Template(String clientId, String clientSecret, String authorizeUrl, String authenticateUrl, String accessTokenUrl) {
super(clientId, clientSecret, authorizeUrl, authenticateUrl, accessTokenUrl);
setUseParametersForClientAuthentication(true);
}
@Override
protected AccessGrant createAccessGrant(String accessToken, String scope, String refreshToken, Integer expiresIn, Map<String, Object> response) {
this.instanceUrl = (String) response.get("instance_url");
return super.createAccessGrant(accessToken, scope, refreshToken, expiresIn, response);
}
public String getInstanceUrl() {
return instanceUrl;
}
}
| package org.springframework.social.salesforce.connect;
import org.springframework.social.oauth2.AccessGrant;
import org.springframework.social.oauth2.OAuth2Template;
import java.util.Map;
/**
* Salesforce OAuth2Template implementation.
* <p/>
* The reason to extend is to extract non-standard instance_url from Salesforce's oauth token response.
*
* @author Umut Utkan
*/
public class SalesforceOAuth2Template extends OAuth2Template {
private String instanceUrl = null;
public SalesforceOAuth2Template(String clientId, String clientSecret, String authorizeUrl, String accessTokenUrl) {
super(clientId, clientSecret, authorizeUrl, accessTokenUrl);
}
public SalesforceOAuth2Template(String clientId, String clientSecret, String authorizeUrl, String authenticateUrl, String accessTokenUrl) {
super(clientId, clientSecret, authorizeUrl, authenticateUrl, accessTokenUrl);
}
@Override
protected AccessGrant createAccessGrant(String accessToken, String scope, String refreshToken, Integer expiresIn, Map<String, Object> response) {
this.instanceUrl = (String) response.get("instance_url");
return super.createAccessGrant(accessToken, scope, refreshToken, expiresIn, response);
}
public String getInstanceUrl() {
return instanceUrl;
}
}
|
Trim for news headline newlines | const $ = require('cheerio');
const Promise = require('bluebird');
const drive = require('../drive');
const get = require('../get');
const textTemplate = require('../textTemplate');
const url = 'http://yle.fi/uutiset/osasto/news/';
const randomItem = ar => (ar[Math.floor(Math.random() * ar.length)]);
module.exports = {
id: 'news',
getText: () => Promise.all([
get(url),
drive.getContent('news', ['prefix']),
])
.then((res) => {
const doc = res[0];
const randomPrefix = randomItem(res[1].prefix);
const articles = $('section.recommends > article', doc);
const randomArticle = randomItem(articles);
const articleHeader = $('a > h1', randomArticle).text().trim();
const newsText = `${textTemplate(randomPrefix)} ${articleHeader}.`;
return Promise.resolve(newsText);
}),
};
| const $ = require('cheerio');
const Promise = require('bluebird');
const drive = require('../drive');
const get = require('../get');
const textTemplate = require('../textTemplate');
const url = 'http://yle.fi/uutiset/osasto/news/';
const randomItem = ar => (ar[Math.floor(Math.random() * ar.length)]);
module.exports = {
id: 'news',
getText: () => Promise.all([
get(url),
drive.getContent('news', ['prefix']),
])
.then((res) => {
const doc = res[0];
const randomPrefix = randomItem(res[1].prefix);
const articles = $('section.recommends > article', doc);
const randomArticle = randomItem(articles);
const articleHeader = $('a > h1', randomArticle).text();
const newsText = `${textTemplate(randomPrefix)} ${articleHeader}.`;
return Promise.resolve(newsText);
}),
};
|
Use jQuery 1.9.0 for CI | steal.config({
map: {
"*": {
"jquery/jquery.js" : "jquery",
"can/util/util.js": "can/util/jquery/jquery.js"
}
},
paths: {
"jquery": "can/lib/jquery.1.9.0.js",
"mootools/mootools.js" : "can/lib/mootools-core-1.4.3.js",
"dojo/dojo.js" : "can/util/dojo/dojo-1.8.1.js",
"yui/yui.js" : "can/lib/yui-3.7.3.js",
"zepto/zepto.js" : "can/lib/zepto.1.0rc1.js"
},
shim : {
jquery: {
exports: "jQuery"
}
},
ext: {
js: "js",
css: "css",
less: "steal/less/less.js",
coffee: "steal/coffee/coffee.js",
ejs: "can/view/ejs/ejs.js"
}
})
| steal.config({
map: {
"*": {
"jquery/jquery.js" : "jquery",
"can/util/util.js": "can/util/jquery/jquery.js"
}
},
paths: {
"jquery": "can/lib/jquery.1.8.3.js",
"mootools/mootools.js" : "can/lib/mootools-core-1.4.3.js",
"dojo/dojo.js" : "can/util/dojo/dojo-1.8.1.js",
"yui/yui.js" : "can/lib/yui-3.7.3.js",
"zepto/zepto.js" : "can/lib/zepto.1.0rc1.js"
},
shim : {
jquery: {
exports: "jQuery"
}
},
ext: {
js: "js",
css: "css",
less: "steal/less/less.js",
coffee: "steal/coffee/coffee.js",
ejs: "can/view/ejs/ejs.js"
}
})
|
Remove rendering for debugging click handlers | import Prop from 'props/prop';
import canvas from 'canvas';
import mouse from 'lib/mouse';
// http://stackoverflow.com/questions/16628184/add-onclick-and-onmouseover-to-canvas-element
export default class Clickable extends Prop {
constructor(x, y, width, height, fn) {
super(x, y, width, height);
this.fn = fn;
this.onClick = this.onClick.bind(this);
}
onClick(event) {
const coords = mouse.getCoordinates(event);
if (this.isPointInside(coords.x, coords.y)) {
this.fn();
this.destroy();
}
}
render() {
canvas.addEventListener('click', this.onClick);
}
destroy() {
canvas.removeEventListener('click', this.onClick);
}
isPointInside(x, y) {
return (x >= this.x && x <= this.x + this.width && y >= this.y && y <= this.y + this.height);
}
}
| import Prop from 'props/prop';
import canvas from 'canvas';
import mouse from 'lib/mouse';
// http://stackoverflow.com/questions/16628184/add-onclick-and-onmouseover-to-canvas-element
export default class Clickable extends Prop {
constructor(x, y, width, height, fn) {
super(x, y, width, height);
this.fn = fn;
this.onClick = this.onClick.bind(this);
}
onClick(event) {
const coords = mouse.getCoordinates(event);
if (this.isPointInside(coords.x, coords.y)) {
this.fn();
this.destroy();
}
}
render() {
canvas.addEventListener('click', this.onClick);
// @TODO: Remove this debug when complete.
super.render(null, null, 'rgba(50, 50, 50, 1)');
}
destroy() {
canvas.removeEventListener('click', this.onClick);
}
isPointInside(x, y) {
return (x >= this.x && x <= this.x + this.width && y >= this.y && y <= this.y + this.height);
}
}
|
Update file input RaisedButton example
This shows how to correctly embed a file input file into a RaisedButton ensuring that the file input remains clickable cross browser #3689 #4983 #1178 | import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import ActionAndroid from 'material-ui/svg-icons/action/android';
import FontIcon from 'material-ui/FontIcon';
const styles = {
button: {
margin: 12,
},
exampleImageInput: {
cursor: 'pointer',
position: 'absolute',
top: 0,
bottom: 0,
right: 0,
left: 0,
width: '100%',
opacity: 0,
},
};
const RaisedButtonExampleComplex = () => (
<div>
<RaisedButton
label="Choose an Image"
labelPosition="before"
style={styles.button}
containerElement="label"
>
<input type="file" style={styles.exampleImageInput} />
</RaisedButton>
<RaisedButton
label="Label before"
labelPosition="before"
primary={true}
icon={<ActionAndroid />}
style={styles.button}
/>
<RaisedButton
label="Github Link"
href="https://github.com/callemall/material-ui"
secondary={true}
style={styles.button}
icon={<FontIcon className="muidocs-icon-custom-github" />}
/>
</div>
);
export default RaisedButtonExampleComplex;
| import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import ActionAndroid from 'material-ui/svg-icons/action/android';
import FontIcon from 'material-ui/FontIcon';
const styles = {
button: {
margin: 12,
},
exampleImageInput: {
cursor: 'pointer',
position: 'absolute',
top: 0,
bottom: 0,
right: 0,
left: 0,
width: '100%',
opacity: 0,
},
};
const RaisedButtonExampleComplex = () => (
<div>
<RaisedButton
label="Choose an Image"
labelPosition="before"
style={styles.button}
>
<input type="file" style={styles.exampleImageInput} />
</RaisedButton>
<RaisedButton
label="Label before"
labelPosition="before"
primary={true}
icon={<ActionAndroid />}
style={styles.button}
/>
<RaisedButton
label="Github Link"
href="https://github.com/callemall/material-ui"
secondary={true}
style={styles.button}
icon={<FontIcon className="muidocs-icon-custom-github" />}
/>
</div>
);
export default RaisedButtonExampleComplex;
|
Load cache reload iframe as soon as we have a url
We should not wait for onload to fire because it might never fire.
Instead, we run the cache reload code as soon as we have a url, and
allow it to reload the user's browser cache. | /**
* \file cache_reload.js
* Plugin that forces a cache reload of boomerang (assuming you have server side support)
* Copyright (c) 2013, SOASTA, Inc. All rights reserved.
*/
(function() {
BOOMR = BOOMR || {};
BOOMR.plugins = BOOMR.plugins || {};
var impl = {
url: ""
};
BOOMR.plugins.CACHE_RELOAD = {
init: function(config) {
BOOMR.utils.pluginConfig(impl, config, "CACHE_RELOAD", ["url"]);
if(!impl.url)
return this;
// we use document and not BOOMR.window.document since
// we can run inside the boomerang iframe if any
var i=document.createElement('iframe');
i.style.display="none";
i.src=impl.url;
document.body.appendChild(i);
return this;
},
is_complete: function() {
// we always return true since this plugin never adds anything to the beacon
return true;
}
};
}());
| /**
* \file cache_reload.js
* Plugin that forces a cache reload of boomerang (assuming you have server side support)
* Copyright (c) 2013, SOASTA, Inc. All rights reserved.
*/
(function() {
BOOMR = BOOMR || {};
BOOMR.plugins = BOOMR.plugins || {};
var impl = {
url: "",
initialized: false
};
BOOMR.plugins.CACHE_RELOAD = {
init: function(config) {
BOOMR.utils.pluginConfig(impl, config, "CACHE_RELOAD", ["url"]);
if(this.initalized)
return this;
BOOMR.subscribe(
"page_ready",
function() {
if(!impl.url)
return;
// we use document and not BOOMR.window.document since
// we can run inside the boomerang iframe if any
var i=document.createElement('iframe');
i.style.display="none";
i.src=impl.url;
document.body.appendChild(i);
},
null,
null
);
this.initialized = true;
return this;
},
is_complete: function() {
// we always return true since this plugin never adds anything to the beacon
return true;
}
};
}());
|
Update js ajax call method | import * as utility from './utility.js'
/**
* the function to submit form via ajax in dendrogram
* @returns {void} - nothing is returned from this function.
*/
function generateBCT () {
// Show loading icon.
$('#status-analyze').css({'visibility': 'visible'})
// Convert form into an object map string to string
const form = utility.jsonifyForm()
// Send the ajax request
utility.sendAjaxRequest('/bct_analysis_result', form)
.done(
function (response) {
const static_url = $('#static-url').data().url
$('#bct-result').html(`<img src="${static_url}/${response}">`)
})
.fail(
function () {
utility.runModal('Error encountered while generating the bootstrap consensus result.')
})
.always(
function () {
$('#status-analyze').css({'visibility': 'hidden'})
})
}
/**
* When the HTML documents finish loading
*/
$(function () {
/**
* the events after dendrogram is clicked
*/
$('#get-bct').on('click', function () {
// Catch the possible error happens during submission.
const error = utility.submissionError(2)
if (error === null) { // If there is no error
generateBCT()
utility.scrollToDiv($('#bct-result'))
} else {
utility.runModal(error)
}
})
})
| import * as utility from './utility.js'
/**
* the function to submit form via ajax in dendrogram
* @returns {void} - nothing is returned from this function.
*/
function generateBCT () {
// Show loading icon.
$('#status-analyze').css({'visibility': 'visible'})
// Convert form into an object map string to string
const form = utility.jsonifyForm()
// Send the ajax request
utility.sendAjaxRequest('/bct_analysis_result', form)
.done(
function (response) {
$('#bct-result').html(response)
})
.fail(
function () {
utility.runModal('Error encountered while generating the bootstrap consensus result.')
})
.always(
function () {
$('#status-analyze').css({'visibility': 'hidden'})
})
}
/**
* When the HTML documents finish loading
*/
$(function () {
/**
* the events after dendrogram is clicked
*/
$('#get-bct').on('click', function () {
// Catch the possible error happens during submission.
const error = utility.submissionError(2)
if (error === null) { // If there is no error
generateBCT()
utility.scrollToDiv($('#bct-result'))
} else {
utility.runModal(error)
}
})
})
|
Fix only variables should be passed by reference notice | <?php
namespace OntraportAPI;
/**
* Class APIAutoloader
*
* @author ONTRAPORT
*
* @package OntraportAPI
*/
class APIAutoloader
{
public static function loader($className)
{
// Ensure correct path
if (strpos($className, "\\"))
{
$tmp = explode("\\", $className);
$className = array_pop($tmp);
}
$file = dirname(__FILE__) . "/" . $className . '.php';
if (file_exists($file))
{
require_once($file);
}
else if (strpos($file, "Exception") !== false)
{
require_once(dirname(__FILE__) . '/Exceptions/OntraportAPIException.php');
}
}
}
spl_autoload_register('\OntraportAPI\APIAutoloader::loader'); | <?php
namespace OntraportAPI;
/**
* Class APIAutoloader
*
* @author ONTRAPORT
*
* @package OntraportAPI
*/
class APIAutoloader
{
public static function loader($className)
{
// Ensure correct path
if (strpos($className, "\\"))
{
$className = array_pop(explode("\\", $className));
}
$file = dirname(__FILE__) . "/" . $className . '.php';
if (file_exists($file))
{
require_once($file);
}
else if (strpos($file, "Exception"))
{
require_once(dirname(__FILE__) . '/Exceptions/OntraportAPIException.php');
}
}
}
spl_autoload_register('\OntraportAPI\APIAutoloader::loader'); |
Add fastRender for the home | var subscriptions = new SubsManager();
Router.configure({
layoutTemplate: 'layout',
loadingTemplate: 'loading',
notFoundTemplate: 'notFound'
});
Router.route('/', {
name: 'home',
waitOn: function() {
return subscriptions.subscribe('allMangasCover');
},
fastRender: true
});
Router.route('/ownedMangas', {
name: 'ownedMangas',
waitOn: function() {
return subscriptions.subscribe('allOwnedMangas', Meteor.userId());
}
});
Router.route('/missingMangas', {
name: 'missingMangas',
waitOn: function() {
return subscriptions.subscribe('allMissingMangas', Meteor.userId());
}
});
Router.route('/:mangasName/tome/:tomeNumber/:_id', {
name: 'tomeDetails',
waitOn: function() {
return [subscriptions.subscribe('tomeDetails', this.params._id), subscriptions.subscribe('allTomes', Meteor.userId(), this.params.mangasName)];
},
data: function() {
return Mangas.findOne(this.params._id);
}
});
Router.route('/:author', {
name: 'mangaka',
waitOn: function() {
return subscriptions.subscribe('mangaka', Meteor.userId(), this.params.author);
}
});
| var subscriptions = new SubsManager();
Router.configure({
layoutTemplate: 'layout',
loadingTemplate: 'loading',
notFoundTemplate: 'notFound'
});
Router.route('/', {
name: 'home',
waitOn: function() {
return subscriptions.subscribe('allMangasCover');
}
});
Router.route('/ownedMangas', {
name: 'ownedMangas',
waitOn: function() {
return subscriptions.subscribe('allOwnedMangas', Meteor.userId());
}
});
Router.route('/missingMangas', {
name: 'missingMangas',
waitOn: function() {
return subscriptions.subscribe('allMissingMangas', Meteor.userId());
}
});
Router.route('/:mangasName/tome/:tomeNumber/:_id', {
name: 'tomeDetails',
waitOn: function() {
return [subscriptions.subscribe('tomeDetails', this.params._id), subscriptions.subscribe('allTomes', Meteor.userId(), this.params.mangasName)];
},
data: function() {
return Mangas.findOne(this.params._id);
}
});
Router.route('/:author', {
name: 'mangaka',
waitOn: function() {
return subscriptions.subscribe('mangaka', Meteor.userId(), this.params.author);
}
});
|
Add quotes around undefined when checking for type | 'use strict'
var _ = require('underscore')
/**
* Given a maze, position to start at, and a visited set, apply a randomized
* depth-first-search algorithm to the maze.
*
* @param {type} maze Maze to apply the random dfs algorithm to
* @param {type} position Current position to consider
* @param {type} visited Object containing visited maze cells
*/
var randomDfs = function (maze, position, visited) {
visited = typeof visited !== 'undefined' ? visited : {}
visited[getPositionString(position)] = true
var positions = _.shuffle(maze.getAdjacentPositionsTo(position))
positions.forEach(function (nextPosition) {
if (!visited[getPositionString(nextPosition)]) {
maze.setWallBetween(position, nextPosition, false)
randomDfs(maze, nextPosition, visited)
}
})
}
/**
* Given a position, return a string representing it.
*
* @param {Position} position description
* @return {String} A string representing position
*/
var getPositionString = function (position) {
return position.x.toString() + ',' + position.y.toString()
}
module.exports = randomDfs
| 'use strict'
var _ = require('underscore')
/**
* Given a maze, position to start at, and a visited set, apply a randomized
* depth-first-search algorithm to the maze.
*
* @param {type} maze Maze to apply the random dfs algorithm to
* @param {type} position Current position to consider
* @param {type} visited Object containing visited maze cells
*/
var randomDfs = function (maze, position, visited) {
visited = typeof visited !== undefined ? visited : {}
visited[getPositionString(position)] = true
var positions = _.shuffle(maze.getAdjacentPositionsTo(position))
positions.forEach(function (nextPosition) {
if (!visited[getPositionString(nextPosition)]) {
maze.setWallBetween(position, nextPosition, false)
randomDfs(maze, nextPosition, visited)
}
})
}
/**
* Given a position, return a string representing it.
*
* @param {Position} position description
* @return {String} A string representing position
*/
var getPositionString = function (position) {
return position.x.toString() + ',' + position.y.toString()
}
module.exports = randomDfs
|
Fix path to emial.hbs in second-emial.js
related #143 | 'use strict';
const handelbars = require('handlebars');
const fs = require('fs');
const path = require('path');
const nodemailer = require('nodemailer');
require('env2')(`${__dirname}/../.env`);
// create reusable transporter object using the default SMTP transport
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.EMAIL,
pass: process.env.PASS
}
});
function sendMail(emailAddress, emailContent, cb){
const emailTemplate = fs.readFileSync(path.join(__dirname, '..', 'src', 'templates' ,'views', 'email.hbs'), 'utf8');
const template = handelbars.compile(emailTemplate);
const emailBody = template(emailContent);
const mailOptions = {
from: '"CAMHS π" <welcome.to.cahms@hotmail.co.uk>',
subject: 'Getting to know you Questionnaire',
text: 'Questionnaire',
html: emailBody,
to: emailAddress
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return cb(error)
}
return cb(null, `Message ${info.messageId} sent: ${info.response}`)
});
}
module.exports = sendMail;
| 'use strict';
const handelbars = require('handlebars');
const fs = require('fs');
const path = require('path');
const nodemailer = require('nodemailer');
require('env2')(`${__dirname}/../.env`);
// create reusable transporter object using the default SMTP transport
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.EMAIL,
pass: process.env.PASS
}
});
function sendMail(emailAddress, emailContent, cb){
const emailTemplate = fs.readFileSync(path.join(__dirname, '..', 'public', 'views', 'email.hbs'), 'utf8');
const template = handelbars.compile(emailTemplate);
const emailBody = template(emailContent);
const mailOptions = {
from: '"CAMHS π" <welcome.to.cahms@hotmail.co.uk>',
subject: 'Getting to know you Questionnaire',
text: 'Questionnaire',
html: emailBody,
to: emailAddress
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return cb(error)
}
return cb(null, `Message ${info.messageId} sent: ${info.response}`)
});
}
module.exports = sendMail;
|
installer: Use replaceState for updating the URL
Disables back button. The other option is to allow navigating between
steps using the browser's back/forward, but that overlaps with the
current behaviour of picking up an existing install process using the
base URL. This is a temporary fix and will be revisited soon.
refs #1337
Signed-off-by: Jesse Stuart <a5c95b3d7cb4d0ae05a15c79c79ab458dc2c8f9e@jessestuart.ca> | import Router from 'marbles/router';
import WizardComponent from './views/wizard';
import Dispatcher from './dispatcher';
var MainRouter = Router.createClass({
routes: [
{ path: '', handler: 'landingPage' },
{ path: '/install/:install_id', handler: 'landingPage' }
],
willInitialize: function () {
Dispatcher.register(this.handleEvent.bind(this));
},
beforeHandler: function (event) {
Dispatcher.dispatch({
name: 'LOAD_INSTALL',
id: event.params[0].install_id || ''
});
},
landingPage: function (params, opts, context) {
var props = {
dataStore: context.dataStore
};
context.render(WizardComponent, props);
},
handleEvent: function (event) {
var installID;
switch (event.name) {
case 'INSTALL_EXISTS':
installID = this.history.pathParams[0].install_id;
if ( !event.exists && (!event.id || event.id === installID) ) {
this.history.navigate('/', { replace: true });
} else if (event.exists && installID !== event.id) {
this.history.navigate('/install/'+ event.id, { replace: true });
}
break;
case 'LAUNCH_INSTALL_SUCCESS':
installID = event.res.id;
this.history.navigate('/install/'+ installID, { replace: true });
break;
}
}
});
export default MainRouter;
| import Router from 'marbles/router';
import WizardComponent from './views/wizard';
import Dispatcher from './dispatcher';
var MainRouter = Router.createClass({
routes: [
{ path: '', handler: 'landingPage' },
{ path: '/install/:install_id', handler: 'landingPage' }
],
willInitialize: function () {
Dispatcher.register(this.handleEvent.bind(this));
},
beforeHandler: function (event) {
Dispatcher.dispatch({
name: 'LOAD_INSTALL',
id: event.params[0].install_id || ''
});
},
landingPage: function (params, opts, context) {
var props = {
dataStore: context.dataStore
};
context.render(WizardComponent, props);
},
handleEvent: function (event) {
var installID;
switch (event.name) {
case 'INSTALL_EXISTS':
installID = this.history.pathParams[0].install_id;
if ( !event.exists && (!event.id || event.id === installID) ) {
this.history.navigate('/');
} else if (event.exists && installID !== event.id) {
this.history.navigate('/install/'+ event.id);
}
break;
case 'LAUNCH_INSTALL_SUCCESS':
installID = event.res.id;
this.history.navigate('/install/'+ installID);
break;
}
}
});
export default MainRouter;
|
Use sort,pop,remove and so on. | #!/usr/local/bin/python
#a=[1,2,3,4,5,6,7,8,9,10]
#print a[:3]
#print a[-3:]
#print a[:]
#print a[::2]
#print a[8:3:-1]
#print [1,2,3]+[4,5,6]
#print ["Hi"]*3
#print 1 in a
#print max(a)
#print min(a)
#print len(a)
#print list("Hello")
#b=[1,3,5,7,9,8]
#b[1]=4
#print b
#del b[1]
#print b
#c=list("Perl")
#c[1:1]=list('ython')
#c[-4:]=[]
#c.append('n')
#print c.count('t')
#print c
#d=[1,2,3]
#d.extend([4,5,6])
#print d
#e=[7,8,9]
#print e+[10,11,12]
#print e
f=list("abcdefg")
print f.index('c')
f.insert(len(f),'h')
print f
print f.pop()
f.append('h')
print f
f.remove('h')
print f
g=[1,2,3]
g.reverse()
print g
h=[3,4,8,2,6]
i=h[:]
i.sort()
print i
h.sort(reverse=True)
print h
j=['ads','dd','eeeee','asdsadd']
print j.sort(key=len)
print j
| #!/usr/local/bin/python
#a=[1,2,3,4,5,6,7,8,9,10]
#print a[:3]
#print a[-3:]
#print a[:]
#print a[::2]
#print a[8:3:-1]
#print [1,2,3]+[4,5,6]
#print ["Hi"]*3
#print 1 in a
#print max(a)
#print min(a)
#print len(a)
#print list("Hello")
#b=[1,3,5,7,9,8]
#b[1]=4
#print b
#del b[1]
#print b
c=list("Perl")
c[1:1]=list('ython')
c[-4:]=[]
c.append('n')
print c.count('t')
print c
d=[1,2,3]
d.extend([4,5,6])
print d
e=[7,8,9]
print e+[10,11,12]
print e
|
Fix import error for boto.utils | import logging
import socket
from boto.utils import get_instance_metadata
LOG_FORMAT = '%(asctime)s [%(name)s] %(levelname)s %(message)s'
LOG_DATE = '%Y-%m-%d %I:%M:%S %p'
logging.basicConfig(format=LOG_FORMAT, datefmt=LOG_DATE, level=logging.WARN)
logger = logging.getLogger('yoda-discover')
logger.level = logging.INFO
def port_test(port, host, protocol='tcp'):
if isinstance(port, str):
port = int(port)
sock_type = socket.SOCK_DGRAM if protocol == 'udp' else socket.SOCK_STREAM
sock = socket.socket(socket.AF_INET, sock_type)
sock.settimeout(2000)
try:
sock.connect((host, port))
sock.shutdown(socket.SHUT_RDWR)
sock.close()
return True
except socket.error as error:
logger.warn('Port test failed for host: %s port: %s. Reason: %s',
host, port, error)
return False
def map_proxy_host(proxy_host):
proxy_host = proxy_host.lower()
if proxy_host.startswith('ec2:meta-data:'):
meta_data = proxy_host.replace('ec2:meta-data:', '')
return get_instance_metadata()[meta_data]
return proxy_host
| import logging
import socket
import boto
LOG_FORMAT = '%(asctime)s [%(name)s] %(levelname)s %(message)s'
LOG_DATE = '%Y-%m-%d %I:%M:%S %p'
logging.basicConfig(format=LOG_FORMAT, datefmt=LOG_DATE, level=logging.WARN)
logger = logging.getLogger('yoda-discover')
logger.level = logging.INFO
def port_test(port, host, protocol='tcp'):
if isinstance(port, str):
port = int(port)
sock_type = socket.SOCK_DGRAM if protocol == 'udp' else socket.SOCK_STREAM
sock = socket.socket(socket.AF_INET, sock_type)
sock.settimeout(2000)
try:
sock.connect((host, port))
sock.shutdown(socket.SHUT_RDWR)
sock.close()
return True
except socket.error as error:
logger.warn('Port test failed for host: %s port: %s. Reason: %s',
host, port, error)
return False
def map_proxy_host(proxy_host):
proxy_host = proxy_host.lower()
if proxy_host.startswith('ec2:meta-data:'):
meta_data = proxy_host.replace('ec2:meta-data:', '')
return boto.utils.get_instance_metadata()[meta_data]
return proxy_host
|
Reduce normal request timeout to 5 minutes |
PASSWORD_PLACEHOLDER = '*' * 16
# If any remote service does not respond within 5 minutes, time out
REQUEST_TIMEOUT = 5 * 60
ALGO_AES = 'aes'
DATA_TYPE_UNKNOWN = None
COMMCARE_DATA_TYPE_TEXT = 'cc_text'
COMMCARE_DATA_TYPE_INTEGER = 'cc_integer'
COMMCARE_DATA_TYPE_DECIMAL = 'cc_decimal'
COMMCARE_DATA_TYPE_DATE = 'cc_date'
COMMCARE_DATA_TYPE_DATETIME = 'cc_datetime'
COMMCARE_DATA_TYPE_TIME = 'cc_time'
COMMCARE_DATA_TYPES = (
COMMCARE_DATA_TYPE_TEXT,
COMMCARE_DATA_TYPE_INTEGER,
COMMCARE_DATA_TYPE_DECIMAL,
COMMCARE_DATA_TYPE_DATE,
COMMCARE_DATA_TYPE_DATETIME,
COMMCARE_DATA_TYPE_TIME,
)
DIRECTION_IMPORT = 'in'
DIRECTION_EXPORT = 'out'
DIRECTION_BOTH = None
DIRECTIONS = (
DIRECTION_IMPORT,
DIRECTION_EXPORT,
DIRECTION_BOTH,
)
|
PASSWORD_PLACEHOLDER = '*' * 16
# If any remote service does not respond within 10 minutes, time out
REQUEST_TIMEOUT = 600
ALGO_AES = 'aes'
DATA_TYPE_UNKNOWN = None
COMMCARE_DATA_TYPE_TEXT = 'cc_text'
COMMCARE_DATA_TYPE_INTEGER = 'cc_integer'
COMMCARE_DATA_TYPE_DECIMAL = 'cc_decimal'
COMMCARE_DATA_TYPE_DATE = 'cc_date'
COMMCARE_DATA_TYPE_DATETIME = 'cc_datetime'
COMMCARE_DATA_TYPE_TIME = 'cc_time'
COMMCARE_DATA_TYPES = (
COMMCARE_DATA_TYPE_TEXT,
COMMCARE_DATA_TYPE_INTEGER,
COMMCARE_DATA_TYPE_DECIMAL,
COMMCARE_DATA_TYPE_DATE,
COMMCARE_DATA_TYPE_DATETIME,
COMMCARE_DATA_TYPE_TIME,
)
DIRECTION_IMPORT = 'in'
DIRECTION_EXPORT = 'out'
DIRECTION_BOTH = None
DIRECTIONS = (
DIRECTION_IMPORT,
DIRECTION_EXPORT,
DIRECTION_BOTH,
)
|
Move checker.configure(...) line to beforeeach | var Checker = require('../lib/checker');
var assert = require('assert');
describe('rules/require-blocks-on-newline', function() {
var checker;
beforeEach(function() {
checker = new Checker();
checker.registerDefaultRules();
checker.configure({ requireBlocksOnNewline: true });
});
it('should report missing newline after opening brace', function() {
assert(checker.checkString('if (true) {abc();\n}').getErrorCount() === 1);
});
it('should report missing newline before closing brace', function() {
assert(checker.checkString('if (true) {\nabc();}').getErrorCount() === 1);
});
it('should report missing newlines in both cases', function() {
assert(checker.checkString('if (true) {abc();}').getErrorCount() === 2);
});
it('should not report with no spaces', function() {
assert(checker.checkString('if (true) {\nabc();\n}').isEmpty());
});
it('should not report empty function definitions', function() {
assert(checker.checkString('var a = function() {};').isEmpty());
});
});
| var Checker = require('../lib/checker');
var assert = require('assert');
describe('rules/require-blocks-on-newline', function() {
var checker;
beforeEach(function() {
checker = new Checker();
checker.registerDefaultRules();
});
it('should report missing newline after opening brace', function() {
checker.configure({ requireBlocksOnNewline: true });
assert(checker.checkString('if (true) {abc();\n}').getErrorCount() === 1);
});
it('should report missing newline before closing brace', function() {
checker.configure({ requireBlocksOnNewline: true });
assert(checker.checkString('if (true) {\nabc();}').getErrorCount() === 1);
});
it('should report missing newlines in both cases', function() {
checker.configure({ requireBlocksOnNewline: true });
assert(checker.checkString('if (true) {abc();}').getErrorCount() === 2);
});
it('should not report with no spaces', function() {
checker.configure({ requireBlocksOnNewline: true });
assert(checker.checkString('if (true) {\nabc();\n}').isEmpty());
});
it('should not report empty function definitions', function() {
checker.configure({ requireBlocksOnNewline: true });
assert(checker.checkString('var a = function() {};').isEmpty());
});
});
|
Add one missing return type. | // @flow
const isKataLine = (line) => line.trim().startsWith('////');
const enableKataLine = (line) => line.replace(/\/\/\/\/\s*/, '');
const removeLinesAfterKataLine = (_, lineIndex, lines) => {
if (lineIndex === 0) return true;
const previousLine = lines[lineIndex-1];
return !isKataLine(previousLine);
};
export const kataifyFile = (fileContent: string): string => {
const lines = fileContent.split('\n');
return lines
.filter(removeLinesAfterKataLine)
.map(enableKataLine)
.join('\n')
;
};
export const kataify = (
kataifyableList: KataifyableListType,
deps: KataifyDeps
): Promise<*> => {
const kataifyableToTask = (kataifyable) =>
deps.readFile(kataifyable.sourceFilename)
.then(kataifyFile)
.then(content => deps.writeFile(kataifyable.destinationFilename, content))
;
return Promise.all(kataifyableList.map(kataifyableToTask));
};
| // @flow
const isKataLine = (line) => line.trim().startsWith('////');
const enableKataLine = (line) => line.replace(/\/\/\/\/\s*/, '');
const removeLinesAfterKataLine = (_, lineIndex, lines) => {
if (lineIndex === 0) return true;
const previousLine = lines[lineIndex-1];
return !isKataLine(previousLine);
};
export const kataifyFile = (fileContent: string) => {
const lines = fileContent.split('\n');
return lines
.filter(removeLinesAfterKataLine)
.map(enableKataLine)
.join('\n')
;
};
export const kataify = (
kataifyableList: KataifyableListType,
deps: KataifyDeps
): Promise<*> => {
const kataifyableToTask = (kataifyable) =>
deps.readFile(kataifyable.sourceFilename)
.then(kataifyFile)
.then(content => deps.writeFile(kataifyable.destinationFilename, content))
;
return Promise.all(kataifyableList.map(kataifyableToTask));
};
|
Add proper classpath to syntax tests
To prevent unknown type errors being spewed on stderr. | package syntax;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.extendj.JavaChecker;
import org.extendj.parser.JavaParser;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.*;
public abstract class SyntaxTestBase {
private static final String DIR = "src/test/resources/syntax/";
private static class Checker extends JavaChecker {
private String runChecker(String file) throws IOException {
run(new String[]{"-classpath", "build/classes/main", file});
return program.structuredPrettyPrint();
}
}
private static String slurp(String file) throws IOException {
return new String(Files.readAllBytes(Paths.get(file)), UTF_8);
}
protected void checkSyntax(String name) {
String actual, expected;
try {
actual = new Checker().runChecker(DIR + name + ".java");
expected = slurp(DIR + name + ".expected");
}
catch (IOException e) {
throw new RuntimeException(e);
}
assertEquals(expected.trim(), actual.trim());
}
}
| package syntax;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.extendj.JavaChecker;
import org.extendj.parser.JavaParser;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.*;
public abstract class SyntaxTestBase {
private static final String DIR = "src/test/resources/syntax/";
private static class Checker extends JavaChecker {
private String runChecker(String file) throws IOException {
run(new String[]{file});
return program.structuredPrettyPrint();
}
}
private static String slurp(String file) throws IOException {
return new String(Files.readAllBytes(Paths.get(file)), UTF_8);
}
protected void checkSyntax(String name) {
String actual, expected;
try {
actual = new Checker().runChecker(DIR + name + ".java");
expected = slurp(DIR + name + ".expected");
}
catch (IOException e) {
throw new RuntimeException(e);
}
assertEquals(expected.trim(), actual.trim());
}
}
|
Split feeds and app config locations. | var fs = require('fs');
var p = require('path');
var slug = require('slug');
var url = require('url');
var util = require('util');
slug.defaults.mode ='rfc3986';
var env = process.env['FEEDPAPER_ENV'];
var feedsCategories = JSON.parse(fs.readFileSync(p.join('../conf', env, 'feeds.json')));
var conf = JSON.parse(fs.readFileSync(p.join('../../config/studio/feedpaper', env, 'feedpaper.json')));
// in lieu of AE86 pre-hook
var apiBase = url.format({
protocol: conf.api.protocol,
hostname: conf.api.host,
pathname: util.format('v%d/%s', conf.api.version, conf.api.path)
});
var globalJs = fs.readFileSync(p.join('static', 'scripts', 'global.js.tpl'), 'utf-8');
globalJs = globalJs.replace(/var apiBase = 'PLACEHOLDER';/, util.format('var apiBase = \'%s\';', apiBase));
fs.writeFileSync(p.join('static', 'scripts', 'global.js'), globalJs)
exports.params = {
slug: function(title, cb) {
cb(slug(title));
},
sitemap: {
'index.html': { title: 'Feedpaper' }
},
categories: feedsCategories
};
| var fs = require('fs');
var p = require('path');
var slug = require('slug');
var url = require('url');
var util = require('util');
slug.defaults.mode ='rfc3986';
var env = process.env['FEEDPAPER_ENV'];
var feedsCategories = JSON.parse(fs.readFileSync(p.join('..', 'conf', env, 'feeds.json')));
var conf = JSON.parse(fs.readFileSync(p.join('..', 'conf', env, 'feedpaper.json')));
// in lieu of AE86 pre-hook
var apiBase = url.format({
protocol: conf.api.protocol,
hostname: conf.api.host,
pathname: util.format('v%d/%s', conf.api.version, conf.api.path)
});
var globalJs = fs.readFileSync(p.join('static', 'scripts', 'global.js.tpl'), 'utf-8');
globalJs = globalJs.replace(/var apiBase = 'PLACEHOLDER';/, util.format('var apiBase = \'%s\';', apiBase));
fs.writeFileSync(p.join('static', 'scripts', 'global.js'), globalJs)
exports.params = {
slug: function(title, cb) {
cb(slug(title));
},
sitemap: {
'index.html': { title: 'Feedpaper' }
},
categories: feedsCategories
};
|
Change the base URL for the Twitter API | import email
import datetime
import re
from django.conf import settings
import twitter
from parliament.core.models import Politician, PoliticianInfo
from parliament.activity import utils as activity
def save_tweets():
twitter_to_pol = dict([(i.value.lower(), i.politician) for i in PoliticianInfo.objects.filter(schema='twitter').select_related('politician')])
twit = twitter.Twitter(domain='api.twitter.com/1')
statuses = twit.openparlca.lists.mps.statuses(per_page=200)
statuses.reverse()
for status in statuses:
pol = twitter_to_pol[status['user']['screen_name'].lower()]
date = datetime.date.fromtimestamp(
email.utils.mktime_tz(
email.utils.parsedate_tz(status['created_at'])
)
) # fuck you, time formats
guid = 'twit_%s' % status['id']
# Twitter apparently escapes < > but not & "
# so I'm clunkily unescaping lt and gt then reescaping in the template
text = status['text'].replace('<', '<').replace('>', '>')
activity.save_activity({'text': status['text']}, politician=pol,
date=date, guid=guid, variety='twitter')
| import email
import datetime
import re
from django.conf import settings
import twitter
from parliament.core.models import Politician, PoliticianInfo
from parliament.activity import utils as activity
def save_tweets():
twitter_to_pol = dict([(i.value.lower(), i.politician) for i in PoliticianInfo.objects.filter(schema='twitter').select_related('politician')])
twit = twitter.Twitter()
statuses = twit.openparlca.lists.mps.statuses(per_page=200)
statuses.reverse()
for status in statuses:
pol = twitter_to_pol[status['user']['screen_name'].lower()]
date = datetime.date.fromtimestamp(
email.utils.mktime_tz(
email.utils.parsedate_tz(status['created_at'])
)
) # fuck you, time formats
guid = 'twit_%s' % status['id']
# Twitter apparently escapes < > but not & "
# so I'm clunkily unescaping lt and gt then reescaping in the template
text = status['text'].replace('<', '<').replace('>', '>')
activity.save_activity({'text': status['text']}, politician=pol,
date=date, guid=guid, variety='twitter')
|
Convert Windows CI to use Microsoft MCR image urls
Signed-off-by: Justin Terry (VM) <f0c38945ef01caad6a7c3d4b90a29703264b34a4@microsoft.com> | /*
Copyright The containerd Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package containerd
import (
"os"
"path/filepath"
)
const (
defaultAddress = `\\.\pipe\containerd-containerd-test`
testImage = "mcr.microsoft.com/windows/nanoserver:sac2016"
)
var (
defaultRoot = filepath.Join(os.Getenv("programfiles"), "containerd", "root-test")
defaultState = filepath.Join(os.Getenv("programfiles"), "containerd", "state-test")
)
| /*
Copyright The containerd Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package containerd
import (
"os"
"path/filepath"
)
const (
defaultAddress = `\\.\pipe\containerd-containerd-test`
testImage = "docker.io/microsoft/nanoserver@sha256:8f78a4a7da4464973a5cd239732626141aec97e69ba3e4023357628630bc1ee2"
)
var (
defaultRoot = filepath.Join(os.Getenv("programfiles"), "containerd", "root-test")
defaultState = filepath.Join(os.Getenv("programfiles"), "containerd", "state-test")
)
|
Fix babelLoaderMatcher for other npm install tool
like https://github.com/cnpm/npminstall | const babelLoaderMatcher = function(rule) {
return rule.loader && rule.loader.indexOf("babel-loader/") != -1;
}
const getLoader = function(rules, matcher) {
var loader;
rules.some(rule => {
return loader = matcher(rule)
? rule
: getLoader(rule.use || rule.oneOf || [], matcher);
});
return loader;
};
const getBabelLoader = function(rules) {
return getLoader(rules, babelLoaderMatcher);
}
const injectBabelPlugin = function(pluginName, config) {
const loader = getBabelLoader(config.module.rules);
if (!loader) {
console.log("babel-loader not found");
return config;
}
loader.options.plugins = [pluginName].concat(loader.options.plugins || []);
return config;
};
module.exports = { getLoader, getBabelLoader, injectBabelPlugin };
| const babelLoaderMatcher = function(rule) {
return rule.loader && rule.loader.indexOf("/babel-loader/") != -1;
}
const getLoader = function(rules, matcher) {
var loader;
rules.some(rule => {
return loader = matcher(rule)
? rule
: getLoader(rule.use || rule.oneOf || [], matcher);
});
return loader;
};
const getBabelLoader = function(rules) {
return getLoader(rules, babelLoaderMatcher);
}
const injectBabelPlugin = function(pluginName, config) {
const loader = getBabelLoader(config.module.rules);
if (!loader) {
console.log("babel-loader not found");
return config;
}
loader.options.plugins = [pluginName].concat(loader.options.plugins || []);
return config;
};
module.exports = { getLoader, getBabelLoader, injectBabelPlugin };
|
Fix order of classifiers
The list should be alphabetical. N comes after L. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
settings = dict()
# Publish
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
settings.update(
name='whenpy',
version='0.1.0',
description='Friendly Dates and Times',
long_description=open('README.rst').read(),
author='Andy Dirnberger',
author_email='dirn@dirnonline.com',
url='https://github.com/dirn/when.py',
packages=['when'],
install_requires=['pytz'],
license=open('LICENSE').read(),
classifiers=(
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: Python 2.6',
'Programming Language :: Python :: Python 2.7',
'Topic :: Software Development :: Libraries :: Python Modules',
),
)
setup(**settings)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
settings = dict()
# Publish
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
settings.update(
name='whenpy',
version='0.1.0',
description='Friendly Dates and Times',
long_description=open('README.rst').read(),
author='Andy Dirnberger',
author_email='dirn@dirnonline.com',
url='https://github.com/dirn/when.py',
packages=['when'],
install_requires=['pytz'],
license=open('LICENSE').read(),
classifiers=(
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: Python 2.6',
'Programming Language :: Python :: Python 2.7',
'Topic :: Software Development :: Libraries :: Python Modules',
),
)
setup(**settings)
|
Test for existence of node before clearing it | """
Classes for customising node caching.
"""
class BasicCacher(object):
"""
Basic in-memory caching.
"""
def __init__(self, logger=None):
self._cache = {}
self.logger = logger
def set_cache(self, node, data):
"""
Store some data on the object.
"""
self._cache[node.label] = data
def get_cache(self, node):
"""
Return cached data.
"""
return self._cache.get(node.label)
def has_cache(self, node):
return self._cache.get(node.label) is not None
def clear_cache(self, node):
if self._cache.get(node.label):
del self._cache[node.label]
def clear(self):
self._cache = {}
def __repr__(self):
return "<%s>" % self.__class__.__name__
| """
Classes for customising node caching.
"""
class BasicCacher(object):
"""
Basic in-memory caching.
"""
def __init__(self, logger=None):
self._cache = {}
self.logger = logger
def set_cache(self, node, data):
"""
Store some data on the object.
"""
self._cache[node.label] = data
def get_cache(self, node):
"""
Return cached data.
"""
return self._cache.get(node.label)
def has_cache(self, node):
return self._cache.get(node.label) is not None
def clear_cache(self, node):
del self._cache[node.label]
def clear(self):
self._cache = {}
def __repr__(self):
return "<%s>" % self.__class__.__name__
|
Add fix for frost-guide that filters out nested folders | import Ember from 'ember'
import svgs from 'ember-frost-core/svgs'
import _ from 'lodash/lodash'
export default Ember.Controller.extend({
backgroundColors: [
'bg-tile-color',
'bg-content-color',
'bg-info-color',
'bg-hint-text-color',
'bg-line-color',
'bg-main-button-color'
],
backgroundColor: 'bg-tile-color',
entries: Ember.computed(function () {
return _.keys(svgs).reduce((entries, category) => {
return _.union(entries, _.keys(svgs[category]).map((entry) => {
const icon = `${category}/${entry}`
return {
icon,
markdown: `\`${icon}\``
}
}).filter((entry) => {
// filter out objects when used on frost-guide as it picks up other svgs (folder in folder)
// these nested folders return as objects with its properties equal to folders inside
if (typeof Ember.get(svgs, entry.icon.replace(/\//g, '.')) === 'string') {
return true
}
}))
}, [])
}),
actions: {
colorSelected (color) {
console.log(`selected: ${color}`)
this.set('backgroundColor', color)
}
}
})
| import Ember from 'ember'
import svgs from 'ember-frost-core/svgs'
import _ from 'lodash/lodash'
export default Ember.Controller.extend({
backgroundColors: [
'bg-tile-color',
'bg-content-color',
'bg-info-color',
'bg-hint-text-color',
'bg-line-color',
'bg-main-button-color'
],
backgroundColor: 'bg-tile-color',
entries: Ember.computed(function () {
return _.keys(svgs).reduce((entries, category) => {
return _.union(entries, _.keys(svgs[category]).map((entry) => {
const icon = `${category}/${entry}`
return {
icon,
markdown: `\`${icon}\``
}
}))
}, [])
}),
actions: {
colorSelected (color) {
console.log(`selected: ${color}`)
this.set('backgroundColor', color)
}
}
})
|
Move koala-serializer to extra requirements | import sys
from setuptools import setup, find_packages
setup(
name='chillin-server',
version='2.0.0',
description='Chillin AI Game Framework (Python Server)',
long_description='',
author='Koala',
author_email='mdan.hagh@gmail.com',
url='https://github.com/koala-team/Chillin-PyServer',
keywords='ai game framework chillin',
classifiers=[
'Environment :: Console',
'License :: OSI Approved :: GNU Affero General Public License v3',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.5',
'Topic :: Software Development :: Libraries :: Application Frameworks'
],
license='AGPL License, Version 3.0',
install_requires=[
'circuits==3.2',
'pydblite==3.0.4',
'configparser==3.5.0',
'enum34==1.1.6'
],
extras_require={
'dev': ['koala-serializer']
},
packages=find_packages(),
package_data={
'chillin_server': ['default_certs/*']
}
)
| import sys
from setuptools import setup, find_packages
setup(
name='chillin-server',
version='2.0.0',
description='Chillin AI Game Framework (Python Server)',
long_description='',
author='Koala',
author_email='mdan.hagh@gmail.com',
url='https://github.com/koala-team/Chillin-PyServer',
keywords='ai game framework chillin',
classifiers=[
'Environment :: Console',
'License :: OSI Approved :: GNU Affero General Public License v3',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.5',
'Topic :: Software Development :: Libraries :: Application Frameworks'
],
license='AGPL License, Version 3.0',
install_requires=[
'circuits==3.2',
'pydblite==3.0.4',
'koala-serializer==0.6.3',
'configparser==3.5.0',
'enum34==1.1.6'
],
packages=find_packages(),
package_data={
'chillin_server': ['default_certs/*']
}
)
|
Write 100 records and flush every 10 during HDFSDatasetWriter write test. | package com.cloudera.data.hdfs;
import java.io.File;
import java.io.IOException;
import org.apache.avro.Schema;
import org.apache.avro.Schema.Type;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.google.common.io.Files;
public class TestHDFSDatasetWriter {
private File testDirectory;
private FileSystem fileSystem;
@Before
public void setUp() throws IOException {
testDirectory = Files.createTempDir();
Configuration conf = new Configuration();
conf.set("fs.default.name", "file:///");
fileSystem = FileSystem.get(conf);
}
@After
public void tearDown() throws IOException {
fileSystem.delete(new Path(testDirectory.getAbsolutePath()), true);
}
@Test
public void testWrite() throws IOException {
HDFSDatasetWriter<String> writer = new HDFSDatasetWriter<String>(
fileSystem, new Path(testDirectory.getAbsolutePath(), "write-1.avro"),
Schema.create(Type.STRING));
writer.open();
for (int i = 0; i < 100; i++) {
writer.write("entry " + i);
if (i % 10 == 0) {
writer.flush();
}
}
writer.close();
}
}
| package com.cloudera.data.hdfs;
import java.io.File;
import java.io.IOException;
import org.apache.avro.Schema;
import org.apache.avro.Schema.Type;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.google.common.io.Files;
public class TestHDFSDatasetWriter {
private File testDirectory;
private FileSystem fileSystem;
@Before
public void setUp() throws IOException {
testDirectory = Files.createTempDir();
Configuration conf = new Configuration();
conf.set("fs.default.name", "file:///");
fileSystem = FileSystem.get(conf);
}
@After
public void tearDown() throws IOException {
fileSystem.delete(new Path(testDirectory.getAbsolutePath()), true);
}
@Test
public void testWrite() throws IOException {
HDFSDatasetWriter<String> writer = new HDFSDatasetWriter<String>(
fileSystem, new Path(testDirectory.getAbsolutePath(), "write-1.avro"),
Schema.create(Type.STRING));
writer.open();
for (int i = 0; i < 10; i++) {
writer.write("entry " + i);
}
writer.close();
}
}
|
Remove li tag around the button. Disable the button when the editor is in edit mode. | angular.module('ngWig')
.config(['ngWigToolbarProvider', function (ngWigToolbarProvider) {
ngWigToolbarProvider.addCustomButton('forecolor', 'nw-forecolor-button');
}])
.directive('nwForecolorButton', function() {
return {
restrict: 'E',
replace: true,
template: '<button colorpicker ng-model="fontcolor" ng-disabled="editMode" colorpicker-position="right" class="nw-button" title="Font Color"><i class="fa fa-font"></i></button>',
link: function (scope) {
scope.$on("colorpicker-selected", function ($event, color) {
scope.execCommand('foreColor', color.value);
});
}
};
});
| angular.module('ngWig')
.config(['ngWigToolbarProvider', function (ngWigToolbarProvider) {
ngWigToolbarProvider.addCustomButton('forecolor', 'nw-forecolor-button');
}])
.directive('nwForecolorButton', function() {
return {
restrict: 'E',
replace: true,
template: '<li class="nw-toolbar__item"><button colorpicker ng-model="fontcolor" colorpicker-position="right" class="nw-button" title="Font Color"><i class="fa fa-font"></i></button></li>',
link: function (scope) {
scope.$on("colorpicker-selected", function ($event, color) {
scope.execCommand('foreColor', color.value);
});
}
};
});
|
Rename test to use class convention | <?php
use Rawebone\Tapped\Comparator;
use Rawebone\Tapped\Extension;
use Rawebone\Tapped\Extensions;
use function Rawebone\Tapped\test;
test(Extensions::class, function ($expect) {
$extension = new class extends Extension
{
function boot() { $this->boot = true; }
function comparisons(Comparator $c) { $this->comparisons = true; }
function setup() { $this->setup = true; }
function tearDown() { $this->tearDown = true; }
function shutdown() { $this->shutdown = true; }
};
$extensions = new Extensions;
$extensions->registerMany([$extension]);
$extensions->boot();
$extensions->comparisons(new Comparator);
$extensions->setup();
$extensions->tearDown();
$extensions->shutdown();
$expect($extension->boot)->toEqual(true)->when('Extensions can be booted');
$expect($extension->comparisons)->toEqual(true)->when('Extensions can register comparisons');
$expect($extension->setup)->toEqual(true)->when('Extensions can be setup');
$expect($extension->tearDown)->toEqual(true)->when('Extensions can be torn down');
$expect($extension->shutdown)->toEqual(true)->when('Extensions can be shutdown');
});
| <?php
use Rawebone\Tapped\Comparator;
use Rawebone\Tapped\Extension;
use Rawebone\Tapped\Extensions;
use function Rawebone\Tapped\test;
test('Extensions can be registered and executed', function ($expect) {
$extension = new class extends Extension
{
function boot() { $this->boot = true; }
function comparisons(Comparator $c) { $this->comparisons = true; }
function setup() { $this->setup = true; }
function tearDown() { $this->tearDown = true; }
function shutdown() { $this->shutdown = true; }
};
$extensions = new Extensions;
$extensions->registerMany([$extension]);
$extensions->boot();
$extensions->comparisons(new Comparator);
$extensions->setup();
$extensions->tearDown();
$extensions->shutdown();
$expect($extension->boot)->toEqual(true)->when('Extensions can be booted');
$expect($extension->comparisons)->toEqual(true)->when('Extensions can register comparisons');
$expect($extension->setup)->toEqual(true)->when('Extensions can be setup');
$expect($extension->tearDown)->toEqual(true)->when('Extensions can be torn down');
$expect($extension->shutdown)->toEqual(true)->when('Extensions can be shutdown');
});
|
Revert "Dummy commit to test"
This reverts commit dd95013be87c409d6aac0b302a06fc426ef60339. | <?php
include 'includes/constant/config.inc.php';
session_start();
return_meta();
?>
<head>
<title>Home</title></head>
<body>
<div id="container">
<div id="headerplaced">
<?php include 'includes/constant/nav.inc.php'; ?>
</div>
<div class="content">
<div class="sidebarhome">
<h2>What would you like to do?</h2>
<p><strong>Volunteer </strong>button</p>
<p><strong>Get Pet Assistance </strong>button</p>
<p class="note"><strong>Register first!</strong> When volunteering or requesting assistance for the first time, you will be first directed to register on the Pet Project website. </p>
</div>
<div class="mainhome">
<p>Home page content/photo.</p>
<img src="images/unpurchased_photo.jpg">
</div>
</div>
<div id="footer">
<p>Here's some content for the footer. Need to use an include for this.</p>
</div>
</div>
</body>
</html>
| <?php
include 'includes/constant/config.inc.php';
session_start();
return_meta();
?>
<head>
<title>Home</title></head>
<body>
<div id="container">
<div id="headerplaced">
<?php include 'includes/constant/nav.inc.php'; ?>
</div>
<div class="content">
<div class="sidebarhome">
<h2>What would you like to do?</h2>
<p>A CHANGE </p>
<p><strong>Volunteer </strong>button</p>
<p><strong>Get Pet Assistance </strong>button</p>
<p class="note"><strong>Register first!</strong> When volunteering or requesting assistance for the first time, you will be first directed to register on the Pet Project website. </p>
</div>
<div class="mainhome">
<p>Home page content/photo.</p>
<img src="images/unpurchased_photo.jpg">
</div>
</div>
<div id="footer">
<p>Here's some content for the footer. Need to use an include for this.</p>
</div>
</div>
</body>
</html>
|
Fix cache key set, on core cache | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.db import models
from django.core.cache import cache
from django.conf import settings
def _cache_key(model, id):
return u'{}:{}:{}'.format(settings.CACHE_PREFIX,
model._meta.db_table,
id)
class CacheManager(models.Manager):
def get(self, *args, **kwargs):
id = repr(kwargs)
pointer_key = _cache_key(self.model, id)
model_key = cache.get(pointer_key)
if model_key is not None:
model = cache.get(model_key)
if model is not None:
return model
model = super(CacheManager, self).get(*args, **kwargs)
if not model_key:
model_key = _cache_key(model, model.pk)
cache.set(pointer_key, model_key, settings.CACHE_EXPIRE)
cache.set(model_key, model, settings.CACHE_EXPIRE)
return model
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.db import models
from django.core.cache import cache
from django.conf import settings
class CacheManager(models.Manager):
def __cache_key(self, id):
return u'{}:{}:{}'.format(settings.CACHE_PREFIX,
self.model._meta.db_table,
id)
def get(self, *args, **kwargs):
id = repr(kwargs)
pointer_key = self.__cache_key(id)
model_key = cache.get(pointer_key)
if model_key is not None:
model = cache.get(model_key)
if model is not None:
return model
model = super(CacheManager, self).get(*args, **kwargs)
if not model_key:
model_key = self.__cache_key(model, model.pk)
cache.set(pointer_key, model_key, settings.CACHE_EXPIRE)
cache.set(model_key, model, settings.CACHE_EXPIRE)
return model
|
Allow over 100 again for when load becomes available | #!/usr/bin/env python3
import psutil
import os
import time
import math
blocks = ['β', 'β', 'β', 'β', 'β
', 'β', 'β', 'β']
def create_bar(filled):
filled = int(filled * 100)
if filled < 50:
color = "green"
elif filled < 80:
color = "yellow"
else:
color = "red"
bar = '#[fg=' + color + ']β'
if filled < 100:
block = math.floor(filled / (100 / 7) + 0.5)
bar += blocks[block]
else:
bar += blocks[7]
bar += 'β'
if filled >= 100:
bar += str(filled)
else:
bar += "{0:2}%".format(filled)
bar += '#[fg=default]'
return bar
while True:
meminfo = psutil.virtual_memory()
numcpus = psutil.cpu_count()
with open(os.path.expanduser("~/.memblock"), "w") as memblock:
memblock.write(create_bar((meminfo.total - meminfo.available) / meminfo.total))
with open(os.path.expanduser("~/.cpuutilblock"), "w") as cpuutilblock:
cpuutilblock.write(create_bar(psutil.cpu_percent() / 100))
time.sleep(20)
| #!/usr/bin/env python3
import psutil
import os
import time
import math
blocks = ['β', 'β', 'β', 'β', 'β
', 'β', 'β', 'β']
def create_bar(filled):
if filled > 1:
low = str(int(filled))
high = str(int(filled + 1))
filled = filled - int(filled)
filled = int(filled * 100)
if filled < 50:
color = "green"
elif filled < 80:
color = "yellow"
else:
color = "red"
block = math.floor(filled / (100 / 7) + 0.5)
bar = '#[fg=' + color + ']β'
bar += blocks[block]
bar += 'β'
if filled >= 100:
bar += str(filled)
else:
bar += "{0:2}%".format(filled)
bar += '#[fg=default]'
return bar
while True:
meminfo = psutil.virtual_memory()
numcpus = psutil.cpu_count()
with open(os.path.expanduser("~/.memblock"), "w") as memblock:
memblock.write(create_bar((meminfo.total - meminfo.available) / meminfo.total))
with open(os.path.expanduser("~/.cpuutilblock"), "w") as cpuutilblock:
cpuutilblock.write(create_bar(psutil.cpu_percent() / 100))
time.sleep(20)
|
Use git version tag for version | import os
from setuptools import setup, find_packages
cdir = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(cdir, 'readme.rst')).read()
setup(
name='KegBouncer',
setup_requires=['setuptools_scm'],
use_scm_version=True,
description='A three-tiered permissions model for KegElements built atop Flask-User',
long_description=README,
author='Level 12',
author_email='devteam@level12.io',
url='https://github.com/level12/keg-bouncer',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.5',
],
packages=find_packages(exclude=['keg_bouncer_test_app*']),
include_package_data=True,
zip_safe=False,
install_requires=[
'Flask-Login',
'Keg',
'KegElements',
'cryptography',
'six',
'SQLAlchemy',
'wrapt',
],
)
| import os
from setuptools import setup, find_packages
cdir = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(cdir, 'readme.rst')).read()
from keg_bouncer.version import VERSION
setup(
name='KegBouncer',
version=VERSION,
description='A three-tiered permissions model for KegElements built atop Flask-User',
author='Level 12',
author_email='devteam@level12.io',
url='https://github.com/level12/keg-bouncer',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.5',
],
packages=find_packages(exclude=['keg_bouncer_test_app*']),
include_package_data=True,
zip_safe=False,
install_requires=[
'Flask-Login',
'Keg',
'KegElements',
'cryptography',
'six',
'SQLAlchemy',
'wrapt',
],
long_descripton=README,
)
|
Remove @ in front of 'You'. | const qs = require('qs');
module.exports.handler = (event, context, callback) => {
/** Immediate response for WarmUP plugin */
if (event.source === 'serverless-plugin-warmup') {
console.log('WarmUP - Lambda is warm!');
return callback(null, 'Lambda is warm!');
}
const body = qs.parse(event.body);
const identity = body.user_name ? `@${body.user_name}` : 'You';
const result = body.text === 'coin'
? `:coin_${Math.floor((Math.random() * 2) + 1)}:`
: `:dice_${Math.floor((Math.random() * 6) + 1)}:`;
const response = {
statusCode: 200,
headers: {
// Required for CORS support to work
'Access-Control-Allow-Origin': '*',
// Required for cookies, authorization headers with HTTPS
'Access-Control-Allow-Credentials': true,
'Content-type': 'application/json',
},
body: JSON.stringify({
response_type: 'in_channel',
text: `${identity} just rolled: ${result}`,
}),
};
callback(null, response);
};
| const qs = require('qs');
module.exports.handler = (event, context, callback) => {
/** Immediate response for WarmUP plugin */
if (event.source === 'serverless-plugin-warmup') {
console.log('WarmUP - Lambda is warm!');
return callback(null, 'Lambda is warm!');
}
const body = qs.parse(event.body);
const result = body.text === 'coin'
? `:coin_${Math.floor((Math.random() * 2) + 1)}:`
: `:dice_${Math.floor((Math.random() * 6) + 1)}:`;
const response = {
statusCode: 200,
headers: {
// Required for CORS support to work
'Access-Control-Allow-Origin': '*',
// Required for cookies, authorization headers with HTTPS
'Access-Control-Allow-Credentials': true,
'Content-type': 'application/json',
},
body: JSON.stringify({
response_type: 'in_channel',
text: `@${body.user_name || 'You'} just rolled: ${result}`,
}),
};
callback(null, response);
};
|
Refactor test to eliminate assertRaises() error with Python 2.6 | from unittest import TestCase
from pyparsing import ParseException
from regparser.grammar.atomic import *
class GrammarAtomicTests(TestCase):
def test_em_digit_p(self):
result = em_digit_p.parseString('(<E T="03">2</E>)')
self.assertEqual('2', result.p5)
def test_double_alpha(self):
for text, p1 in [('(a)', 'a'),
('(aa)', 'aa'),
('(i)','i')]:
result = lower_p.parseString(text)
self.assertEqual(p1, result.p1)
for text in ['(ii)', '(iv)', '(vi)']:
try:
result = lower_p.parseString(text)
except ParseException:
pass
except e:
self.fail("Unexpected error:", e)
else:
self.fail("Didn't raise ParseException")
| from unittest import TestCase
from pyparsing import ParseException
from regparser.grammar.atomic import *
class GrammarAtomicTests(TestCase):
def test_em_digit_p(self):
result = em_digit_p.parseString('(<E T="03">2</E>)')
self.assertEqual('2', result.p5)
def test_double_alpha(self):
# Match (aa), (bb), etc.
result = lower_p.parseString('(a)')
self.assertEqual('a', result.p1)
result = lower_p.parseString('(aa)')
self.assertEqual('aa', result.p1)
result = lower_p.parseString('(i)')
self.assertEqual('i', result.p1)
# Except for roman numerals
with self.assertRaises(ParseException):
result = lower_p.parseString('(ii)')
with self.assertRaises(ParseException):
result = lower_p.parseString('(iv)')
|
[FIX] Test was running too fast, delaying more | import Ember from 'ember';
import startApp from '../../helpers/start-app';
import {TRANSPARENT_PIXEL} from 'dummy/utils/img-manager/img-clone-holder';
import '../../helpers/later';
var application;
module('Acceptance: should update the image after the src changed', {
setup: function () {
application = startApp();
},
teardown: function () {
Ember.run(application, 'destroy');
}
});
test('visiting /img-wrap/delayed-src', function () {
var $imgContainer;
visit('/img-wrap/delayed-src');
andThen(function(){
fillIn('#img-src', 'assets/images/cartoon-1.jpg');
later(100);
});
andThen(function () {
equal(currentPath(), 'img-wrap.delayed-src');
$imgContainer = find('.img-container');
equal($imgContainer.find('img').attr('src'), 'assets/images/cartoon-1.jpg');
equal($imgContainer.find('img').attr('alt'), 'Cartoon 1');
});
});
| import Ember from 'ember';
import startApp from '../../helpers/start-app';
import {TRANSPARENT_PIXEL} from 'dummy/utils/img-manager/img-clone-holder';
import '../../helpers/later';
var application;
module('Acceptance: should update the image after the src changed', {
setup: function () {
application = startApp();
},
teardown: function () {
Ember.run(application, 'destroy');
}
});
test('visiting /img-wrap/delayed-src', function () {
var $imgContainer;
visit('/img-wrap/delayed-src');
andThen(function(){
fillIn('#img-src', 'assets/images/cartoon-1.jpg');
later(10);
});
andThen(function () {
equal(currentPath(), 'img-wrap.delayed-src');
$imgContainer = find('.img-container');
equal($imgContainer.find('img').attr('src'), 'assets/images/cartoon-1.jpg');
equal($imgContainer.find('img').attr('alt'), 'Cartoon 1');
});
});
|
Use a different version number | from setuptools import setup, find_packages
setup(
name='exchangerates',
version='0.1.2',
description="A module to make it easier to handle historical exchange rates",
long_description="",
classifiers=[
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
'Programming Language :: Python :: 2.7'
],
author='Mark Brough',
author_email='mark@brough.io',
url='http://github.com/markbrough/exchangerates',
license='MIT',
packages=find_packages(exclude=['ez_setup', 'examples']),
namespace_packages=[],
include_package_data=True,
zip_safe=True,
install_requires=[
'lxml == 3.7.3',
'requests == 2.13.0'
],
entry_points={
}
)
| from setuptools import setup, find_packages
setup(
name='exchangerates',
version='0.1.01',
description="A module to make it easier to handle historical exchange rates",
long_description="",
classifiers=[
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
'Programming Language :: Python :: 2.7'
],
author='Mark Brough',
author_email='mark@brough.io',
url='http://github.com/markbrough/exchangerates',
license='MIT',
packages=find_packages(exclude=['ez_setup', 'examples']),
namespace_packages=[],
include_package_data=True,
zip_safe=True,
install_requires=[
'lxml == 3.7.3',
'requests == 2.13.0'
],
entry_points={
}
)
|
Add TapReporter to Protractor reports | 'use strict'
var proxy = {
proxyType: 'autodetect'
}
if (process.env.HTTP_PROXY !== undefined && process.env.HTTP_PROXY !== null) {
proxy = {
proxyType: 'manual',
httpProxy: process.env.HTTP_PROXY
}
}
exports.config = {
directConnect: true,
allScriptsTimeout: 80000,
specs: [
'test/e2e/*.js'
],
capabilities: {
browserName: 'chrome',
proxy: proxy
},
baseUrl: 'http://localhost:3000',
framework: 'jasmine2',
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 90000
},
onPrepare: function () {
var jasmineReporters = require('jasmine-reporters')
jasmine.getEnv().clearReporters()
jasmine.getEnv().addReporter(new jasmineReporters.TapReporter())
jasmine.getEnv().addReporter(new jasmineReporters.JUnitXmlReporter({
consolidateAll: true,
savePath: 'build/reports/e2e_results'
}))
// Get cookie consent popup out of the way
browser.get('/#')
browser.manage().addCookie({ name: 'cookieconsent_status', value: 'dismiss' })
}
}
if (process.env.TRAVIS_BUILD_NUMBER) {
exports.config.capabilities.chromeOptions = {
args: ['--headless', '--disable-gpu', '--window-size=800,600']
}
}
| 'use strict'
var proxy = {
proxyType: 'autodetect'
}
if (process.env.HTTP_PROXY !== undefined && process.env.HTTP_PROXY !== null) {
proxy = {
proxyType: 'manual',
httpProxy: process.env.HTTP_PROXY
}
}
exports.config = {
directConnect: true,
allScriptsTimeout: 80000,
specs: [
'test/e2e/*.js'
],
capabilities: {
browserName: 'chrome',
proxy: proxy
},
baseUrl: 'http://localhost:3000',
framework: 'jasmine2',
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 90000
},
onPrepare: function () {
var jasmineReporters = require('jasmine-reporters')
jasmine.getEnv().clearReporters()
jasmine.getEnv().addReporter(new jasmineReporters.JUnitXmlReporter({
consolidateAll: true,
savePath: 'build/reports/e2e_results'
}))
// Get cookie consent popup out of the way
browser.get('/#')
browser.manage().addCookie({ name: 'cookieconsent_status', value: 'dismiss' })
}
}
if (process.env.TRAVIS_BUILD_NUMBER) {
exports.config.capabilities.chromeOptions = {
args: ['--headless', '--disable-gpu', '--window-size=800,600']
}
}
|
Replace broken babel documentation link
According to Babel's PyPI package page, http://babel.pocoo.org/docs/ is
the official documentation website. | from decimal import Decimal as D, InvalidOperation
from django import template
from django.conf import settings
from babel.numbers import format_currency
register = template.Library()
@register.filter(name='currency')
def currency(value):
"""
Format decimal value as currency
"""
try:
value = D(value)
except (TypeError, InvalidOperation):
return u""
# Using Babel's currency formatting
# http://babel.pocoo.org/docs/api/numbers/#babel.numbers.format_currency
kwargs = {
'currency': settings.OSCAR_DEFAULT_CURRENCY,
'format': getattr(settings, 'OSCAR_CURRENCY_FORMAT', None)}
locale = getattr(settings, 'OSCAR_CURRENCY_LOCALE', None)
if locale:
kwargs['locale'] = locale
return format_currency(value, **kwargs)
| from decimal import Decimal as D, InvalidOperation
from django import template
from django.conf import settings
from babel.numbers import format_currency
register = template.Library()
@register.filter(name='currency')
def currency(value):
"""
Format decimal value as currency
"""
try:
value = D(value)
except (TypeError, InvalidOperation):
return u""
# Using Babel's currency formatting
# http://packages.python.org/Babel/api/babel.numbers-module.html#format_currency
kwargs = {
'currency': settings.OSCAR_DEFAULT_CURRENCY,
'format': getattr(settings, 'OSCAR_CURRENCY_FORMAT', None)}
locale = getattr(settings, 'OSCAR_CURRENCY_LOCALE', None)
if locale:
kwargs['locale'] = locale
return format_currency(value, **kwargs)
|
Use normal without extra libs | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Generate hastag from a webpage</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>
<body>
<div class="container-fluid">
<h1>Generate hastag from a webpage</h1>
<?php
$this->load->helper('form');
echo form_open("/Hashtags/generate_tags",array)
?>
<form class="form-inline" action="<?php echo "http://$_SERVER[HTTP_HOST]/index.php/Hashtags/generate_tags"?> method="POST">
<div class="form-group">
<input type="text" class="form-control" name="url" placeholder="Enter the site url here" required>
</div>
<button type="submit" class="btn btn-primary">Go!</button>
</form>
</div>
</body>
</html>
| <?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Generate hastag from a webpage</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>
<body>
<div class="container-fluid">
<h1>Generate hastag from a webpage</h1>
<?php
$this->load->helper('form');
echo "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
echo form_open("/Hashtags/generate_tags",array('class'=>'form-inline'));
?>
<div class="form-group">
<input type="text" class="form-control" name="url" placeholder="Enter the site url here" required>
</div>
<button type="submit" class="btn btn-primary">Go!</button>
</form>
</div>
</body>
</html>
|
Load the real staged changes patch in CommitPreviewContainer | import React from 'react';
import PropTypes from 'prop-types';
import yubikiri from 'yubikiri';
import ObserveModel from '../views/observe-model';
import LoadingView from '../views/loading-view';
import CommitPreviewController from '../controllers/commit-preview-controller';
export default class CommitPreviewContainer extends React.Component {
static propTypes = {
repository: PropTypes.object.isRequired,
}
fetchData = repository => {
return yubikiri({
multiFilePatch: repository.getStagedChangesPatch(),
});
}
render() {
return (
<ObserveModel model={this.props.repository} fetchData={this.fetchData}>
{this.renderResult}
</ObserveModel>
);
}
renderResult = data => {
if (this.props.repository.isLoading() || data === null) {
return <LoadingView />;
}
return (
<CommitPreviewController
{...data}
{...this.props}
/>
);
}
}
| import React from 'react';
import PropTypes from 'prop-types';
import yubikiri from 'yubikiri';
import ObserveModel from '../views/observe-model';
import LoadingView from '../views/loading-view';
import CommitPreviewController from '../controllers/commit-preview-controller';
import MultiFilePatch from '../models/patch/multi-file-patch';
export default class CommitPreviewContainer extends React.Component {
static propTypes = {
repository: PropTypes.object.isRequired,
}
fetchData = repository => {
return yubikiri({
multiFilePatch: new MultiFilePatch([]),
});
}
render() {
return (
<ObserveModel model={this.props.repository} fetchData={this.fetchData}>
{this.renderResult}
</ObserveModel>
);
}
renderResult = data => {
if (this.props.repository.isLoading() || data === null) {
return <LoadingView />;
}
return (
<CommitPreviewController
{...data}
{...this.props}
/>
);
}
}
|
Add $email parameter to resetPassword() | <?php
require('DB_Config.php');
require('Encrypt.class.php');
class Authenticate {
private $mysqli;
//Get the table structure from DB_Config
private $tablename = TABLE_OF_USERS;
private $usercol = COLUMN_OF_USERS;
private $emailcol = COLUMN_OF_EMAILS;
private $passwordcol = COLUMN_OF_PASSWORDS;
function __construct()
{
$mysqli = new mysqli(HOST, DB_USERNAME, DB_PASSWORD, DATABASE_NAME);
$this -> mysqli = $mysqli;
}
function login($username, $password)
{
}
function createUser($username, $password, $confirmpassword, $email)
{
}
function logout()
{
session_destroy();
}
function resetPassword($username, $email)
{
}
function isUserActive($active)
{
}
function changePassword($username, $password, $newpassword, $confirmnewpassword)
{
}
}
?> | <?php
require('DB_Config.php');
require('Encrypt.class.php');
class Authenticate {
private $mysqli;
//Get the table structure from DB_Config
private $tablename = TABLE_OF_USERS;
private $usercol = COLUMN_OF_USERS;
private $emailcol = COLUMN_OF_EMAILS;
private $passwordcol = COLUMN_OF_PASSWORDS;
function __construct()
{
$mysqli = new mysqli(HOST, DB_USERNAME, DB_PASSWORD, DATABASE_NAME);
$this -> mysqli = $mysqli;
}
function login($username, $password)
{
}
function createUser($username, $password, $confirmpassword, $email)
{
}
function logout()
{
session_destroy();
}
function resetPassword($username)
{
}
function isUserActive($active)
{
}
function changePassword($username, $password, $newpassword, $confirmnewpassword)
{
}
}
?> |
Add check for user existance inside session | const UserDB = require('../db/userdb').Users
exports.ui = (req, res, next) => {
if (req.session && req.session.user) {
let name = req.session.user.userName
console.log('</routes/chat.js , ui> userName -> ', name)
req.userName = res.locals.userName = name
getAllUsers(res, name)
} else {
res.redirect('/')
}
}
getAllUsers = (res, name) => {
UserDB.all((err, users) => {
//console.log('<chat.js, getAllUsers > users -> ', users)
if (err) throw new Error(err)
if (users.length > 0) {
res.render('chat_ui', {
userName: name,
users: users
})
} else {
res.render('chat_ui', {
userName: name,
users: []
})
}
})
}
| const UserDB = require('../db/userdb').Users
exports.ui = (req, res, next) => {
if (req.session) {
let name = req.session.user.userName
console.log('</routes/chat.js , ui> userName -> ', name)
req.userName = res.locals.userName = name
getAllUsers(res, name)
} else {
res.redirect('/')
}
}
getAllUsers = (res, name) => {
UserDB.all((err, users) => {
//console.log('<chat.js, getAllUsers > users -> ', users)
if (err) throw new Error(err)
if (users.length > 0) {
res.render('chat_ui', {
userName: name,
users: users
})
} else {
res.render('chat_ui', {
userName: name,
users: []
})
}
})
}
|
Add body property to message, previously undeclared | <?php
namespace PhpAmqpLib\Message;
use PhpAmqpLib\Wire\GenericContent;
/**
* A Message for use with the Channnel.basic_* methods.
*/
class AMQPMessage extends GenericContent
{
public $body;
protected static $PROPERTIES = array(
"content_type" => "shortstr",
"content_encoding" => "shortstr",
"application_headers" => "table",
"delivery_mode" => "octet",
"priority" => "octet",
"correlation_id" => "shortstr",
"reply_to" => "shortstr",
"expiration" => "shortstr",
"message_id" => "shortstr",
"timestamp" => "timestamp",
"type" => "shortstr",
"user_id" => "shortstr",
"app_id" => "shortstr",
"cluster_id" => "shortstr"
);
public function __construct($body = '', $properties = null)
{
$this->body = $body;
parent::__construct($properties, static::$PROPERTIES);
}
}
| <?php
namespace PhpAmqpLib\Message;
use PhpAmqpLib\Wire\GenericContent;
/**
* A Message for use with the Channnel.basic_* methods.
*/
class AMQPMessage extends GenericContent
{
protected static $PROPERTIES = array(
"content_type" => "shortstr",
"content_encoding" => "shortstr",
"application_headers" => "table",
"delivery_mode" => "octet",
"priority" => "octet",
"correlation_id" => "shortstr",
"reply_to" => "shortstr",
"expiration" => "shortstr",
"message_id" => "shortstr",
"timestamp" => "timestamp",
"type" => "shortstr",
"user_id" => "shortstr",
"app_id" => "shortstr",
"cluster_id" => "shortstr"
);
public function __construct($body = '', $properties = null)
{
$this->body = $body;
parent::__construct($properties, static::$PROPERTIES);
}
}
|
Add signOut function to navbar proptypes | import React, { PureComponent, PropTypes } from 'react'
import { connect } from 'react-redux'
import { Link } from 'react-router'
import signOut from '../../actions/users/sign-out'
class Navbar extends PureComponent {
static propTypes = {
currentUser: PropTypes.object,
signedIn: PropTypes.bool.isRequired,
signOut: PropTypes.func.isRequired
}
renderSignOut() {
return <li><a onClick={this.props.signOut} href='#'>Sign Out</a></li>
}
renderSignIn() {
return <li><Link to='/sign-in'>Sign In</Link></li>
}
render() {
const { signedIn } = this.props
return(
<header className='page-header'>
<span><Link to='/'>SlimPoll</Link></span>
<nav className='navbar'>
<li><Link to="/all-polls">Polls</Link></li>
{ signedIn && <li><Link to="/create-poll">Create a poll</Link></li> }
{ signedIn && <li><Link to="/my-polls">View your polls</Link></li> }
{ signedIn ? this.renderSignOut() : this.renderSignIn() }
</nav>
</header>
)
}
}
const mapStateToProps = ({ currentUser }) => ({
currentUser,
signedIn: !!currentUser
})
export default connect(mapStateToProps, { signOut })(Navbar)
| import React, { PureComponent, PropTypes } from 'react'
import { connect } from 'react-redux'
import { Link } from 'react-router'
import signOut from '../../actions/users/sign-out'
class Navbar extends PureComponent {
static propTypes = {
currentUser: PropTypes.object,
signedIn: PropTypes.bool.isRequired
}
renderSignOut() {
return <li><a onClick={this.props.signOut} href='#'>Sign Out</a></li>
}
renderSignIn() {
return <li><Link to='/sign-in'>Sign In</Link></li>
}
render() {
const { signedIn } = this.props
return(
<header className='page-header'>
<span><Link to='/'>SlimPoll</Link></span>
<nav className='navbar'>
<li><Link to="/all-polls">Polls</Link></li>
{ signedIn && <li><Link to="/create-poll">Create a poll</Link></li> }
{ signedIn && <li><Link to="/my-polls">View your polls</Link></li> }
{ signedIn ? this.renderSignOut() : this.renderSignIn() }
</nav>
</header>
)
}
}
const mapStateToProps = ({ currentUser }) => ({
currentUser,
signedIn: !!currentUser
})
export default connect(mapStateToProps, { signOut })(Navbar)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.