text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Add item object model import
define(['itemObjectModel', 'mac/roman'], function(itemOM, macRoman) { 'use strict'; function open(item) { function onBlock(item, byteSource) { return byteSource.slice(0, 8).getBytes().then(function(headerBytes) { var length = new DataView(headerBytes.buffer, headerBytes.byteOffset, 4).getUint32(0, false); var name = macRoman(headerBytes, 4, 4); var blockItem = itemOM.createItem(name); item.addItem(blockItem); if (length > 8) { blockItem.byteSource = byteSource.slice(8, length); } if (byteSource.byteLength >= (length + 8)) { return onBlock(item, byteSource.slice(length)); } }); } return onBlock(item, item.byteSource); } return open; });
define(['mac/roman'], function(macRoman) { 'use strict'; function open(item) { function onBlock(item, byteSource) { return byteSource.slice(0, 8).getBytes().then(function(headerBytes) { var length = new DataView(headerBytes.buffer, headerBytes.byteOffset, 4).getUint32(0, false); var name = macRoman(headerBytes, 4, 4); var blockItem = itemOM.createItem(name); item.addItem(blockItem); if (length > 8) { blockItem.byteSource = byteSource.slice(8, length); } if (byteSource.byteLength >= (length + 8)) { return onBlock(item, byteSource.slice(length)); } }); } return onBlock(item, item.byteSource); } return open; });
Switch account fix 2 :)
/** * Account Switch Controller */ angular .module('RDash') .controller('accountSwitchCtrl', ['$state', '$scope', '$stateParams', 'User', 'notificationService', accountSwitchCtrl]); function accountSwitchCtrl($state, $scope, $stateParams, User, notificationService) { User.getCurrent(function(user, req, err) { if (err) { notificationService.error('Account could not be changed!'); $state.go('master.index', {}, {location: true}); } User.prototype$updateAttributes({ id: user.id }, { defaultAccountId: $stateParams.accountId }, function() { notificationService.success('Account changed!'); $scope.$emit('retrieveAccounts'); $state.go('master.index', {}, {location: true}); }, function() { notificationService.error('Account could not be changed!'); $state.go('master.index', {}, {location: true}); }); }); }
/** * Account Switch Controller */ angular .module('RDash') .controller('accountSwitchCtrl', ['$state', '$scope', '$stateParams', 'User', 'notificationService', accountSwitchCtrl]); function accountSwitchCtrl($state, $scope, $stateParams, User, notificationService) { User.getCurrent(function(user, req, err) { if (err) { notificationService.error('Account could not be changed!'); $state.go('master.index', {}, {location: true}); } var userId = user.id; user.id = undefined; user.defaultAccountId = $stateParams.accountId; User.prototype$updateAttributes({ id: userId }, user, function() { notificationService.success('Account changed!'); $scope.$emit('retrieveAccounts'); $state.go('master.index', {}, {location: true}); }, function() { notificationService.error('Account could not be changed!'); $state.go('master.index', {}, {location: true}); }); }); }
Make filtered search boards more consistent with EE
/* eslint-disable class-methods-use-this */ import FilteredSearchContainer from '../filtered_search/container'; export default class FilteredSearchBoards extends gl.FilteredSearchManager { constructor(store, updateUrl = false, cantEdit = []) { super('boards'); this.store = store; this.updateUrl = updateUrl; // Issue boards is slightly different, we handle all the requests async // instead or reloading the page, we just re-fire the list ajax requests this.isHandledAsync = true; this.cantEdit = cantEdit; } updateObject(path) { this.store.path = path.substr(1); if (this.updateUrl) { gl.issueBoards.BoardsStore.updateFiltersUrl(); } } removeTokens() { const tokens = FilteredSearchContainer.container.querySelectorAll('.js-visual-token'); // Remove all the tokens as they will be replaced by the search manager [].forEach.call(tokens, (el) => { el.parentNode.removeChild(el); }); this.filteredSearchInput.value = ''; } updateTokens() { this.removeTokens(); this.loadSearchParamsFromURL(); // Get the placeholder back if search is empty this.filteredSearchInput.dispatchEvent(new Event('input')); } canEdit(tokenName) { return this.cantEdit.indexOf(tokenName) === -1; } }
/* eslint-disable class-methods-use-this */ import FilteredSearchContainer from '../filtered_search/container'; export default class FilteredSearchBoards extends gl.FilteredSearchManager { constructor(store, updateUrl = false, cantEdit = []) { super('boards'); this.store = store; this.updateUrl = updateUrl; // Issue boards is slightly different, we handle all the requests async // instead or reloading the page, we just re-fire the list ajax requests this.isHandledAsync = true; this.cantEdit = cantEdit; } updateObject(path) { this.store.path = path.substr(1); if (this.updateUrl) { gl.issueBoards.BoardsStore.updateFiltersUrl(); } } removeTokens() { const tokens = FilteredSearchContainer.container.querySelectorAll('.js-visual-token'); // Remove all the tokens as they will be replaced by the search manager [].forEach.call(tokens, (el) => { el.parentNode.removeChild(el); }); this.filteredSearchInput.value = ''; } updateTokens() { this.removeTokens(); this.loadSearchParamsFromURL(); // Get the placeholder back if search is empty this.filteredSearchInput.dispatchEvent(new Event('input')); } canEdit(tokenName) { return this.cantEdit.indexOf(tokenName) === -1; } }
Add XML to @produces for ContextResolver
package org.slc.sli.api.resources.config; import javax.ws.rs.Produces; import javax.ws.rs.ext.ContextResolver; import javax.ws.rs.ext.Provider; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.SerializationConfig; import org.springframework.stereotype.Component; import org.slc.sli.api.resources.Resource; /** * Provides a Jackson context resolver that Jersey uses for serializing to JSON or XML. * * @author Sean Melody <smelody@wgen.net> * */ @Provider @Component @Produces({ Resource.JSON_MEDIA_TYPE, Resource.SLC_JSON_MEDIA_TYPE, Resource.XML_MEDIA_TYPE, Resource.SLC_XML_MEDIA_TYPE }) public class CustomJacksonContextResolver implements ContextResolver<ObjectMapper> { private ObjectMapper mapper = new ObjectMapper(); public CustomJacksonContextResolver() { mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false); mapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false); } @Override public ObjectMapper getContext(Class<?> cl) { return mapper; } }
package org.slc.sli.api.resources.config; import javax.ws.rs.Produces; import javax.ws.rs.ext.ContextResolver; import javax.ws.rs.ext.Provider; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.SerializationConfig; import org.springframework.stereotype.Component; import org.slc.sli.api.resources.Resource; /** * Provides a Jackson context resolver that Jersey uses for serializing to JSON. * * @author Sean Melody <smelody@wgen.net> * */ @Provider @Component @Produces({ Resource.JSON_MEDIA_TYPE, Resource.SLC_JSON_MEDIA_TYPE }) public class CustomJacksonContextResolver implements ContextResolver<ObjectMapper> { private ObjectMapper mapper = new ObjectMapper(); public CustomJacksonContextResolver() { mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false); mapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false); } @Override public ObjectMapper getContext(Class<?> cl) { return mapper; } }
Configure test admin username and password.
# -*- coding: utf-8 -*- from collections import namedtuple from pytest import fixture from flask import Flask, g from flask_sqlalchemy import SQLAlchemy from flask_perm import Perm from flask_perm.core import db @fixture def app(request): flask_app = Flask(__name__) flask_app.config['TESTING'] = True flask_app.config['DEBUG'] = True flask_app.config['SERVER_NAME'] = 'localhost' ctx = flask_app.app_context() ctx.push() request.addfinalizer(ctx.pop) return flask_app class User(namedtuple('User', 'id nickname')): pass @fixture def perm(app, request): def user_loader(id): return User(id=id, nickname='User%d'%id) def current_user_loader(): return user_loader(1) def users_loader(**kwargs): return [user_loader(id) for id in range(20)] app.config['PERM_URL_PREFIX'] = '/perm' app.config['PERM_ADMIN_USERNAME'] = 'admin' app.config['PERM_ADMIN_PASSWORD'] = 'test' perm = Perm() perm.app = app perm.init_app(app) perm.user_loader(user_loader) perm.current_user_loader(current_user_loader) perm.users_loader(users_loader) db.create_all() return perm
# -*- coding: utf-8 -*- from collections import namedtuple from pytest import fixture from flask import Flask, g from flask_sqlalchemy import SQLAlchemy from flask_perm import Perm from flask_perm.core import db @fixture def app(request): flask_app = Flask(__name__) flask_app.config['TESTING'] = True flask_app.config['DEBUG'] = True flask_app.config['SERVER_NAME'] = 'localhost' ctx = flask_app.app_context() ctx.push() request.addfinalizer(ctx.pop) return flask_app class User(namedtuple('User', 'id nickname')): pass @fixture def perm(app, request): def user_loader(id): return User(id=id, nickname='User%d'%id) def current_user_loader(): return user_loader(1) def users_loader(): return [user_loader(id) for id in range(20)] app.config['PERM_CURRENT_USER_ACCESS_VALIDATOR'] = lambda user: True app.config['PERM_URL_PREFIX'] = '/perm' perm = Perm() perm.app = app perm.init_app(app) perm.user_loader(user_loader) perm.current_user_loader(current_user_loader) perm.users_loader(users_loader) db.create_all() return perm
Fix login JS files not being output to right dir
var browserify = require('browserify'); var watchify = require('watchify'); var source = require('vinyl-source-stream'); var gulp = require('gulp'); var uglify = require('gulp-uglify'); var streamify = require('gulp-streamify'); var gutil = require('gulp-util'); var pump = require('pump'); function react_browserify(infile, outfile, outdir, debug) { outfile = (outfile === undefined) ? infile : outfile; outdir = (outdir === undefined) ? 'static/js' : outdir; debug = (debug === undefined) ? false : debug; var b = browserify('client-js/'+infile+'.jsx', {transform: 'babelify', debug:true}); b = watchify(b); function bundlefn(cb) { pump([ b.bundle(), source(outfile+'.js'), debug ? gutil.noop() : streamify(uglify()), gulp.dest(outdir) ], cb); } b.on('update', bundlefn); b.on('log', gutil.log); return bundlefn; } gulp.task('build-login', react_browserify('login', 'login', 'public/js')); gulp.task('build-inventory', react_browserify('inventory')); gulp.task('build-users', react_browserify('users')); gulp.task('build-nav', react_browserify('CommonNav', 'navbar')); gulp.task('build', ['build-login', 'build-inventory', 'build-users', 'build-nav']);
var browserify = require('browserify'); var watchify = require('watchify'); var source = require('vinyl-source-stream'); var gulp = require('gulp'); var uglify = require('gulp-uglify'); var streamify = require('gulp-streamify'); var gutil = require('gulp-util'); var pump = require('pump'); function react_browserify(infile, outfile, debug) { outfile = (outfile === undefined) ? infile : outfile; debug = (debug === undefined) ? false : debug; var b = browserify('client-js/'+infile+'.jsx', {transform: 'babelify', debug:true}); b = watchify(b); function bundlefn(cb) { pump([ b.bundle(), source(outfile+'.js'), debug ? gutil.noop() : streamify(uglify()), gulp.dest('static/js') ], cb); } b.on('update', bundlefn); b.on('log', gutil.log); return bundlefn; } gulp.task('build-login', react_browserify('login')); gulp.task('build-inventory', react_browserify('inventory')); gulp.task('build-users', react_browserify('users')); gulp.task('build-nav', react_browserify('CommonNav', 'navbar')); gulp.task('build', ['build-login', 'build-inventory', 'build-users', 'build-nav']);
Convert Twilio URL to IDN.
from flask import abort, current_app, request from functools import wraps from twilio.util import RequestValidator from config import * def validate_twilio_request(f): @wraps(f) def decorated_function(*args, **kwargs): validator = RequestValidator(TWILIO_SECRET) request_valid = validator.validate( request.url.encode("idna"), request.form, request.headers.get("X-TWILIO-SIGNATURE", "")) if request_valid or current_app.debug: return f(*args, **kwargs) else: return abort(403) return decorated_function
from flask import abort, current_app, request from functools import wraps from twilio.util import RequestValidator from config import * def validate_twilio_request(f): @wraps(f) def decorated_function(*args, **kwargs): validator = RequestValidator(TWILIO_SECRET) request_valid = validator.validate( request.url, request.form, request.headers.get("X-TWILIO-SIGNATURE", "")) if request_valid or current_app.debug: return f(*args, **kwargs) else: return abort(403) return decorated_function
Add member avatars and move phone link
import React, {PropTypes} from 'react' import {List, ListItem} from 'material-ui/List' import Divider from 'material-ui/Divider' import Avatar from 'material-ui/Avatar' import SocialPersonOutline from 'material-ui/svg-icons/social/person-outline'; const TeamListItem = props => { let memberCount = props.members let avatar if (props.photoUrl) { avatar = <Avatar src={props.pictureUrl} /> } else { avatar = <SocialPersonOutline /> } return ( <div> <Divider/> <ListItem onClick={() => props.onClick()} primaryText={props.name} secondaryText={ <a href={`tel:${props.phone}`}> {props.phone} </a> } leftAvatar={avatar} /> </div> ) } TeamListItem.propTypes = { members: React.PropTypes.array, name: React.PropTypes.string, scans: React.PropTypes.string, onClick: React.PropTypes.func } export default TeamListItem
import React, {PropTypes} from 'react' import {List, ListItem} from 'material-ui/List' import Divider from 'material-ui/Divider' const TeamListItem = props => { let memberCount = props.members return ( <div> <Divider/> <ListItem onClick={() => props.onClick()} primaryText={props.name} secondaryTextLines={2} rightAvatar= { <a href={`tel:${props.phone}`}> {props.phone} </a> } /> </div> ) } TeamListItem.propTypes = { members: React.PropTypes.array, name: React.PropTypes.string, scans: React.PropTypes.string, onClick: React.PropTypes.func } export default TeamListItem
Fix the resolver to work for non-PHP file extensions.
<?php defined('SYSPATH') or die('No direct script access.'); /** * Resolver that allows PHPTAL to resolve paths in the Kohana filesystem. * * @package KOtal * @category Base * @author Hanson Wong * @author johanlindblad * @copyright (c) 2010 Hanson Wong * @license http://github.com/Dismounted/KOtal/blob/master/LICENSE */ class Kotal_SourceResolver implements PHPTAL_SourceResolver { /** * Resolves files according to Kohana conventions. * * @param string Path to resolve * * @return PHPTAL_FileSource * @return null */ public function resolve($path) { $ext = Kohana::$config->load('kotal.ext'); $path = str_replace(array(APPPATH.'views/', '.' . $ext), '', $path); $file = Kohana::find_file('views', $path, $ext); if ($file) { return new PHPTAL_FileSource($file); } return null; } }
<?php defined('SYSPATH') or die('No direct script access.'); /** * Resolver that allows PHPTAL to resolve paths in the Kohana filesystem. * * @package KOtal * @category Base * @author Hanson Wong * @author johanlindblad * @copyright (c) 2010 Hanson Wong * @license http://github.com/Dismounted/KOtal/blob/master/LICENSE */ class Kotal_SourceResolver implements PHPTAL_SourceResolver { /** * Resolves files according to Kohana conventions. * * @param string Path to resolve * * @return PHPTAL_FileSource * @return null */ public function resolve($path) { $path = str_replace(array(APPPATH.'views/', '.php'), '', $path); $ext = Kohana::$config->load('kotal.ext'); $file = Kohana::find_file('views', $path, $ext); if ($file) { return new PHPTAL_FileSource($file); } return null; } }
Send notification using the auth secret, if available
// Use the web-push library to hide the implementation details of the communication // between the application server and the push service. // For details, see https://tools.ietf.org/html/draft-ietf-webpush-protocol-01 and // https://tools.ietf.org/html/draft-thomson-webpush-encryption-01. var webPush = require('web-push'); webPush.setGCMAPIKey(process.env.GCM_API_KEY); module.exports = function(app, route) { app.post(route + 'register', function(req, res) { // A real world application would store the subscription info. res.sendStatus(201); }); app.post(route + 'sendNotification', function(req, res) { setTimeout(function() { webPush.sendNotification(req.body.endpoint, { TTL: req.body.ttl, payload: req.body.payload, userPublicKey: req.body.key, userAuth: req.body.authSecret, }) .then(function() { res.sendStatus(201); }); }, req.body.delay * 1000); }); };
// Use the web-push library to hide the implementation details of the communication // between the application server and the push service. // For details, see https://tools.ietf.org/html/draft-ietf-webpush-protocol-01 and // https://tools.ietf.org/html/draft-thomson-webpush-encryption-01. var webPush = require('web-push'); webPush.setGCMAPIKey(process.env.GCM_API_KEY); module.exports = function(app, route) { app.post(route + 'register', function(req, res) { // A real world application would store the subscription info. res.sendStatus(201); }); app.post(route + 'sendNotification', function(req, res) { setTimeout(function() { webPush.sendNotification(req.body.endpoint, req.body.ttl, req.body.key, req.body.payload) .then(function() { res.sendStatus(201); }); }, req.body.delay * 1000); }); };
Undo change made for debugging
import { remote } from 'electron'; import fs from 'fs'; import path from 'path'; window.addEventListener('load', () => { if (window.$ && Settings.get('welcomed') !== remote.app.getVersion() && $('#welcome').length) { $('[data-app-changes]').html(fs.readFileSync(path.resolve(`${__dirname}/../../../../MR_CHANGELOG.html`), 'utf8')); // eslint-disable-line $('#welcome').openModal({ dismissible: false, complete: () => { Emitter.fire('welcomed', remote.app.getVersion()); }, }); } if (window.$) { const modal = $('#about'); $('[data-app-version]').text(remote.app.getVersion()); $('[data-app-name]').text(remote.app.getName()); $('[data-app-dev-mode]').text(remote.getGlobal('DEV_MODE') ? 'Running in Development Mode' : ''); Emitter.on('about', () => { modal.openModal({ dismissable: true, }); }); } });
import { remote } from 'electron'; import fs from 'fs'; import path from 'path'; window.addEventListener('load', () => { if (window.$ && Settings.get('welcomed') === remote.app.getVersion() && $('#welcome').length) { $('[data-app-changes]').html(fs.readFileSync(path.resolve(`${__dirname}/../../../../MR_CHANGELOG.html`), 'utf8')); // eslint-disable-line $('#welcome').openModal({ dismissible: false, complete: () => { Emitter.fire('welcomed', remote.app.getVersion()); }, }); } if (window.$) { const modal = $('#about'); $('[data-app-version]').text(remote.app.getVersion()); $('[data-app-name]').text(remote.app.getName()); $('[data-app-dev-mode]').text(remote.getGlobal('DEV_MODE') ? 'Running in Development Mode' : ''); Emitter.on('about', () => { modal.openModal({ dismissable: true, }); }); } });
Optimize number of SQL queries in Order details view
from django.db.models import Sum from django.db.models.query import QuerySet from django.shortcuts import render, get_object_or_404 from django.utils import timezone from orders.models import Order def order_details(request, order_pk): order = get_object_or_404(Order.objects.prefetch_related('books', 'books__book_type').select_related('user'), pk=order_pk) return render(request, 'orders/details.html', {'order': order, 'book_list': [book.book_type for book in order.books.all()]}) def not_executed(request): orders = get_orders().filter(valid_until__gt=timezone.now(), sold_count=0) return render(request, 'orders/not_executed.html', {'orders': orders}) def outdated(request): orders = get_orders().filter(valid_until__lte=timezone.now(), sold_count=0) return render(request, 'orders/outdated.html', {'orders': orders}) def executed(request): orders = get_orders().exclude(sold_count=0) return render(request, 'orders/executed.html', {'orders': orders}) def get_orders() -> QuerySet: """ The function returns QuerySet of Order model with all necessary values for displaying also selected/prefetched. :return: the QuerySet of Order model """ return Order.objects.select_related('user').prefetch_related('books').annotate(sold_count=Sum('books__sold'))
from django.db.models import Sum from django.db.models.query import QuerySet from django.shortcuts import render, get_object_or_404 from django.utils import timezone from orders.models import Order def order_details(request, order_pk): order = get_object_or_404(Order.objects.prefetch_related('books'), pk=order_pk) return render(request, 'orders/details.html', {'order': order, 'book_list': [book.book_type for book in order.books.all()]}) def not_executed(request): orders = get_orders().filter(valid_until__gt=timezone.now(), sold_count=0) return render(request, 'orders/not_executed.html', {'orders': orders}) def outdated(request): orders = get_orders().filter(valid_until__lte=timezone.now(), sold_count=0) return render(request, 'orders/outdated.html', {'orders': orders}) def executed(request): orders = get_orders().exclude(sold_count=0) return render(request, 'orders/executed.html', {'orders': orders}) def get_orders() -> QuerySet: """ The function returns QuerySet of Order model with all necessary values for displaying also selected/prefetched. :return: the QuerySet of Order model """ return Order.objects.select_related('user').prefetch_related('books').annotate(sold_count=Sum('books__sold'))
Add call to Components.getInstance to robotInit. This call will create all subsystems at robot init time.
/*----------------------------------------------------------------------------*/ /* Copyright (c) FIRST 2008. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package com.edinarobotics.zed; import edu.wpi.first.wpilibj.IterativeRobot; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Zed extends IterativeRobot { /** * This function is run when the robot is first started up and should be * used for any initialization code. */ public void robotInit() { Components.getInstance(); //Create all robot subsystems. } /** * This function is called periodically during autonomous */ public void autonomousPeriodic() { } /** * This function is called periodically during operator control */ public void teleopPeriodic() { } /** * This function is called periodically during test mode */ public void testPeriodic() { } }
/*----------------------------------------------------------------------------*/ /* Copyright (c) FIRST 2008. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package com.edinarobotics.zed; import edu.wpi.first.wpilibj.IterativeRobot; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Zed extends IterativeRobot { /** * This function is run when the robot is first started up and should be * used for any initialization code. */ public void robotInit() { } /** * This function is called periodically during autonomous */ public void autonomousPeriodic() { } /** * This function is called periodically during operator control */ public void teleopPeriodic() { } /** * This function is called periodically during test mode */ public void testPeriodic() { } }
Exclude the salt from the returned decrypted password
from Crypto.Cipher import Blowfish from django.conf import settings from random import choice from base64 import encodestring as encode from base64 import decodestring as decode import base64 import hashlib import string import os def sha_password(password): salt = os.urandom(4) h = hashlib.sha1(password) h.update(salt) return "{SSHA}" + encode(h.digest() + salt)[:-1] def check_password(challenge_password, password,): challenge_bytes = decode(challenge_password[6:]) digest = challenge_bytes[:20] salt = challenge_bytes[20:] hr = hashlib.sha1(password) hr.update(salt) return digest == hr.digest() def encrypt_password(password): obj = Blowfish.new(settings.BLOWFISH_KEY) return base64.b64encode(obj.encrypt(password + settings.SECRET_KEY[:8])) def decrypt_password(password): obj = Blowfish.new(settings.BLOWFISH_KEY) original_password = obj.decrypt(base64.b64decode(password + settings.SECRET_KEY[:8])) return original_password[:-8] def random_string(length, type = None): if type == 'password': chars = string.printable[:-6] else: chars = string.letters + string.digits return ''.join([choice(chars) for i in range(length)])
from Crypto.Cipher import Blowfish from django.conf import settings from random import choice from base64 import encodestring as encode from base64 import decodestring as decode import base64 import hashlib import string import os def sha_password(password): salt = os.urandom(4) h = hashlib.sha1(password) h.update(salt) return "{SSHA}" + encode(h.digest() + salt)[:-1] def check_password(challenge_password, password,): challenge_bytes = decode(challenge_password[6:]) digest = challenge_bytes[:20] salt = challenge_bytes[20:] hr = hashlib.sha1(password) hr.update(salt) return digest == hr.digest() def encrypt_password(password): obj = Blowfish.new(settings.BLOWFISH_KEY) return base64.b64encode(obj.encrypt(password + settings.SECRET_KEY[:8])) def decrypt_password(password): obj = Blowfish.new(settings.BLOWFISH_KEY) original_password = obj.decrypt(base64.b64decode(password + settings.SECRET_KEY[:8])) return original_password def random_string(length, type = None): if type == 'password': chars = string.printable[:-6] else: chars = string.letters + string.digits return ''.join([choice(chars) for i in range(length)])
Fix javascript links to list prefix path
function searchFrameLinks() { $('#method_list_link').unbind("click").click(function() { toggleSearchFrame(this, '/' + library + '/methods'); }); $('#class_list_link').unbind("click").click(function() { toggleSearchFrame(this, '/' + library + '/class'); }); $('#file_list_link').unbind("click").click(function() { toggleSearchFrame(this, '/' + library + '/files'); }); } function methodPermalinks() { if ($($('#content h1')[0]).text().match(/^Method:/)) return; $('#method_details .signature, #constructor_details .signature, ' + '.method_details .signature, #method_missing_details .signature').each(function() { var id = this.id; var match = id.match(/^(.+?)-(class|instance)_method$/); if (match) { var name = match[1]; var scope = match[2] == "class" ? "." : ":"; var url = window.location.pathname + scope + escape(name); $(this).prepend('<a class="permalink" href="' + url + '">permalink</a>'); } }); } $(searchFrameLinks); $(methodPermalinks);
function searchFrameLinks() { $('#method_list_link').unbind("click").click(function() { toggleSearchFrame(this, '/list/' + library + '/methods'); }); $('#class_list_link').unbind("click").click(function() { toggleSearchFrame(this, '/list/' + library + '/class'); }); $('#file_list_link').unbind("click").click(function() { toggleSearchFrame(this, '/list/' + library + '/files'); }); } function methodPermalinks() { if ($($('#content h1')[0]).text().match(/^Method:/)) return; $('#method_details .signature, #constructor_details .signature, ' + '.method_details .signature, #method_missing_details .signature').each(function() { var id = this.id; var match = id.match(/^(.+?)-(class|instance)_method$/); if (match) { var name = match[1]; var scope = match[2] == "class" ? "." : ":"; var url = window.location.pathname + scope + escape(name); $(this).prepend('<a class="permalink" href="' + url + '">permalink</a>'); } }); } $(searchFrameLinks); $(methodPermalinks);
Remove greenkeeper directories from gh-pages
#! python import sys import requests import urllib3 from os import listdir from shutil import rmtree from json import loads urllib3.disable_warnings() def main(): url = "https://api.github.com/repos/{}/ngeo/branches?per_page=100".format(sys.argv[1]) try: json = requests.get(url).json() expected = [ branch["name"] for branch in json ] expected.append("index.html") expected.append(".git") for path in listdir(sys.argv[2]): if path not in expected or path.startswith("greenkeeper/"): print("Remove: {}".format(path)) rmtree("{}/{}".format(sys.argv[2], path)) except Exception as e: print("WARN {} seems unreachable ({}).".format(url, e)) if __name__ == "__main__": main()
#! python import sys import requests import urllib3 from os import listdir from shutil import rmtree from json import loads urllib3.disable_warnings() def main(): url = "https://api.github.com/repos/{}/ngeo/branches?per_page=100".format(sys.argv[1]) try: json = requests.get(url).json() expected = [ branch["name"] for branch in json ] expected.append("index.html") expected.append(".git") for path in listdir(sys.argv[2]): if path not in expected: print("Remove: {}".format(path)) rmtree("{}/{}".format(sys.argv[2], path)) except Exception as e: print("WARN {} seems unreachable ({}).".format(url, e)) if __name__ == "__main__": main()
Make sure that $appname[1] and $appname[2] are set, in case of cli call, those are empty
<?php Event::add_before('system.ready', current(Event::get('system.ready')), 'multisite_fetch_appname'); function multisite_fetch_appname() { (PHP_SAPI == 'cli') AND $_SERVER['SERVER_NAME'] = Null; // Find subdomain and domain name preg_match('/^(?:(.*)\.)?([^.]++\.[^.]++)$/', $_SERVER['SERVER_NAME'], $appname); // Find appname from domain name $domains = Kohana::config('arag.domains'); // Make sure that $appname[1] and $appname[2] are set, in case of cli call, those are empty if (isset($appname[2]) && isset($domains[$appname[2]])) { $appname = $domains[$appname[2]]; } else { $appname = (isset($appname[1]) && $appname[1]) ? $appname[1] : Kohana::config('arag.master_appname'); } if ($appname == Kohana::config('arag.master_appname') || in_array($appname, Kohana::config('arag.master_appaliases')) || in_array('.*', Kohana::config('arag.master_appaliases'))) { define('MASTERAPP', TRUE); define('APPNAME', Kohana::config('arag.master_appname')); define('APPALIAS', $appname); } else { define('MASTERAPP', FALSE); define('APPNAME', $appname); } }
<?php Event::add_before('system.ready', current(Event::get('system.ready')), 'multisite_fetch_appname'); function multisite_fetch_appname() { (PHP_SAPI == 'cli') AND $_SERVER['SERVER_NAME'] = Null; // Find subdomain and domain name preg_match('/^(?:(.*)\.)?([^.]++\.[^.]++)$/', $_SERVER['SERVER_NAME'], $appname); // Find appname from domain name $domains = Kohana::config('arag.domains'); if (isset($domains[$appname[2]])) { $appname = $domains[$appname[2]]; } else { $appname = ($appname[1]) ? $appname[1] : Kohana::config('arag.master_appname'); } if ($appname == Kohana::config('arag.master_appname') || in_array($appname, Kohana::config('arag.master_appaliases')) || in_array('.*', Kohana::config('arag.master_appaliases'))) { define('MASTERAPP', TRUE); define('APPNAME', Kohana::config('arag.master_appname')); define('APPALIAS', $appname); } else { define('MASTERAPP', FALSE); define('APPNAME', $appname); } }
Remove the need for the babel polyfill
const async = require('async') function parallel (promiseFunctions) { return generatePromise(promiseFunctions, async.parallel) } function series (promiseFunctions) { return generatePromise(promiseFunctions, async.series) } function generatePromise (promiseFunctions, asyncMethod) { return new Promise((resolve, reject) => { // Generate a function that executes the promise function and // calls back in a way that the async library requires let callbacks = promiseFunctions.map(promiseFunction => (callback) => { promiseFunction().then( data => callback(null, data), err => callback(err) ) } ) asyncMethod(callbacks, (err, results) => { if (err) { return reject(err) } resolve(results) }) }) } module.exports = {parallel, series}
require('babel-polyfill') const async = require('async') function parallel (promiseFunctions) { return generatePromise(promiseFunctions, async.parallel) } function series (promiseFunctions) { return generatePromise(promiseFunctions, async.series) } function generatePromise (promiseFunctions, asyncMethod) { return new Promise((resolve, reject) => { let callbacks = promiseFunctions .map(promiseFunction => async (callback) => { try { callback(null, await promiseFunction()) } catch (err) { callback(err) } } ) asyncMethod(callbacks, (err, results) => { if (err) { return reject(err) } resolve(results) }) }) } module.exports = {parallel, series}
Use new core API for modifying WebAppView properties
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <toby.zerner@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Flarum\Embed; use Flarum\Forum\WebApp; class EmbedWebApp extends WebApp { /** * {@inheritdoc} */ public function getView() { $view = parent::getView(); $view->getJs()->addFile(__DIR__.'/../js/forum/dist/extension.js'); $view->getCss()->addFile(__DIR__.'/../less/forum/extension.less'); $view->loadModule('flarum/embed/main'); $view->layout = __DIR__.'/../views/embed.blade.php'; return $view; } /** * {@inheritdoc} */ public function getAssets() { return $this->assets->make('embed'); } }
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <toby.zerner@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Flarum\Embed; use Flarum\Forum\WebApp; class EmbedWebApp extends WebApp { /** * {@inheritdoc} */ public function getView() { $view = parent::getView(); $view->getJs()->addFile(__DIR__.'/../js/forum/dist/extension.js'); $view->getCss()->addFile(__DIR__.'/../less/forum/extension.less'); $view->loadModule('flarum/embed/main'); $view->setLayout(__DIR__.'/../views/embed.blade.php'); return $view; } /** * {@inheritdoc} */ public function getAssets() { return $this->assets->make('embed'); } }
Drop patterns import for Django 1.0 compatibility.
# -*- coding: utf-8 -*- # # django-agpl -- tools to aid releasing Django projects under the AGPL # Copyright (C) 2008, 2009, 2016 Chris Lamb <chris@chris-lamb.co.uk> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from django.conf.urls import url from . import views urlpatterns = ( url(r'^tar$', views.tar, name='download-tar'), url(r'^zip$', views.zip, name='download-zip'), url(r'^targz$', views.targz, name='download-targz'), url(r'^tarbz2$', views.tarbz2, name='download-tarbz2'), )
# -*- coding: utf-8 -*- # # django-agpl -- tools to aid releasing Django projects under the AGPL # Copyright (C) 2008, 2009, 2016 Chris Lamb <chris@chris-lamb.co.uk> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from django.conf.urls import patterns, url from . import views urlpatterns = patterns('django_agpl.views', url(r'^tar$', views.tar, name='download-tar'), url(r'^zip$', views.zip, name='download-zip'), url(r'^targz$', views.targz, name='download-targz'), url(r'^tarbz2$', views.tarbz2, name='download-tarbz2'), )
Use imported version and author from ptwit
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup import ptwit requires = ['python-twitter>=1.0'] def readme(): with open('README.rst') as f: return f.read() setup(name='ptwit', version=ptwit.__version__, description='A simple twitter command line client', long_description=readme(), classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', 'Environment :: Console', 'Intended Audience :: End Users/Desktop', 'Topic :: Utilities'], url='http://github.com/ptpt/ptwit', author=ptwit.__author__, author_email='ptpttt+ptwit@gmail.com', keywords='twitter, command-line, client', license=ptwit.__license__, py_modules=['ptwit'], install_requires=requires, entry_points={ 'console_scripts': ['ptwit=ptwit:cmd']}, zip_safe=False)
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup requires = ['python-twitter>=1.0'] def readme(): with open('README.rst') as f: return f.read() setup(name='ptwit', version='0.0.7', description='A simple twitter command line client', long_description=readme(), classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', 'Environment :: Console', 'Intended Audience :: End Users/Desktop', 'Topic :: Utilities'], url='http://github.com/ptpt/ptwit', author='Tao Peng', author_email='ptpttt+ptwit@gmail.com', keywords='twitter, command-line, client', license='MIT', py_modules=['ptwit'], install_requires=requires, entry_points={ 'console_scripts': ['ptwit=ptwit:cmd']}, zip_safe=False)
Put bus-tracker as default page
"use strict"; var http = require('http'); var path = require('path'); var fs = require('fs'); var mime = require('mime'); function send404 (response) { response.writeHead(404, {"Content-type" : "text/plain"}); response.write("Error 404: Resource not found"); response.end(); } function sendPage (response, filePath, fileContents) { response.writeHead(200, { "Content-type": mime.lookup(path.basename(filePath)) }); response.end(fileContents); } function serverWorking (response, absPath) { fs.exists(absPath, function (exists) { if (exists) { fs.readFile(absPath, function (e, data) { if (e) send404(response); else sendPage(response, absPath, data); }); } else send404(response); }); } var server = http.createServer(function (request, response) { var filePath; if (request.url === '/') filePath = 'bus-tracker.html'; else filePath = request.url; serverWorking(response, "./" + filePath); }); server.listen(process.env.PORT || 8080); console.log("Please go to http://127.0.0.1:8080");
"use strict"; var http = require('http'); var path = require('path'); var fs = require('fs'); var mime = require('mime'); function send404 (response) { response.writeHead(404, {"Content-type" : "text/plain"}); response.write("Error 404: Resource not found"); response.end(); } function sendPage (response, filePath, fileContents) { response.writeHead(200, { "Content-type": mime.lookup(path.basename(filePath)) }); response.end(fileContents); } function serverWorking (response, absPath) { fs.exists(absPath, function (exists) { if (exists) { fs.readFile(absPath, function (e, data) { if (e) send404(response); else sendPage(response, absPath, data); }); } else send404(response); }); } var server = http.createServer(function (request, response) { var filePath; if (request.url === '/') filePath = 'index.html'; else if (request.url === '/bus-tracker' || request.url === '/bus-tracker/') filePath = 'bus-tracker.html'; else filePath = request.url; serverWorking(response, "./" + filePath); }); server.listen(process.env.PORT || 8080); console.log("Please go to http://127.0.0.1:8080");
Support callback as render's second arg
module.exports = function(req, res, next) { if (!req.session.flash) { req.session.flash = []; } res.locals.flash = req.session.flash; req.session.flash = []; req.oneFlash = function(type, message) { if (!message) { message = type; type = 'info'; } req.session.flash.push({ type: type, message: message }); } var _render = res.render; res.render = function(view, options, fn) { // support the callback as the second argument if(typeof(options) === 'function'){ fn = options; options = {}; } if (!options) { options = {}; } if (req.session.flash.length > 0 && res.locals.flash.length === 0) { options.flash = req.session.flash; req.session.flash = []; } _render.call(this, view, options, fn); } next(); };
module.exports = function(req, res, next) { if (!req.session.flash) { req.session.flash = []; } res.locals.flash = req.session.flash; req.session.flash = []; req.oneFlash = function(type, message) { if (!message) { message = type; type = 'info'; } req.session.flash.push({ type: type, message: message }); } var _render = res.render; res.render = function(view, options, fn) { if (!options) { options = {}; } if (req.session.flash.length > 0 && res.locals.flash.length === 0) { options.flash = req.session.flash; req.session.flash = []; } _render.call(this, view, options, fn); } next(); };
Update String in Add-on to 'Enabled' from 'Now active' for Enabled experiments
/* * This Source Code is subject to the terms of the Mozilla Public License * version 2.0 (the 'License'). You can obtain a copy of the License at * http://mozilla.org/MPL/2.0/. */ module.exports.experimentList = ` <div class="experiment-list"> {{#experiments}} <a class="experiment-item {{#active}}active{{/active}}" href="{{base_url}}/experiments/{{slug}}?{{params}}"> <div class="icon-wrapper" style="background-color:{{gradient_start}}; background-image: linear-gradient(300deg, {{gradient_start}}, {{gradient_stop}})"> <div class="icon" style="background-image:url('{{thumbnail}}');"></div> </div> <div class="experiment-title">{{title}} <span class="active-span {{#active}}visible{{/active}}">Enabled</span> </div> </a> {{/experiments}} </div> <a class="view-all" href="{{base_url}}/experiments?{{view_all_params}}">View all experiments</a>`; module.exports.installed = ` <div class="installed-message"> <p><strong>FYI:</strong> We put an button in your toolbar <br> so you can always find Test Pilot.</p> </div>`;
/* * This Source Code is subject to the terms of the Mozilla Public License * version 2.0 (the 'License'). You can obtain a copy of the License at * http://mozilla.org/MPL/2.0/. */ module.exports.experimentList = ` <div class="experiment-list"> {{#experiments}} <a class="experiment-item {{#active}}active{{/active}}" href="{{base_url}}/experiments/{{slug}}?{{params}}"> <div class="icon-wrapper" style="background-color:{{gradient_start}}; background-image: linear-gradient(300deg, {{gradient_start}}, {{gradient_stop}})"> <div class="icon" style="background-image:url('{{thumbnail}}');"></div> </div> <div class="experiment-title">{{title}} <span class="active-span {{#active}}visible{{/active}}">Now Active</span> </div> </a> {{/experiments}} </div> <a class="view-all" href="{{base_url}}/experiments?{{view_all_params}}">View all experiments</a>`; module.exports.installed = ` <div class="installed-message"> <p><strong>FYI:</strong> We put an button in your toolbar <br> so you can always find Test Pilot.</p> </div>`;
Fix bug when no session scope
package de.springbootbuch.webmvc; import java.io.IOException; import javax.inject.Provider; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; /** * Part of springbootbuch.de. * * @author Michael J. Simons * @author @rotnroll666 */ @Component public class DemoFilter implements Filter { private static final Logger LOG = LoggerFactory .getLogger(DemoFilter.class); private final Provider<ShoppingCart> shoppingCart; public DemoFilter( Provider<ShoppingCart> shoppingCart) { this.shoppingCart = shoppingCart; } // Init und Destroy der Übersicht // halber nicht gezeigt @Override public void init( FilterConfig filterConfig) throws ServletException { } @Override public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException, ServletException { chain.doFilter(request, response); if(request instanceof HttpServletRequest && ((HttpServletRequest)request).getSession(false) != null) { LOG.info( "Request from {}", shoppingCart.get() .getContent().isEmpty() ? "" : "not" ); } } @Override public void destroy() { } }
package de.springbootbuch.webmvc; import java.io.IOException; import javax.inject.Provider; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; /** * Part of springbootbuch.de. * * @author Michael J. Simons * @author @rotnroll666 */ @Component public class DemoFilter implements Filter { private static final Logger LOG = LoggerFactory .getLogger(DemoFilter.class); private final Provider<ShoppingCart> shoppingCart; public DemoFilter( Provider<ShoppingCart> shoppingCart) { this.shoppingCart = shoppingCart; } // Init und Destroy der Übersicht // halber nicht gezeigt @Override public void init( FilterConfig filterConfig) throws ServletException { } @Override public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException, ServletException { chain.doFilter(request, response); LOG.info( "Shopping cart is {} empty", shoppingCart.get() .getContent().isEmpty() ? "" : "not" ); } @Override public void destroy() { } }
Update the query for finding all commits belonging to a project The new query returns all commits. In the old query, two types of commit were not taken into account: - Commits in which no files were changed. - Commits in which only files that were in submodules were changed. If a project consists only of commits in which no files have been changed, the commits are not collected. However, this happens very rarely and an analysis of such a project makes no sense. Adapting to this situation would involve the domain (a relationship between the project and the first commit would have to be added).
package io.reflectoring.coderadar.graph.query.repository; import io.reflectoring.coderadar.analyzer.domain.Commit; import io.reflectoring.coderadar.graph.analyzer.domain.CommitEntity; import java.util.List; import org.springframework.data.neo4j.annotation.Query; import org.springframework.data.neo4j.repository.Neo4jRepository; import org.springframework.stereotype.Repository; @Repository public interface GetCommitsInProjectRepository extends Neo4jRepository<CommitEntity, Long> { @Query("MATCH (p1:ProjectEntity)-[:CONTAINS*]-(f1:FileEntity)-[:CHANGED_IN]->(c1:CommitEntity) " + "OPTIONAL MATCH (c2:CommitEntity)-[:IS_CHILD_OF]->(c1:CommitEntity) " + "WHERE ID(p1) = {0} " + "UNWIND [c1, c2] AS c " + "RETURN DISTINCT c " + "ORDER BY c.timestamp DESC") List<CommitEntity> findByProjectId(Long projectId); @Query( value = "MATCH (p:Project)-[:HAS]->(c:Commit) WHERE ID(p) = {0} RETURN c ORDER BY c.sequenceNumber DESC LIMIT 1" ) Commit findTop1ByProjectIdOrderBySequenceNumberDesc(Long id); }
package io.reflectoring.coderadar.graph.query.repository; import io.reflectoring.coderadar.analyzer.domain.Commit; import io.reflectoring.coderadar.graph.analyzer.domain.CommitEntity; import java.util.List; import org.springframework.data.neo4j.annotation.Query; import org.springframework.data.neo4j.repository.Neo4jRepository; import org.springframework.stereotype.Repository; @Repository public interface GetCommitsInProjectRepository extends Neo4jRepository<CommitEntity, Long> { @Query( "MATCH (p:ProjectEntity)-[:CONTAINS]->(f:FileEntity)-[:CHANGED_IN]->(c:CommitEntity) WHERE ID(p) = {0} RETURN c " + "UNION MATCH (p:ProjectEntity)-[:CONTAINS]->(m:ModuleEntity)-[:CONTAINS]->(f:FileEntity)-[:CHANGED_IN]->(c:CommitEntity) WHERE ID(p) = {0} RETURN c") List<CommitEntity> findByProjectId(Long projectId); @Query( value = "MATCH (p:Project)-[:HAS]->(c:Commit) WHERE ID(p) = {0} RETURN c ORDER BY c.sequenceNumber DESC LIMIT 1" ) Commit findTop1ByProjectIdOrderBySequenceNumberDesc(Long id); }
Trim category description at 200 chars in category combobox
/** This view handles rendering of a combobox that can view a category @class ComboboxViewCategory @extends Discourse.ComboboxView @namespace Discourse @module Discourse **/ Discourse.ComboboxViewCategory = Discourse.ComboboxView.extend({ none: 'category.none', classNames: ['combobox category-combobox'], overrideWidths: true, dataAttributes: ['name', 'color', 'text_color', 'description', 'topic_count'], valueBinding: Ember.Binding.oneWay('source'), template: function(text, templateData) { if (!templateData.color) return text; var result = "<span class='badge-category' style='background-color: #" + templateData.color + '; color: #' + templateData.text_color + ";'>" + templateData.name + "</span>"; result += " <span class='topic-count'>&times; " + templateData.topic_count + "</span>"; if (templateData.description && templateData.description !== 'null') { result += '<div class="category-desc">' + Handlebars.Utils.escapeExpression(templateData.description.substr(0,200)) + (templateData.description.length > 200 ? '&hellip;' : '') + '</div>'; } return result; } });
/** This view handles rendering of a combobox that can view a category @class ComboboxViewCategory @extends Discourse.ComboboxView @namespace Discourse @module Discourse **/ Discourse.ComboboxViewCategory = Discourse.ComboboxView.extend({ none: 'category.none', classNames: ['combobox category-combobox'], overrideWidths: true, dataAttributes: ['name', 'color', 'text_color', 'description', 'topic_count'], valueBinding: Ember.Binding.oneWay('source'), template: function(text, templateData) { if (!templateData.color) return text; var result = "<span class='badge-category' style='background-color: #" + templateData.color + '; color: #' + templateData.text_color + ";'>" + templateData.name + "</span>"; result += " <span class='topic-count'>&times; " + templateData.topic_count + "</span>"; if (templateData.description && templateData.description !== 'null') { result += '<div class="category-desc">' + Handlebars.Utils.escapeExpression(templateData.description) + '</div>'; } return result; } });
Fix typo in isolate server. Did I say we need more integration tests? TBR=vadimsh@chromium.org BUG= Review URL: https://codereview.appspot.com/220370043
# Copyright 2014 The Swarming Authors. All rights reserved. # Use of this source code is governed by the Apache v2.0 license that can be # found in the LICENSE file. """This modules is imported by AppEngine and defines the 'app' object. It is a separate file so that application bootstrapping code like ereporter2, that shouldn't be done in unit tests, can be done safely. This file must be tested via a smoke test. """ import os import sys import endpoints APP_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.join(APP_DIR, 'components', 'third_party')) from components import ereporter2 from components import utils import handlers_endpoints import handlers_frontend def create_application(): ereporter2.register_formatter() # App that serves HTML pages and old API. frontend = handlers_frontend.create_application(False) # App that serves new endpoints API. api = endpoints.api_server([handlers_endpoints.IsolateServer]) return frontend, api frontend_app, endpoints_app = create_application()
# Copyright 2014 The Swarming Authors. All rights reserved. # Use of this source code is governed by the Apache v2.0 license that can be # found in the LICENSE file. """This modules is imported by AppEngine and defines the 'app' object. It is a separate file so that application bootstrapping code like ereporter2, that shouldn't be done in unit tests, can be done safely. This file must be tested via a smoke test. """ import os import sys import endpoints APP_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.join(APP_DIR, 'components', 'third_party')) from components import ereporter2 from components import utils import handlers_endpoints import handlers_frontend def create_application(): ereporter2.register_formatter() # App that serves HTML pages and old API. frontend = handlers_frontend.create_application(False) # App that serves new endpoints API. api = endpoints.api_server([handlers_endpoints.isolate_api]) return frontend, api frontend_app, endpoints_app = create_application()
Fix number of extra bytes for CryptoBoxSeal and CryptoBoxSealOpen
package cryptobox // #cgo pkg-config: libsodium // #include <stdlib.h> // #include <sodium.h> import "C" import "github.com/GoKillers/libsodium-go/support" func CryptoBoxSeal(m []byte, pk []byte) ([]byte, int) { support.CheckSize(pk, CryptoBoxPublicKeyBytes(), "public key") c := make([]byte, len(m)+CryptoBoxSealBytes()) exit := int(C.crypto_box_seal( (*C.uchar)(&c[0]), (*C.uchar)(&m[0]), (C.ulonglong)(len(m)), (*C.uchar)(&pk[0]))) return c, exit } func CryptoBoxSealOpen(c []byte, pk []byte, sk []byte) ([]byte, int) { support.CheckSize(pk, CryptoBoxPublicKeyBytes(), "public key") support.CheckSize(sk, CryptoBoxSecretKeyBytes(), "secret key") m := make([]byte, len(c)-CryptoBoxSealBytes()) exit := int(C.crypto_box_seal_open( (*C.uchar)(&m[0]), (*C.uchar)(&c[0]), (C.ulonglong)(len(c)), (*C.uchar)(&pk[0]), (*C.uchar)(&sk[0]))) return m, exit } func CryptoBoxSealBytes() int { return int(C.crypto_box_sealbytes()) }
package cryptobox // #cgo pkg-config: libsodium // #include <stdlib.h> // #include <sodium.h> import "C" import "github.com/GoKillers/libsodium-go/support" func CryptoBoxSeal(m []byte, pk []byte) ([]byte, int) { support.CheckSize(pk, CryptoBoxPublicKeyBytes(), "public key") c := make([]byte, len(m)+CryptoBoxMacBytes()) exit := int(C.crypto_box_seal( (*C.uchar)(&c[0]), (*C.uchar)(&m[0]), (C.ulonglong)(len(m)), (*C.uchar)(&pk[0]))) return c, exit } func CryptoBoxSealOpen(c []byte, pk []byte, sk []byte) ([]byte, int) { support.CheckSize(pk, CryptoBoxPublicKeyBytes(), "public key") support.CheckSize(sk, CryptoBoxSecretKeyBytes(), "secret key") m := make([]byte, len(c)-CryptoBoxMacBytes()) exit := int(C.crypto_box_seal_open( (*C.uchar)(&m[0]), (*C.uchar)(&c[0]), (C.ulonglong)(len(c)), (*C.uchar)(&pk[0]), (*C.uchar)(&sk[0]))) return m, exit } func CryptoBoxSealBytes() int { return int(C.crypto_box_sealbytes()) }
Store untagged root logger in map together with all tagged loggers
package org.tinylog; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * Static logger for issuing log entries. */ public final class Logger { private static final ConcurrentMap<String, TaggedLogger> loggers = new ConcurrentHashMap<>(); /** */ private Logger() { } /** * Retrieves a tagged logger instance. Category tags are case-sensitive. If a tagged logger does not yet exists for * the passed tag, a new logger will be created. This method always returns the same logger instance for the same * tag. * * @param tag The case-sensitive category tag of the requested logger, or {@code null} for receiving an untagged * logger * @return Logger instance */ public static TaggedLogger tag(String tag) { if (tag == null || tag.isEmpty()) { return loggers.computeIfAbsent("", untagged -> new TaggedLogger(null)); } else { return loggers.computeIfAbsent(tag, TaggedLogger::new); } } }
package org.tinylog; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * Static logger for issuing log entries. */ public final class Logger { private static final ConcurrentMap<String, TaggedLogger> loggers = new ConcurrentHashMap<>(); private static final TaggedLogger logger = new TaggedLogger(null); /** */ private Logger() { } /** * Retrieves a tagged logger instance. Category tags are case-sensitive. If a tagged logger does not yet exists for * the passed tag, a new logger will be created. This method always returns the same logger instance for the same * tag. * * @param tag The case-sensitive category tag of the requested logger, or {@code null} for receiving an untagged * logger * @return Logger instance */ public static TaggedLogger tag(String tag) { if (tag == null || tag.isEmpty()) { return logger; } else { return loggers.computeIfAbsent(tag, TaggedLogger::new); } } }
Revert "Refactor RelativeResize param extraction in filter loader" This reverts commit 6226d0f5dffda0f8db8cfa212ced16b73c44b1b0.
<?php namespace Liip\ImagineBundle\Imagine\Filter\Loader; use Imagine\Exception\InvalidArgumentException; use Imagine\Image\ImageInterface; use Liip\ImagineBundle\Imagine\Filter\RelativeResize; /** * Loader for this bundle's relative resize filter. * * @author Jeremy Mikola <jmikola@gmail.com> */ class RelativeResizeFilterLoader implements LoaderInterface { /** * {@inheritdoc} */ public function load(ImageInterface $image, array $options = array()) { foreach ($options as $method => $parameter) { $filter = new RelativeResize($method, $parameter); return $filter->apply($image); } throw new InvalidArgumentException('Expected method/parameter pair, none given'); } }
<?php namespace Liip\ImagineBundle\Imagine\Filter\Loader; use Imagine\Exception\InvalidArgumentException; use Imagine\Image\ImageInterface; use Liip\ImagineBundle\Imagine\Filter\RelativeResize; /** * Loader for this bundle's relative resize filter. * * @author Jeremy Mikola <jmikola@gmail.com> */ class RelativeResizeFilterLoader implements LoaderInterface { /** * {@inheritdoc} */ public function load(ImageInterface $image, array $options = array()) { if (list($method, $parameter) = each($options)) { $filter = new RelativeResize($method, $parameter); return $filter->apply($image); } throw new InvalidArgumentException('Expected method/parameter pair, none given'); } }
Add TypeTable(), Operate() and MustOperate() to orm.Interface All those methods are implemented by both Orm and Tx
package orm import ( "reflect" "gnd.la/orm/operation" "gnd.la/orm/query" ) // Interface is implemented by both Orm // and Transaction. This allows functions to // receive an orm.Interface parameter and work // with both transactions and outside of them. // See the Orm documentation to find what each // method does. type Interface interface { TypeTable(reflect.Type) *Table Table(t *Table) *Query Exists(t *Table, q query.Q) (bool, error) Count(t *Table, q query.Q) (uint64, error) Query(q query.Q) *Query One(q query.Q, out ...interface{}) (bool, error) MustOne(q query.Q, out ...interface{}) bool All() *Query Insert(obj interface{}) (Result, error) MustInsert(obj interface{}) Result Update(q query.Q, obj interface{}) (Result, error) MustUpdate(q query.Q, obj interface{}) Result Upsert(q query.Q, obj interface{}) (Result, error) MustUpsert(q query.Q, obj interface{}) Result Save(obj interface{}) (Result, error) MustSave(obj interface{}) Result DeleteFrom(t *Table, q query.Q) (Result, error) Delete(obj interface{}) error MustDelete(obj interface{}) Begin() (*Tx, error) Operate(*Table, query.Q, ...*operation.Operation) (Result, error) MustOperate(*Table, query.Q, ...*operation.Operation) Result }
package orm import ( "gnd.la/orm/query" ) // Interface is implemented by both Orm // and Transaction. This allows functions to // receive an orm.Interface parameter and work // with both transactions and outside of them. // See the Orm documentation to find what each // method does. type Interface interface { Table(t *Table) *Query Exists(t *Table, q query.Q) (bool, error) Count(t *Table, q query.Q) (uint64, error) Query(q query.Q) *Query One(q query.Q, out ...interface{}) (bool, error) MustOne(q query.Q, out ...interface{}) bool All() *Query Insert(obj interface{}) (Result, error) MustInsert(obj interface{}) Result Update(q query.Q, obj interface{}) (Result, error) MustUpdate(q query.Q, obj interface{}) Result Upsert(q query.Q, obj interface{}) (Result, error) MustUpsert(q query.Q, obj interface{}) Result Save(obj interface{}) (Result, error) MustSave(obj interface{}) Result DeleteFrom(t *Table, q query.Q) (Result, error) Delete(obj interface{}) error MustDelete(obj interface{}) Begin() (*Tx, error) }
Remove certain files from build
const cssStandards = require('spike-css-standards'); const latest = require('babel-preset-latest'); const reshape = require('reshape'); const include = require('reshape-include'); const layouts = require('reshape-layouts'); const content = require('reshape-content'); const expressions = require('reshape-expressions'); const listings = require('./data/listings.json'); module.exports = { devtool: 'source-map', ignore: [ 'views/layout.html', 'views/partials/*', 'data/*', '.github/*', 'Readme.md', 's3_website.yml', '**/_*', '**/.*' ], reshape: { locals: { defaultTitle: 'JuniorJobs - Entry level jobs in UK tech/design', jobs: listings }, plugins: [ layouts(), content(), include(), expressions() ] }, postcss: (ctx) => { return cssStandards({ parser: false, webpack: ctx }) }, babel: { presets: [latest] } };
const cssStandards = require('spike-css-standards'); const latest = require('babel-preset-latest'); const reshape = require('reshape'); const include = require('reshape-include'); const layouts = require('reshape-layouts'); const content = require('reshape-content'); const expressions = require('reshape-expressions'); const listings = require('./data/listings.json'); module.exports = { devtool: 'source-map', ignore: ['**/layout.html', '**/_*', '**/.*'], reshape: { locals: { defaultTitle: 'JuniorJobs - Entry level jobs in UK tech/design', jobs: listings }, plugins: [ layouts(), content(), include(), expressions() ] }, postcss: (ctx) => { return cssStandards({ parser: false, webpack: ctx }) }, babel: { presets: [latest] } };
Enable livereload in grunt watch
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), sass: { dist: { options: { sourcemap: 'none' }, files: { 'test/hocus-pocus.css': 'hocus-pocus.sass' } } }, autoprefixer: { no_dest: { src: 'test/hocus-pocus.css' } }, watch: { files: ['**/*.sass'], tasks: ['sass', 'autoprefixer'], options: { livereload: true } }, connect: { server: { options: { port: 3000, base: 'test/' } } } }); grunt.loadNpmTasks('grunt-contrib-sass'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-connect'); grunt.loadNpmTasks('grunt-autoprefixer'); grunt.registerTask('default', ['connect', 'watch']); };
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), sass: { dist: { options: { sourcemap: 'none' }, files: { 'test/hocus-pocus.css': 'hocus-pocus.sass' } } }, autoprefixer: { no_dest: { src: 'test/hocus-pocus.css' } }, watch: { files: ['**/*.sass'], tasks: ['sass', 'autoprefixer'], }, connect: { server: { options: { port: 3000, base: 'test/' } } } }); grunt.loadNpmTasks('grunt-contrib-sass'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-connect'); grunt.loadNpmTasks('grunt-autoprefixer'); grunt.registerTask('default', ['connect', 'watch']); };
Add spinner when loggin in
import React from 'react'; import {browserHistory} from 'react-router' import Login from './Login'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import * as actions from '../actions/LoginActions'; import {AUTHENTICATED, DEFAULT, ERROR, LOADING} from '../constants/loginStates' import CircularProgress from 'material-ui/CircularProgress'; export const HomePage = (props) => { let onLogin = phone => { props.actions.login(phone) } console.log(props.loginState) if (props.loginState === AUTHENTICATED) { browserHistory.push('/status') } return ( <div> <div style={props.spinnerStyles}> <CircularProgress /> </div> <Login error={props.errorMessage} onClick={onLogin}/> </div> ); }; function mapStateToProps(state, ownprops) { const errorMessage = 'Login failed try again' return { data: state.loginReducer, loginState: state.loginReducer.loginState, errorMessage: state.loginReducer.loginState === ERROR ? errorMessage : null, spinnerStyles: { display: state.loginReducer.loginState === LOADING ? 'block' : 'hidden' } } } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(actions, dispatch) }; } export default connect( mapStateToProps, mapDispatchToProps )(HomePage);
import React from 'react'; import {browserHistory} from 'react-router' import Login from './Login'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import * as actions from '../actions/LoginActions'; import {AUTHENTICATED, DEFAULT, ERROR, LOADING} from '../constants/loginStates' export const HomePage = (props) => { let onLogin = phone => { props.actions.login(phone) } console.log(props.loginState) if (props.loginState === AUTHENTICATED) { browserHistory.push('/status') } return ( <div> <Login error={props.errorMessage} onClick={onLogin}/> </div> ); }; function mapStateToProps(state, ownprops) { const errorMessage = 'Login failed try again' return { data: state.loginReducer, loginState: state.loginReducer.loginState, errorMessage: state.loginReducer.loginState === ERROR ? errorMessage : null }; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(actions, dispatch) }; } export default connect( mapStateToProps, mapDispatchToProps )(HomePage);
Change the name for the adapter
var path = require('path'); var createPattern = function(path, included) { return {pattern: path, included: included, served: true, watched: false}; }; var initMocha = function(files, mochaConfig) { var mochaPath = path.dirname(require.resolve('mocha')); files.unshift(createPattern(__dirname + '/testrunner.sw.js')); files.unshift(createPattern(__dirname + '/index.html')); files.unshift(createPattern(mochaPath + '/mocha.js')); files.unshift(createPattern(__dirname + '/adapter.js', true)); if (mochaConfig && mochaConfig.reporter) { files.unshift(createPattern(mochaPath + '/mocha.css')); } }; initMocha.$inject = ['config.files', 'config.client.mocha']; module.exports = { 'framework:sw-mocha': ['factory', initMocha] };
var path = require('path'); var createPattern = function(path, included) { return {pattern: path, included: included, served: true, watched: false}; }; var initMocha = function(files, mochaConfig) { var mochaPath = path.dirname(require.resolve('mocha')); files.unshift(createPattern(__dirname + '/testrunner.sw.js')); files.unshift(createPattern(__dirname + '/index.html')); files.unshift(createPattern(mochaPath + '/mocha.js')); files.unshift(createPattern(__dirname + '/adapter.js', true)); if (mochaConfig && mochaConfig.reporter) { files.unshift(createPattern(mochaPath + '/mocha.css')); } }; initMocha.$inject = ['config.files', 'config.client.mocha']; module.exports = { 'framework:mocha': ['factory', initMocha] };
Reformat the code. Mark the type `final`.
/* * Copyright 2021, TeamDev. 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 * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.server.entity.given.repository; import io.spine.server.entity.TransactionalEntity; import io.spine.test.entity.Project; import io.spine.test.entity.ProjectId; public final class ProjectEntity extends TransactionalEntity<ProjectId, Project, Project.Builder> { private ProjectEntity(ProjectId id) { super(id); } }
/* * Copyright 2021, TeamDev. 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 * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.server.entity.given.repository; import io.spine.server.entity.TransactionalEntity; import io.spine.test.entity.Project; import io.spine.test.entity.ProjectId; public class ProjectEntity extends TransactionalEntity<ProjectId, Project, Project.Builder> { private ProjectEntity(ProjectId id) { super(id); } }
Change desustorage URL to desuarchive
# 4chThreadArchiver # Copyright (C) 2016, Sebastian "Chloride Cull" Johansson # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. ARCHIVE_SITE="https://desuarchive.org" UA="4chThreadArchiver/1.0 (Python {vinfo[0]}.{vinfo[1]}.{vinfo[2]}, using urllib)" #UA="Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.71 Safari/537.36"
# 4chThreadArchiver # Copyright (C) 2016, Sebastian "Chloride Cull" Johansson # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. ARCHIVE_SITE="https://desustorage.org" UA="4chThreadArchiver/1.0 (Python {vinfo[0]}.{vinfo[1]}.{vinfo[2]}, using urllib)" #UA="Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.71 Safari/537.36"
Add announcer UI to UI list and set it to autoload.
var UI = UI || {}; UI.Modules = { "character": { core: true }, "chat": { core: true }, "errormessages": { core: true }, "kills": { core: true }, "login": { core: true }, "perfhud": { core: true }, "respawn": { core: true }, "skillbar": { core: true }, "target": { core: true }, "options": { core: true }, "equippedgear": { core: true }, "inventory": { core: true }, "addons": { core: false, autoLoad: true }, // custom-ui's go below... // "example": { core: false, autoLoad: true } "lb": { core: false, autoLoad: true }, "heatmap": { core: false, autoLoad: true }, "perf": { core: false, autoLoad: true }, "pop": { core: false, autoLoad: true }, "bct": { core: false, autoLoad: true }, "announcer": { core: false, autoLoad: true }, "pledges": { core: false } };
var UI = UI || {}; UI.Modules = { "character": { core: true }, "chat": { core: true }, "errormessages": { core: true }, "kills": { core: true }, "login": { core: true }, "perfhud": { core: true }, "respawn": { core: true }, "skillbar": { core: true }, "target": { core: true }, "options": { core: true }, "equippedgear": { core: true }, "inventory": { core: true }, "addons": { core: false, autoLoad: true }, // custom-ui's go below... // "example": { core: false, autoLoad: true } "lb": { core: false, autoLoad: true }, "heatmap": { core: false, autoLoad: true }, "perf": { core: false, autoLoad: true }, "pop": { core: false, autoLoad: true }, "bct": { core: false, autoLoad: true }, "pledges": { core: false } };
Make selected business link only visible if set
<li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">{{ trans('app.nav.user.business.menu') }} <b class="caret"></b></a> <ul class="dropdown-menu"> @if($business = Session::get('selected.business')) <li><a href="{{ route('user.businesses.home') }}">{!! Icon::map_marker() !!}&nbsp;{{ $business->name }}</a></li> <li class="nav-divider"></li> @endif <li><a href="{{ route('user.businesses.list') }}">{{ trans('app.nav.user.business.selector') }}</a></li> <li><a href="{{ route('user.businesses.suscriptions') }}">{{ trans('app.nav.user.business.my_suscriptions') }}</a></li> <li class="nav-divider"></li> <li><a href="{{ route('user.booking.list') }}">{{ trans('app.nav.user.business.my_appointments') }}</a></li> <li class="nav-divider"></li> <li><a href="{{ route('wizard.welcome') }}">{{ trans('app.nav.wizard') }}</a></li> </ul> </li>
<li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">{{ trans('app.nav.user.business.menu') }} <b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="{{ route('user.businesses.home') }}">{{ trans('app.nav.user.business.home') }}</a></li> <li><a href="{{ route('user.businesses.list') }}">{{ trans('app.nav.user.business.selector') }}</a></li> <li><a href="{{ route('user.businesses.suscriptions') }}">{{ trans('app.nav.user.business.my_suscriptions') }}</a></li> <li class="nav-divider"></li> <li><a href="{{ route('user.booking.list') }}">{{ trans('app.nav.user.business.my_appointments') }}</a></li> <li class="nav-divider"></li> <li><a href="{{ route('wizard.welcome') }}">{{ trans('app.nav.wizard') }}</a></li> </ul> </li>
:new: Add a dummy return value in getDeclarations
'use babel' /* @flow */ import {CompositeDisposable, Emitter} from 'atom' import type {TextEditor, Disposable} from 'atom' import type {Editor} from './editor' import type {Atom$Range, Declarations$Declaration} from './types' export class Declarations { emitter: Emitter; grammarScopes: Array<string>; subscriptions: CompositeDisposable; constructor() { this.emitter = new Emitter() this.subscriptions = new CompositeDisposable() this.grammarScopes = ['source.js.flint'] this.subscriptions.add(this.emitter) } async getDeclarations({textEditor, visibleRange}: {textEditor: TextEditor, visibleRange: Atom$Range}): Promise<Array<Declarations$Declaration>> { return [ { range: [[0, 0], [0, 1]], source: { filePath: '/etc/passwd', position: [10, 0] } } ] } requestEditor(textEditor: TextEditor): ?Editor { const event = {textEditor, editor: null} this.emitter.emit('should-provide-editor', event) return event.editor } onShouldProvideEditor(callback: Function): Disposable { return this.emitter.on('should-provide-editor', callback) } dispose() { this.subscriptions.dispose() } }
'use babel' /* @flow */ import {CompositeDisposable, Emitter} from 'atom' import type {TextEditor, Disposable} from 'atom' import type {Editor} from './editor' import type {Atom$Range, Declarations$Declaration} from './types' export class Declarations { emitter: Emitter; grammarScopes: Array<string>; subscriptions: CompositeDisposable; constructor() { this.emitter = new Emitter() this.subscriptions = new CompositeDisposable() this.grammarScopes = ['source.js.flint'] this.subscriptions.add(this.emitter) } async getDeclarations({textEditor, visibleRange}: {textEditor: TextEditor, visibleRange: Atom$Range}): Promise<Array<Declarations$Declaration>> { console.log('getDeclarations flint', visibleRange) return [] } requestEditor(textEditor: TextEditor): ?Editor { const event = {textEditor, editor: null} this.emitter.emit('should-provide-editor', event) return event.editor } onShouldProvideEditor(callback: Function): Disposable { return this.emitter.on('should-provide-editor', callback) } dispose() { this.subscriptions.dispose() } }
Fix imports at top of file.
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # This module copyright (C) 2013 Therp BV (<http://therp.nl>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from . import res_partner from . import res_partner_relation from . import res_partner_relation_type from . import res_partner_relation_all from . import res_partner_relation_type_selection PADDING = 10 def get_partner_type(partner): """Get partner type for relation. :param partner: a res.partner either a company or not :return: 'c' for company or 'p' for person :rtype: str """ return 'c' if partner.is_company else 'p'
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # This module copyright (C) 2013 Therp BV (<http://therp.nl>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## PADDING = 10 def get_partner_type(partner): """Get partner type for relation. :param partner: a res.partner either a company or not :return: 'c' for company or 'p' for person :rtype: str """ return 'c' if partner.is_company else 'p' from . import res_partner from . import res_partner_relation from . import res_partner_relation_type from . import res_partner_relation_all from . import res_partner_relation_type_selection
Clear the optimized route after changing scenario
var BaseView = require('views/map-view'); module.exports = BaseView.extend({ gRouteOptions: { polylineOptions: { strokeColor: '#e6a640' } }, initialize: function () { this.collection.on('sort', this.renderDirections, this); this.collection.on('reset', this.render, this); BaseView.prototype.initialize.apply(this, arguments); }, handleReset: function () { this.renderWaypoints(); }, render: function() { this.renderSelf(); this.renderWaypoints(); this.fitBounds(); this.clearRoutes(); return this; } });
var BaseView = require('views/map-view'); module.exports = BaseView.extend({ gRouteOptions: { polylineOptions: { strokeColor: '#e6a640' } }, initialize: function () { this.collection.on('sort', this.renderDirections, this); this.collection.on('reset', this.render, this); BaseView.prototype.initialize.apply(this, arguments); }, handleReset: function () { this.renderWaypoints(); }, render: function() { this.renderSelf(); this.renderWaypoints(); this.fitBounds(); return this; } });
Add @api private on private EC2 methods
var AWS = require('../core'); AWS.EC2 = AWS.Service.defineService('ec2', ['2013-06-15*', '2013-07-15*', '2013-08-15*', '2013-10-01*', '2013-10-15'], { /** * @api private */ setupRequestListeners: function setupRequestListeners(request) { request.removeListener('extractError', AWS.EventListeners.Query.EXTRACT_ERROR); request.addListener('extractError', this.extractError); }, /** * @api private */ extractError: function extractError(resp) { // EC2 nests the error code and message deeper than other AWS Query services. var httpResponse = resp.httpResponse; var data = new AWS.XML.Parser({}).parse(httpResponse.body.toString() || ''); if (data.Errors) resp.error = AWS.util.error(new Error(), { code: data.Errors.Error.Code, message: data.Errors.Error.Message }); else resp.error = AWS.util.error(new Error(), { code: httpResponse.statusCode, message: null }); } }); module.exports = AWS.EC2;
var AWS = require('../core'); AWS.EC2 = AWS.Service.defineService('ec2', ['2013-06-15*', '2013-07-15*', '2013-08-15*', '2013-10-01*', '2013-10-15'], { setupRequestListeners: function setupRequestListeners(request) { request.removeListener('extractError', AWS.EventListeners.Query.EXTRACT_ERROR); request.addListener('extractError', this.extractError); }, /** * @api private */ extractError: function extractError(resp) { // EC2 nests the error code and message deeper than other AWS Query services. var httpResponse = resp.httpResponse; var data = new AWS.XML.Parser({}).parse(httpResponse.body.toString() || ''); if (data.Errors) resp.error = AWS.util.error(new Error(), { code: data.Errors.Error.Code, message: data.Errors.Error.Message }); else resp.error = AWS.util.error(new Error(), { code: httpResponse.statusCode, message: null }); } }); module.exports = AWS.EC2;
Clear old method of calling plugins
from tornado import gen, ioloop from tornado.ioloop import IOLoop import sys from pkg_resources import iter_entry_points import json @gen.coroutine def main(plugin): response = yield plugin['receiver']("Prufa") print("Results: \n%s" % json.dumps(response, sort_keys=True, indent=4, separators=(',', ': '))) if __name__ == "__main__": if(len(sys.argv) > 1): iplugin = __import__("%s" % sys.argv[1]) plugin = iplugin.plugin instance = IOLoop.instance() instance.add_callback(callback=lambda: main(plugin)) instance.start() else: for object in iter_entry_points(group='sundaytasks.plugin', name=None): print object.name plugin = object.load() instance = IOLoop.instance() instance.add_callback(callback=lambda: main(plugin)) instance.start()
from tornado import gen, ioloop from tornado.ioloop import IOLoop import sys from pkg_resources import iter_entry_points import json @gen.coroutine def main(plugin): #print("plugin:",plugin['receiver']) response = yield plugin['receiver']("Prufa") print("Results: \n%s" % json.dumps(response, sort_keys=True, indent=4, separators=(',', ': '))) if __name__ == "__main__": if(len(sys.argv) > 1): iplugin = __import__("%s" % sys.argv[1]) plugin = iplugin.plugin instance = IOLoop.instance() instance.add_callback(callback=lambda: main(plugin)) instance.start() else: for object in iter_entry_points(group='sundaytasks.plugin', name=None): print object.name plugin = object.load() instance = IOLoop.instance() instance.add_callback(callback=lambda: main(plugin)) instance.start()
Fix order of then to avoid issue if success/error callback make a then on same promise
export default class CancelablePromise { static all(iterable) { return Promise.all(iterable); } static race(iterable) { return Promise.race(iterable); } static reject(iterable) { return Promise.reject(iterable); } static resolve(iterable) { return Promise.resolve(iterable); } constructor(executor) { let superResolve, superReject; this._promise = new Promise(executor); this._canceled = false; this._onError = []; this._onSuccess = []; let success = (...args) => { if(this._canceled) return; this.then = this._promise.then.bind(this._promise); this._onSuccess.forEach((cb) => { cb(...args); }); }; let error = (...args) => { if(this._canceled) return; this.then = this._promise.then.bind(this._promise); this._onError.forEach((cb) => { cb(...args); }); }; this._promise.then(success, error); } then(success, error) { if (success) this._onSuccess.push(success); if (error) this._onError.push(error); return this; } catch(error) { if (error) this._onError.push(error); return this; } cancel() { this._canceled = true; } }
export default class CancelablePromise { static all(iterable) { return Promise.all(iterable); } static race(iterable) { return Promise.race(iterable); } static reject(iterable) { return Promise.reject(iterable); } static resolve(iterable) { return Promise.resolve(iterable); } constructor(executor) { let superResolve, superReject; this._promise = new Promise(executor); this._canceled = false; this._onError = []; this._onSuccess = []; let success = (...args) => { if(this._canceled) return; this._onSuccess.forEach((cb) => { cb(...args); }); this.then = this._promise.then.bind(this._promise); }; let error = (...args) => { if(this._canceled) return; this._onError.forEach((cb) => { cb(...args); }); this.then = this._promise.then.bind(this._promise); }; this._promise.then(success, error); } then(success, error) { if (success) this._onSuccess.push(success); if (error) this._onError.push(error); return this; } catch(error) { if (error) this._onError.push(error); return this; } cancel() { this._canceled = true; } }
Add constructor to NewError instances
function ErrorMaker(name, ParentError) { var NewError = function NewError(message) { if (!(this instanceof NewError)) return new NewError(message) // get stack try { throw new Error(message) } catch (err) { err.name = name this.stack = err.stack } // A bit of a hack to get the error message to show correctly if (this.stack && this.stack.substr(0, this.name.length) !== this.name) { var errorMessage = name if (message) { errorMessage += ': ' + message } this.stack = errorMessage + this.stack.slice(this.stack.indexOf('\n')) } this.message = message || '' this.name = name } ParentError = ParentError || Error NewError.prototype = new ParentError() NewError.prototype.constructor = NewError NewError.prototype.name = name return NewError } module.exports = ErrorMaker
function ErrorMaker(name, ParentError) { var NewError = function NewError(message) { if (!(this instanceof NewError)) return new NewError(message) // get stack try { throw new Error(message) } catch (err) { err.name = name this.stack = err.stack } // A bit of a hack to get the error message to show correctly if (this.stack && this.stack.substr(0, this.name.length) !== this.name) { var errorMessage = name if (message) { errorMessage += ': ' + message } this.stack = errorMessage + this.stack.slice(this.stack.indexOf('\n')) } this.message = message || '' this.name = name } ParentError = ParentError || Error NewError.prototype = new ParentError() NewError.prototype.name = name return NewError } module.exports = ErrorMaker
Remove green outline colouring when validation passes
/** * Created by nkmathew on 05/07/2016. */ $("#profile-form").submit(function (e) { $("#btn-submit-profile").spin(BIG_SPINNER); var url = '/site/profile'; $.ajax({ type: 'POST', url: url, data: $("#profile-form").serialize(), success: function (data) { // Remove spinner $("#btn-submit-profile").spin(false); // Remove green outline colouring when validation passes setTimeout(function () { $('.has-success').each(function () { $(this).removeClass('has-success'); }) }, 5000); }, error: function (xhr, status, error) { $("#btn-invite-sender").spin(false); $('.alert-box .msg').html('<h4>' + error + '</h4><br/>' + xhr.responseText); $('.alert-box').addClass('alert-danger'); $('.alert-box').show(); }, }); e.preventDefault(); });
/** * Created by nkmathew on 05/07/2016. */ $("#profile-form").submit(function (e) { $("#btn-submit-profile").spin(BIG_SPINNER); var url = '/site/profile'; $.ajax({ type: 'POST', url: url, data: $("#profile-form").serialize(), success: function (data) { // Remove spinner $("#btn-submit-profile").spin(false); }, error: function (xhr, status, error) { $("#btn-invite-sender").spin(false); $('.alert-box .msg').html('<h4>' + error + '</h4><br/>' + xhr.responseText); $('.alert-box').addClass('alert-danger'); $('.alert-box').show(); }, }); e.preventDefault(); });
Update npm-react error to point to autoflow
'use strict'; var copyProperties = require('./lib/copyProperties'); var WARNING_MESSAGE = ( 'It looks like you\'re trying to use jeffbski\'s React.js project.\n' + 'The `react` npm package now points to the React JavaScript library for ' + 'building user interfaces, not the React.js project for managing asynchronous ' + 'control flow. If you\'re looking for that library, please npm install autoflow.' ); function error() { throw new Error(WARNING_MESSAGE); } // Model the React.js project's public interface exactly. function ReactJSShim() { error(); } ReactJSShim.logEvents = error; ReactJSShim.resolvePromises = error; ReactJSShim.trackTasks = error; ReactJSShim.createEventCollector = error; // These could throw using defineProperty() but supporting older browsers will // be painful. Additionally any error messages around this will contain the string // so I think this is sufficient. ReactJSShim.options = WARNING_MESSAGE; ReactJSShim.events = WARNING_MESSAGE; var ReactJSErrors = { wrap: function(module) { copyProperties(ReactJSShim, module); return ReactJSShim; } }; module.exports = ReactJSErrors;
var copyProperties = require('./lib/copyProperties'); var WARNING_MESSAGE = ( 'It looks like you\'re trying to use jeffbski\'s React.js project.\n' + 'The `react` npm package now points to the React JavaScript library for ' + 'building user interfaces, not the React.js project for managing asynchronous ' + 'control flow. If you\'re looking for that library, please npm install reactjs.' ); function error() { throw new Error(WARNING_MESSAGE); } // Model the React.js project's public interface exactly. function ReactJSShim() { error(); }; ReactJSShim.logEvents = error; ReactJSShim.resolvePromises = error; ReactJSShim.trackTasks = error; ReactJSShim.createEventCollector = error; // These could throw using defineProperty() but supporting older browsers will // be painful. Additionally any error messages around this will contain the string // so I think this is sufficient. ReactJSShim.options = WARNING_MESSAGE; ReactJSShim.events = WARNING_MESSAGE; var ReactJSErrors = { wrap: function(module) { copyProperties(ReactJSShim, module); return ReactJSShim; } }; module.exports = ReactJSErrors;
Add Skip Waiting to service worker
/* Copyright 2016 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function() { 'use strict'; // TODO - 3.1: Add install and activate event listeners self.addEventListener('install', function(event) { console.log('Service worker installing...'); // TODO 3.4: Skip waiting self.skipWaiting(); }); self.addEventListener('activate', function(event) { console.log('Service worker activating...'); }); // TODO - 3.3: Add a comment to change the service worker // I'm a new service worker // TODO - 4: Add fetch listener })();
/* Copyright 2016 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function() { 'use strict'; // TODO - 3.1: Add install and activate event listeners self.addEventListener('install', function(event) { console.log('Service worker installing...'); // TODO 3.4: Skip waiting }); self.addEventListener('activate', function(event) { console.log('Service worker activating...'); }); // TODO - 3.3: Add a comment to change the service worker // I'm a new service worker // TODO - 4: Add fetch listener })();
fix: Increase client-side network timeout from 20 seconds to 60 We're having problems in the staging environment where requests are taking longer than 20 seconds and are timing out so the user can't perform certain actions. Increasing the timeout to 60 seconds won't improve the slow performance obviously, but it will at least prevent requests from timing out and will allow the user to use the application normally (albeit slowly).
import wrapper from 'atomic-fuel/libs/constants/wrapper'; import Network from 'atomic-fuel/libs/constants/network'; // Increasing timeout to accomodate slow environments. Default is 20_000. Network.TIMEOUT = 60_000; // Local actions const actions = []; // Actions that make an api request const requests = ['SEARCH_FOR_ACCOUNT_USERS', 'GET_ACCOUNT_USER', 'UPDATE_ACCOUNT_USER']; export const Constants = wrapper(actions, requests); export const searchForAccountUsers = (searchTerm, page) => ({ type: Constants.SEARCH_FOR_ACCOUNT_USERS, method: Network.GET, url: 'api/canvas_account_users', params: { search_term: searchTerm, page, }, }); export const getAccountUser = userId => ({ type: Constants.GET_ACCOUNT_USER, method: Network.GET, url: `api/canvas_account_users/${userId}`, }); export const updateAccountUser = (userId, userAttributes) => ({ type: Constants.UPDATE_ACCOUNT_USER, method: Network.PUT, url: `api/canvas_account_users/${userId}`, body: { user: { name: userAttributes.name, login_id: userAttributes.loginId, sis_user_id: userAttributes.sisUserId, email: userAttributes.email, }, }, });
import wrapper from 'atomic-fuel/libs/constants/wrapper'; import Network from 'atomic-fuel/libs/constants/network'; // Local actions const actions = []; // Actions that make an api request const requests = ['SEARCH_FOR_ACCOUNT_USERS', 'GET_ACCOUNT_USER', 'UPDATE_ACCOUNT_USER']; export const Constants = wrapper(actions, requests); export const searchForAccountUsers = (searchTerm, page) => ({ type: Constants.SEARCH_FOR_ACCOUNT_USERS, method: Network.GET, url: 'api/canvas_account_users', params: { search_term: searchTerm, page, }, }); export const getAccountUser = userId => ({ type: Constants.GET_ACCOUNT_USER, method: Network.GET, url: `api/canvas_account_users/${userId}`, }); export const updateAccountUser = (userId, userAttributes) => ({ type: Constants.UPDATE_ACCOUNT_USER, method: Network.PUT, url: `api/canvas_account_users/${userId}`, body: { user: { name: userAttributes.name, login_id: userAttributes.loginId, sis_user_id: userAttributes.sisUserId, email: userAttributes.email, }, }, });
Add log levels to messages
package logger import ( "encoding/json" "log" "github.com/bsphere/le_go" "github.com/emreler/finch/config" ) const ( levelInfo = "INFO" levelError = "ERROR" ) // Logger . type Logger struct { conn *le_go.Logger } // LogMessage . type LogMessage struct { Level string `json:"level"` Message string `json:"message"` } // NewLogger . func NewLogger(token config.LogentriesConfig) *Logger { le, err := le_go.Connect(string(token)) if err != nil { panic(err) } log.Println("Connected to Logentries") return &Logger{le} } // Info . func (l *Logger) Info(data interface{}) { var j []byte if str, ok := data.(string); ok { logMsg := &LogMessage{ Level: levelInfo, Message: str, } j, _ = json.Marshal(logMsg) l.conn.Println(j) } else { jstring, _ := json.Marshal(data) logMsg := &LogMessage{ Level: levelInfo, Message: string(jstring), } j, _ = json.Marshal(logMsg) l.conn.Println(string(j)) } } func (l *Logger) Error(err error) { logMsg := &LogMessage{ Level: levelError, Message: err.Error(), } j, _ := json.Marshal(logMsg) l.conn.Println(string(j)) }
package logger import ( "encoding/json" "log" "github.com/bsphere/le_go" "github.com/emreler/finch/config" ) // Logger . type Logger struct { conn *le_go.Logger } // NewLogger . func NewLogger(token config.LogentriesConfig) *Logger { le, err := le_go.Connect(string(token)) if err != nil { panic(err) } log.Println("Connected to Logentries") return &Logger{le} } // Info . func (l *Logger) Info(data interface{}) { if str, ok := data.(string); ok { l.conn.Println(str) } else { jstring, _ := json.Marshal(data) l.conn.Println(string(jstring)) } } func (l *Logger) Error(err error) { l.conn.Println(err.Error()) }
Update test and make work
<?php namespace Radebatz\Assetic\Tests; use Assetic\Asset\AssetCollection; use Assetic\Cache\FilesystemCache; use Radebatz\Assetic\Factory\Worker\CacheWorker; use Radebatz\Assetic\Factory\Worker\PreprocessorWorker; /** * Test CacheWorker. */ class CacheWorkerTest extends AsseticTestCase { /** */ public function testBasic() { $cacheDir = __DIR__.'/cache'; @mkdir($cacheDir, 0777); $cacheWorker = new CacheWorker($cache = new FilesystemCache($cacheDir)); $factory = $this->getFactory($defaultRoot = __DIR__.'/assets', [$cacheWorker]); $asset = $factory->createAsset('core/js/require.js'); $this->assertTrue($asset instanceof AssetCollection); // no preprocessor... $this->assertAssetSources(['core/js/require.js'], $asset); // force caching it... $asset->load(); // check cache is not empty $cacheFiles = glob($cacheDir.'/*'); $this->assertEquals(1, count ($cacheFiles)); $this->assertEquals(file_get_contents(array_pop($cacheFiles)), file_get_contents(__DIR__.'/assets/core/js/require.js')); } }
<?php namespace Radebatz\Assetic\Tests; use Assetic\Asset\AssetCollection; use Assetic\Cache\ArrayCache; use Radebatz\Assetic\Factory\Worker\CacheWorker; use Radebatz\Assetic\Factory\Worker\PreprocessorWorker; /** * Test CacheWorker. */ class CacheWorkerTest extends AsseticTestCase { /** */ public function testBasic() { $cacheWorker = new CacheWorker($cache = new ArrayCache()); $factory = $this->getFactory($defaultRoot = __DIR__.'/assets', [$cacheWorker]); $asset = $factory->createAsset('core/js/require.js'); $this->assertTrue($asset instanceof AssetCollection); // no preprocessor... $this->assertAssetSources(['core/js/require.js'], $asset); // force caching it... $asset->load(); // check cache is not empty $rc = new \ReflectionClass($cache); $rp = $rc->getProperty('cache'); $rp->setAccessible(true); $this->assertEquals(1, count($rp->getValue($cache))); } }
Add unique index to username and email for Users
var bcrypt = require('bcrypt'); var mongoose = require('mongoose'); const saltRounds = 10; var userSchema = new mongoose.Schema({ signupDate: { type: Date, default: Date.now }, username: { type: String, required: true, unique: true }, email: { type: String, required: true, unique: true }, password: { type: String, required: true }, name: { type: String } }); userSchema.pre('save', function(next) { if (!this.isModified('password')) { return next(); } bcrypt.hash(this.password, saltRounds, function(err, hash) { if (err) { console.log(err); return next(err); } this.password = hash; next(); }.bind(this)); }); userSchema.methods.checkPassword = function(password, cb) { bcrypt.compare(password, this.password, function(err, result) { if (err) { console.log(err); return next(err); } cb(result); }); }; module.exports = mongoose.model('User', userSchema);
var bcrypt = require('bcrypt'); var mongoose = require('mongoose'); const saltRounds = 10; var userSchema = new mongoose.Schema({ signupDate: { type: Date, default: Date.now }, username: { type: String, required: true }, password: { type: String, required: true }, email: { type: String, required: true }, name: { type: String } }); userSchema.pre('save', function(next) { if (!this.isModified('password')) { return next(); } bcrypt.hash(this.password, saltRounds, function(err, hash) { if (err) { console.log(err); return next(err); } this.password = hash; next(); }.bind(this)); }); userSchema.methods.checkPassword = function(password, cb) { bcrypt.compare(password, this.password, function(err, result) { if (err) { console.log(err); return next(err); } cb(result); }); }; module.exports = mongoose.model('User', userSchema);
Fix timetable being wrongly escaped
<?php namespace Epfl\Contact; require_once 'shortcake-config.php'; function epfl_contact_process_shortcode($atts) { // sanitize parameters foreach($atts as $key => $value) { if (strpos($key, 'information') !== false || strpos($key, 'timetable') !== false) { $atts[$key] = wp_kses_post($value); } elseif ($key == 'introduction') { $atts[$key] = sanitize_textarea_field($value); } else { $atts[$key] = sanitize_text_field($value); } } if (has_action("epfl_contact_action")) { ob_start(); try { do_action("epfl_contact_action", $atts); return ob_get_contents(); } finally { ob_end_clean(); } // otherwise the plugin does the rendering } else { return 'You must activate the epfl theme'; } } add_action( 'register_shortcode_ui', __NAMESPACE__ . '\ShortCake\config'); add_action( 'init', function() { // define the shortcode add_shortcode('epfl_contact', __NAMESPACE__ . '\epfl_contact_process_shortcode'); });
<?php namespace Epfl\Contact; require_once 'shortcake-config.php'; function epfl_contact_process_shortcode($atts) { // sanitize parameters foreach($atts as $key => $value) { if (strpos($key, 'information') !== false) { $atts[$key] = wp_kses_post($value); } elseif ($key == 'introduction') { $atts[$key] = sanitize_textarea_field($value); } else { $atts[$key] = sanitize_text_field($value); } } if (has_action("epfl_contact_action")) { ob_start(); try { do_action("epfl_contact_action", $atts); return ob_get_contents(); } finally { ob_end_clean(); } // otherwise the plugin does the rendering } else { return 'You must activate the epfl theme'; } } add_action( 'register_shortcode_ui', __NAMESPACE__ . '\ShortCake\config'); add_action( 'init', function() { // define the shortcode add_shortcode('epfl_contact', __NAMESPACE__ . '\epfl_contact_process_shortcode'); });
Fix ajax to target form, since its in partial
$(function(){ $('#new_share_link').click(function(e){ e.preventDefault(); $('#new_share_modal').modal({ remote: '/shares/new', show: true }); }); $('#new_share_modal').submit('#new-share-form', function(e){ e.preventDefault(); $('#new_share_modal').modal('toggle'); var data = $(event.target).serialize(); debugger; $.ajax({ type: "POST", url: "/shares", data: data, beforeSend: customBlockUi(this) }).done(function(response) { swal({ title: "Awesome!", text: "Thanks for your share!", confirmButtonColor: "#66BB6A", type: "success" }); }).fail(function(response) { swal({ title: "Oops...", text: "Something went wrong!", confirmButtonColor: "#EF5350", type: "error" }); }); }); });
$(function(){ $('#new_share_link').click(function(e){ e.preventDefault(); $('#new_share_modal').modal({ remote: '/shares/new', show: true }); }); $('#new_share_form').submit(function(e){ e.preventDefault(); $('#new_share_modal').modal('toggle'); $.ajax({ type: "POST", url: "/shares", data: $(this).serialize(), beforeSend: customBlockUi(this) }).done(function(response) { swal({ title: "Awesome!", text: "Thanks for your share!", confirmButtonColor: "#66BB6A", type: "success" }); }).fail(function(response) { swal({ title: "Oops...", text: "Something went wrong!", confirmButtonColor: "#EF5350", type: "error" }); }); }); });
[Java] Fix name recorded in test event log.
/* * Copyright 2014-2021 Real Logic Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.aeron.log; import io.aeron.test.Tests; import org.junit.jupiter.api.extension.AfterEachCallback; import org.junit.jupiter.api.extension.BeforeEachCallback; import org.junit.jupiter.api.extension.ExtensionContext; import java.lang.reflect.Method; /** * JUnit extension to start and reset the CollectingEventLogReaderAgent. */ public class EventLogExtension implements BeforeEachCallback, AfterEachCallback { /** * {@inheritDoc} */ public void beforeEach(final ExtensionContext context) { final String className = context.getTestClass().map(Class::getSimpleName).orElse("<UNKNOWN>"); final String methodName = context.getTestMethod().map(Method::getName).orElse(context.getDisplayName()); Tests.startLogCollecting("TEST: " + className + "." + methodName); } /** * {@inheritDoc} */ public void afterEach(final ExtensionContext context) { Tests.resetLogCollecting(); } }
/* * Copyright 2014-2021 Real Logic Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.aeron.log; import io.aeron.test.Tests; import org.junit.jupiter.api.extension.AfterEachCallback; import org.junit.jupiter.api.extension.BeforeEachCallback; import org.junit.jupiter.api.extension.ExtensionContext; /** * JUnit extension to start and reset the CollectingEventLogReaderAgent. */ public class EventLogExtension implements BeforeEachCallback, AfterEachCallback { /** * {@inheritDoc} */ public void beforeEach(final ExtensionContext context) { final String className = context.getTestClass().map(Class::getSimpleName).orElse("<UNKNOWN>"); final String methodName = context.getTestClass().map(Class::getSimpleName).orElse(context.getDisplayName()); Tests.startLogCollecting("TEST: " + className + "." + methodName); } /** * {@inheritDoc} */ public void afterEach(final ExtensionContext context) { Tests.resetLogCollecting(); } }
Load CSS correctly in tests
var path = require('path'); module.exports = { entry: './test/build/index.js', output: { path: __dirname + "/build", filename: "bundle.js", publicPath: "./build/" }, bail: true, module: { loaders: [ { test: /\.css$/, loader: 'style-loader!css-loader!postcss-loader' }, { test: /\.md$/, loader: 'raw-loader'}, { test: /\.html$/, loader: "file?name=[name].[ext]" }, { test: /\.ipynb$/, loader: 'json-loader' }, { test: /\.json$/, loader: 'json-loader' }, ], }, postcss: function () { return [ require('postcss-import'), require('postcss-cssnext') ]; } }
var path = require('path'); module.exports = { entry: './test/build/index.js', output: { path: __dirname + "/build", filename: "bundle.js", publicPath: "./build/" }, bail: true, module: { loaders: [ { test: /\.css$/, loader: 'style-loader!css-loader' }, { test: /\.md$/, loader: 'raw-loader'}, { test: /\.html$/, loader: "file?name=[name].[ext]" }, { test: /\.ipynb$/, loader: 'json-loader' }, { test: /\.json$/, loader: 'json-loader' }, ], } }
Exclude collection groups from ADM UI
from __future__ import absolute_import from django import forms from django.contrib.auth.models import Group from osf.models import AdminProfile class LoginForm(forms.Form): email = forms.CharField(label=u'Email', required=True) password = forms.CharField( label=u'Password', widget=forms.PasswordInput(render_value=False), required=True ) class UserRegistrationForm(forms.Form): """ A form that finds an existing OSF User, and grants permissions to that user so that they can use the admin app""" osf_id = forms.CharField(required=True, max_length=5, min_length=5) # TODO: Moving to guardian, find a better way to distinguish "admin-like" groups from object permission groups group_perms = forms.ModelMultipleChoiceField( queryset=Group.objects.exclude(name__startswith='collections_'), required=False, widget=forms.CheckboxSelectMultiple ) class DeskUserForm(forms.ModelForm): class Meta: model = AdminProfile fields = ['desk_token', 'desk_token_secret']
from __future__ import absolute_import from django import forms from django.contrib.auth.models import Group from osf.models import AdminProfile class LoginForm(forms.Form): email = forms.CharField(label=u'Email', required=True) password = forms.CharField( label=u'Password', widget=forms.PasswordInput(render_value=False), required=True ) class UserRegistrationForm(forms.Form): """ A form that finds an existing OSF User, and grants permissions to that user so that they can use the admin app""" osf_id = forms.CharField(required=True, max_length=5, min_length=5) group_perms = forms.ModelMultipleChoiceField( queryset=Group.objects.all(), required=False, widget=forms.CheckboxSelectMultiple ) class DeskUserForm(forms.ModelForm): class Meta: model = AdminProfile fields = ['desk_token', 'desk_token_secret']
js: Remove useless timeout from DefaultScanOptions
'use strict'; import { NativeAppEventEmitter, NativeModules } from 'react-native'; const ReactNativeBluetooth = NativeModules.ReactNativeBluetooth; const didChangeState = (callback) => { var subscription = NativeAppEventEmitter.addListener( ReactNativeBluetooth.StateChanged, callback ); ReactNativeBluetooth.notifyCurrentState(); return function() { subscription.remove(); }; }; const DefaultScanOptions = { uuids: [], }; const Scan = { stopAfter: (timeout) => { return new Promise(resolve => { setTimeout(() => { ReactNativeBluetooth.stopScan() .then(resolve) .catch(console.log.bind(console)); }, timeout); }) } } const startScan = (customOptions = {}) => { let options = Object.assign({}, DefaultScanOptions, customOptions); return ReactNativeBluetooth.startScan(options.uuids).then(() => Scan); } const didDiscoverDevice = (callback) => { var subscription = NativeAppEventEmitter.addListener( ReactNativeBluetooth.DeviceDiscovered, callback ); return function() { subscription.remove(); }; }; export default { didChangeState, startScan, didDiscoverDevice, };
'use strict'; import { NativeAppEventEmitter, NativeModules } from 'react-native'; const ReactNativeBluetooth = NativeModules.ReactNativeBluetooth; const didChangeState = (callback) => { var subscription = NativeAppEventEmitter.addListener( ReactNativeBluetooth.StateChanged, callback ); ReactNativeBluetooth.notifyCurrentState(); return function() { subscription.remove(); }; }; const DefaultScanOptions = { uuids: [], timeout: 10000, }; const Scan = { stopAfter: (timeout) => { return new Promise(resolve => { setTimeout(() => { ReactNativeBluetooth.stopScan() .then(resolve) .catch(console.log.bind(console)); }, timeout); }) } } const startScan = (customOptions = {}) => { let options = Object.assign({}, DefaultScanOptions, customOptions); return ReactNativeBluetooth.startScan(options.uuids).then(() => Scan); } const didDiscoverDevice = (callback) => { var subscription = NativeAppEventEmitter.addListener( ReactNativeBluetooth.DeviceDiscovered, callback ); return function() { subscription.remove(); }; }; export default { didChangeState, startScan, didDiscoverDevice, };
Fix the pyOpenSSL version requirement.
from setuptools import setup import sys install_requires = [ 'oauth2client>=1.3.2', 'pyOpenSSL>=0.14', 'simplejson>=2.3.2', ] tests_require = list(install_requires) # Python 2 requires Mock to run tests if sys.version_info < (3, 0): tests_require += ['pbr==1.6', 'Mock'] packages = ['identitytoolkit',] setup( name = 'identity-toolkit-python-client', packages = packages, license="Apache 2.0", version = '0.1.7', description = 'Google Identity Toolkit python client library', author = 'Jin Liu', url = 'https://github.com/google/identity-toolkit-python-client', download_url = 'https://github.com/google/identity-toolkit-python-client/archive/master.zip', keywords = ['identity', 'google', 'login', 'toolkit'], # arbitrary keywords classifiers = [ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Internet :: WWW/HTTP', ], install_requires = install_requires, tests_require = tests_require, test_suite = 'tests', )
from setuptools import setup import sys install_requires = [ 'oauth2client>=1.3.2', 'pyOpenSSL==0.14', 'simplejson>=2.3.2', ] tests_require = list(install_requires) # Python 2 requires Mock to run tests if sys.version_info < (3, 0): tests_require += ['pbr==1.6', 'Mock'] packages = ['identitytoolkit',] setup( name = 'identity-toolkit-python-client', packages = packages, license="Apache 2.0", version = '0.1.7', description = 'Google Identity Toolkit python client library', author = 'Jin Liu', url = 'https://github.com/google/identity-toolkit-python-client', download_url = 'https://github.com/google/identity-toolkit-python-client/archive/master.zip', keywords = ['identity', 'google', 'login', 'toolkit'], # arbitrary keywords classifiers = [ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Internet :: WWW/HTTP', ], install_requires = install_requires, tests_require = tests_require, test_suite = 'tests', )
Test for getting virtualenv name, prompting the user
# -*- coding: utf-8 -*- """ .. module:: tests.test_pipeline.test_python :synopsis: Tests for bundled python pipelines """ from facio.pipeline.python.virtualenv import Virtualenv from mock import patch, PropertyMock from .. import BaseTestCase class TestPythonVirtualenv(BaseTestCase): def setUp(self): # Mocking State patcher = patch('facio.state.state.state', new_callable=PropertyMock, create=True) self.mock_state = patcher.start() self.mock_state.project_name = 'foo' self.mock_state.context_variables = { 'PROJECT_NAME': 'foo'} self.addCleanup(patcher.stop) @patch('facio.base.input') def test_get_name(self, mock_input): mock_input.return_value = 'bar' i = Virtualenv() name = i.get_name() self.assertEqual(name, 'bar') @patch('facio.base.input') def test_get_name_default(self, mock_input): mock_input.return_value = '' i = Virtualenv() name = i.get_name() self.assertEqual(name, 'foo')
# -*- coding: utf-8 -*- """ .. module:: tests.test_pipeline.test_python :synopsis: Tests for bundled python pipelines """ from mock import patch, PropertyMock from .. import BaseTestCase class TestPythonVirtualenv(BaseTestCase): def setUp(self): # Mocking State patcher = patch('facio.pipeline.python.virtualenv.state', new_callable=PropertyMock, create=True) self.mock_state = patcher.start() self.mock_state.project_name = 'foo' self.mock_state.context_variables = { 'PROJECT_NAME': 'foo'} self.addCleanup(patcher.stop)
Check for iPhone, iPad and iPod
module.exports = { init: function() { var client = this function isClient(name) { var agent = window.navigator.userAgent, index = agent.indexOf(name) if (index < 0) { return false } client.version = parseInt(agent.substr(index + name.length + 1)) client.name = name return true } client.isIE = isClient('MSIE') client.isFirefox = isClient('Firefox') client.isWebkit = client.isWebKit = isClient('WebKit') client.isChrome = isClient('Chrome') client.isSafari = !client.isChrome && isClient('Safari') client.isIPhone = isClient('iPhone') client.isIPad = isClient('iPad') client.isIPod = isClient('iPod') }, isQuirksMode: function(doc) { // in IE, if compatMode is undefined (early ie) or explicitly set to BackCompat, we're in quirks return this.isIE && (!doc.compatMode || doc.compatMode == 'BackCompat') } } module.exports.init()
module.exports = { init: function() { var client = this function isClient(name) { var agent = window.navigator.userAgent, index = agent.indexOf(name) if (index < 0) { return false } client.version = parseInt(agent.substr(index + name.length + 1)) client.name = name return true } client.isIE = isClient('MSIE') client.isFirefox = isClient('Firefox') client.isWebkit = client.isWebKit = isClient('WebKit') client.isChrome = isClient('Chrome') client.isSafari = !client.isChrome && isClient('Safari') }, isQuirksMode: function(doc) { // in IE, if compatMode is undefined (early ie) or explicitly set to BackCompat, we're in quirks return this.isIE && (!doc.compatMode || doc.compatMode == 'BackCompat') } } module.exports.init()
Use a relative import to get the read module
#! /usr/bin/env python # # Dakota utility programs for converting output. # # Mark Piper (mark.piper@colorado.edu) import shutil from subprocess import check_call, CalledProcessError from .read import get_names def has_interface_column(tab_file): ''' Returns True if the tabular output file has the v6.1 'interface' column. ''' try: val = get_names(tab_file)[1] == 'interface' except IOError: raise else: return(val) def strip_interface_column(tab_file): ''' Strips the 'interface' column from a Dakota 6.1 tabular output file. ''' try: bak_file = tab_file + '.orig' shutil.copyfile(tab_file, bak_file) cmd = 'cat ' + bak_file +' | colrm 9 18 > ' + tab_file check_call(cmd, shell=True) except (IOError, CalledProcessError): raise
#! /usr/bin/env python # # Dakota utility programs for converting output. # # Mark Piper (mark.piper@colorado.edu) import shutil from subprocess import check_call, CalledProcessError from dakota_utils.read import get_names def has_interface_column(tab_file): ''' Returns True if the tabular output file has the v6.1 'interface' column. ''' try: val = get_names(tab_file)[1] == 'interface' except IOError: raise else: return(val) def strip_interface_column(tab_file): ''' Strips the 'interface' column from a Dakota 6.1 tabular output file. ''' try: bak_file = tab_file + '.orig' shutil.copyfile(tab_file, bak_file) cmd = 'cat ' + bak_file +' | colrm 9 18 > ' + tab_file check_call(cmd, shell=True) except (IOError, CalledProcessError): raise
u9: Use a more readable constant.
package u9 import ( "github.com/gopherjs/gopherjs/js" "honnef.co/go/js/dom" ) // AddTabSupport is a helper that modifies a <textarea>, so that pressing tab key will insert tabs. func AddTabSupport(textArea *dom.HTMLTextAreaElement) { textArea.AddEventListener("keydown", false, func(event dom.Event) { switch ke := event.(*dom.KeyboardEvent); { case ke.KeyCode == '\t' && !ke.CtrlKey && !ke.AltKey && !ke.MetaKey && !ke.ShiftKey: // Tab. value, start, end := textArea.Value, textArea.SelectionStart, textArea.SelectionEnd textArea.Value = value[:start] + "\t" + value[end:] textArea.SelectionStart, textArea.SelectionEnd = start+1, start+1 event.PreventDefault() // Trigger "input" event listeners. inputEvent := js.Global.Get("CustomEvent").New("input") textArea.Underlying().Call("dispatchEvent", inputEvent) } }) }
package u9 import ( "github.com/gopherjs/gopherjs/js" "honnef.co/go/js/dom" ) // AddTabSupport is a helper that modifies a <textarea>, so that pressing tab key will insert tabs. func AddTabSupport(textArea *dom.HTMLTextAreaElement) { textArea.AddEventListener("keydown", false, func(event dom.Event) { switch ke := event.(*dom.KeyboardEvent); { case ke.KeyCode == 9 && !ke.CtrlKey && !ke.AltKey && !ke.MetaKey && !ke.ShiftKey: // Tab. value, start, end := textArea.Value, textArea.SelectionStart, textArea.SelectionEnd textArea.Value = value[:start] + "\t" + value[end:] textArea.SelectionStart, textArea.SelectionEnd = start+1, start+1 event.PreventDefault() // Trigger "input" event listeners. inputEvent := js.Global.Get("CustomEvent").New("input") textArea.Underlying().Call("dispatchEvent", inputEvent) } }) }
Make base module default DJANGO_SETTINGS_MODULE
#!/usr/bin/env python import os import sys import re def read_env(): """Pulled from Honcho code with minor updates, reads local default environment variables from a .env file located in the project root directory. """ try: with open('.env') as f: content = f.read() except IOError: content = '' for line in content.splitlines(): m1 = re.match(r'\A([A-Za-z_0-9]+)=(.*)\Z', line) if m1: key, val = m1.group(1), m1.group(2) m2 = re.match(r"\A'(.*)'\Z", val) if m2: val = m2.group(1) m3 = re.match(r'\A"(.*)"\Z', val) if m3: val = re.sub(r'\\(.)', r'\1', m3.group(1)) os.environ.setdefault(key, val) if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "feedleap.settings.base") from django.core.management import execute_from_command_line read_env() execute_from_command_line(sys.argv)
#!/usr/bin/env python import os import sys import re def read_env(): """Pulled from Honcho code with minor updates, reads local default environment variables from a .env file located in the project root directory. """ try: with open('.env') as f: content = f.read() except IOError: content = '' for line in content.splitlines(): m1 = re.match(r'\A([A-Za-z_0-9]+)=(.*)\Z', line) if m1: key, val = m1.group(1), m1.group(2) m2 = re.match(r"\A'(.*)'\Z", val) if m2: val = m2.group(1) m3 = re.match(r'\A"(.*)"\Z', val) if m3: val = re.sub(r'\\(.)', r'\1', m3.group(1)) os.environ.setdefault(key, val) if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "feedleap.settings") from django.core.management import execute_from_command_line read_env() execute_from_command_line(sys.argv)
Allow single argument calls to methods
/* TODO: Cache individual objects, like ATTR and NTH simple selectors. Reorder pseudos so that the ones with highest overhead (like :hover) come last. */ /** @define {boolean} */ const DEBUG_MODE = false, LEGACY = false const Query = global["Query"] = {} Query["one"] = function(elem, selector) { if (arguments.length === 1) { selector = elem elem = document } return new SelectorGroup(selector).selectFirstFrom(elem) } Query["all"] = function(elem, selector) { if (arguments.length === 1) { selector = elem elem = document } return new SelectorGroup(selector).selectFrom(elem) } Query["matches"] = function(elem, selector) { if (arguments.length === 1) { selector = elem elem = document } return new SelectorGroup(selector).matches(elem) } //const e_proto = (global.HTMLElement || global.Element || {}).prototype //if (e_proto && !e_proto.matches) { // e_proto.matches = // e_proto.matchesSelector || // e_proto.webkitMatchesSelector || // e_proto.mozMatchesSelector || // e_proto.msMatchesSelector || // e_proto.oMatchesSelector || // function(sel) { // return Query["matches"](/**{!Element}*/(this), sel) // } //}
/* TODO: Cache individual objects, like ATTR and NTH simple selectors. Reorder pseudos so that the ones with highest overhead (like :hover) come last. */ /** @define {boolean} */ const DEBUG_MODE = false, LEGACY = false const Query = global["Query"] = {} Query["one"] = function(elem, selector) { return new SelectorGroup(selector).selectFirstFrom(elem) } Query["all"] = function(elem, selector) { return new SelectorGroup(selector).selectFrom(elem) } Query["matches"] = function(elem, selector) { return new SelectorGroup(selector).matches(elem) } //const e_proto = (global.HTMLElement || global.Element || {}).prototype //if (e_proto && !e_proto.matches) { // e_proto.matches = // e_proto.matchesSelector || // e_proto.webkitMatchesSelector || // e_proto.mozMatchesSelector || // e_proto.msMatchesSelector || // e_proto.oMatchesSelector || // function(sel) { // return Query["matches"](/**{!Element}*/(this), sel) // } //}
Use the actual method indices instead of unknown collections.
var ejs = require('elastic.js'), nc = require('elastic.js/elastic-node-client'); // default elasticsearch port is 9200 ejs.client = nc.NodeClient('localhost', '9200'); exports.getResults = function (req, res) { var termQuery = ejs.TermQuery('message', 'hello'), /* a function to display results */ resultsCallBack = function (results) { if (results.hits) { var hits = results.hits.hits; hits.forEach(function (hit) { console.log(hit._source.message); }); } }, /* execute the request */ r = ejs.Request() .indices('twitter') .types('tweet') .query(termQuery); r.doSearch(resultsCallBack); res.json('boom'); };
var ejs = require('elastic.js'), nc = require('elastic.js/elastic-node-client'); // default elasticsearch port is 9200 ejs.client = nc.NodeClient('localhost', '9200'); exports.getResults = function (req, res) { var termQuery = ejs.TermQuery('message', 'hello'), /* a function to display results */ resultsCallBack = function (results) { if (results.hits) { var hits = results.hits.hits; hits.forEach(function (hit) { console.log(hit._source.message); }); } }, /* execute the request */ r = ejs.Request() .collections('twitter') .types('tweet') .query(termQuery); r.doSearch(resultsCallBack); res.json('boom'); };
Use locally installed tbb if available
#!/usr/bin/env node /* Copyright 2015 Google Inc. 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. */ // This craziness basically just makes sure that imports inside experiments // are sane. When we run an experiment we do so as if the experiment were a // node module in the same location. var path = require('path'); var spawn = require('child_process').spawn; var file = process.argv[2]; if (!path.isAbsolute(file)) { file = path.join(process.cwd(), file); } process.chdir(path.dirname(file)); function run(exports, target) { var run; try { // If there's a local tree-builder-builder, use that. run = require('tree-builder-builder').run; } catch (e) { // Otherwise fall back on the one alongside this binary. run = require(exports).run; } run(target, function(name) { return require(name); }); } var exports = JSON.stringify(path.join(__dirname, 'exports.js')); var target = JSON.stringify(file); spawn('/usr/bin/env', [ 'node', '-e', '(' + String(run) + ')(' + exports + ', ' + target + ');', ], {stdio: 'inherit'});
#!/usr/bin/env node /* Copyright 2015 Google Inc. 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. */ // This craziness basically just makes sure that imports inside experiments // are sane. When we run an experiment we do so as if the experiment were a // node module in the same location. var path = require('path'); var spawn = require('child_process').spawn; var file = process.argv[2]; if (!path.isAbsolute(file)) { file = path.join(process.cwd(), file); } process.chdir(path.dirname(file)); var exports = JSON.stringify(path.join(__dirname, 'exports.js')); var target = JSON.stringify(file); spawn('/usr/bin/env', [ 'node', '-e', 'require(' + exports + ').run(' + target + ', function(name) { return require(name); });', ], {stdio: 'inherit'});
Disable Suhosin test for PHP > 5.3.9. Suhosin project is inactive right now and the latest release is for 5.3.9.
<?php /** * Skeleton Test class file for Suhosin group * * @package PhpSecInfo * @author Anthon Pang */ /** * require the main PhpSecInfo class */ require_once(PHPSECINFO_BASE_DIR.'/Test/Test.php'); /** * This is a skeleton class for PhpSecInfo "Suhosin" tests * @package PhpSecInfo */ class PhpSecInfo_Test_Suhosin extends PhpSecInfo_Test { /** * This value is used to group test results together. * * For example, all tests related to the mysql lib should be grouped under "mysql." * * @var string */ var $test_group = 'Suhosin'; /** * "Suhosin" tests should pretty much be always testable, so the default is just to return true * * @return boolean */ function isTestable() { if (version_compare(PHP_VERSION, '5.3.9') >= 0) { return false; } return true; } function getMoreInfoURL() { if ($tn = $this->getTestName()) { return 'http://www.hardened-php.net/suhosin/index.html'; } else { return false; } } }
<?php /** * Skeleton Test class file for Suhosin group * * @package PhpSecInfo * @author Anthon Pang */ /** * require the main PhpSecInfo class */ require_once(PHPSECINFO_BASE_DIR.'/Test/Test.php'); /** * This is a skeleton class for PhpSecInfo "Suhosin" tests * @package PhpSecInfo */ class PhpSecInfo_Test_Suhosin extends PhpSecInfo_Test { /** * This value is used to group test results together. * * For example, all tests related to the mysql lib should be grouped under "mysql." * * @var string */ var $test_group = 'Suhosin'; /** * "Suhosin" tests should pretty much be always testable, so the default is just to return true * * @return boolean */ function isTestable() { return true; } function getMoreInfoURL() { if ($tn = $this->getTestName()) { return 'http://www.hardened-php.net/suhosin/index.html'; } else { return false; } } }
Update path to createReducer function
import { expect } from 'chai'; import Immutable from 'immutable'; import createReducer from 'rook/lib/redux/createReducer'; import reducers from '../modules'; const reducer = createReducer(reducers.random); describe('redux', () => { describe('reducers', () => { describe('random', () => { const initialState = Immutable.fromJS({}); it('handles loadOk', () => { const curDate = new Date().toString(); const newState = reducer(initialState, { type: 'random/loadOk', result: { number: 0.5, time: curDate } }); expect(newState.toJS()).to.deep.equal({ number: 0.5, time: curDate }); }); }); }); });
import { expect } from 'chai'; import Immutable from 'immutable'; import { createReducer } from 'rook/lib/redux/createStore'; import reducers from '../modules'; const reducer = createReducer(reducers.random); describe('redux', () => { describe('reducers', () => { describe('random', () => { const initialState = Immutable.fromJS({}); it('handles loadOk', () => { const curDate = new Date().toString(); const newState = reducer(initialState, { type: 'random/loadOk', result: { number: 0.5, time: curDate } }); expect(newState.toJS()).to.deep.equal({ number: 0.5, time: curDate }); }); }); }); });
Support for default values in constructor added
<?php namespace Kutny\AutowiringBundle\Compiler; use ReflectionMethod; use Symfony\Component\DependencyInjection\Definition; class ClassConstructorFiller { private $parameterProcessor; public function __construct(ParameterProcessor $parameterProcessor) { $this->parameterProcessor = $parameterProcessor; } public function autowireParams(ReflectionMethod $constructor, Definition $definition, array $classes) { $explicitlyDefinedArguments = $definition->getArguments(); $allArguments = array(); foreach ($constructor->getParameters() as $index => $parameter) { if (array_key_exists($index, $explicitlyDefinedArguments)) { $allArguments[] = $explicitlyDefinedArguments[$index]; } else if ($parameter->isDefaultValueAvailable()) { $allArguments[] = $parameter->getDefaultValue(); } else { $allArguments[] = $this->parameterProcessor->getParameterValue($parameter, $classes); } } $definition->setArguments($allArguments); } }
<?php namespace Kutny\AutowiringBundle\Compiler; use ReflectionMethod; use Symfony\Component\DependencyInjection\Definition; class ClassConstructorFiller { private $parameterProcessor; public function __construct(ParameterProcessor $parameterProcessor) { $this->parameterProcessor = $parameterProcessor; } public function autowireParams(ReflectionMethod $constructor, Definition $definition, array $classes) { $explicitlyDefinedArguments = $definition->getArguments(); $allArguments = array(); foreach ($constructor->getParameters() as $index => $parameter) { if (array_key_exists($index, $explicitlyDefinedArguments)) { $allArguments[] = $explicitlyDefinedArguments[$index]; } else { $allArguments[] = $this->parameterProcessor->getParameterValue($parameter, $classes); } } $definition->setArguments($allArguments); } }
Change how the base_url is turned into a domain
from importlib import import_module from django.contrib.auth import SESSION_KEY, BACKEND_SESSION_KEY, HASH_SESSION_KEY def force_login(user, driver, base_url): from django.conf import settings SessionStore = import_module(settings.SESSION_ENGINE).SessionStore selenium_login_start_page = getattr(settings, 'SELENIUM_LOGIN_START_PAGE', '/page_404/') driver.get('{}{}'.format(base_url, selenium_login_start_page)) session = SessionStore() session[SESSION_KEY] = user.id session[BACKEND_SESSION_KEY] = settings.AUTHENTICATION_BACKENDS[0] session[HASH_SESSION_KEY] = user.get_session_auth_hash() session.save() domain = base_url.rpartition('://')[2].split('/')[0].split(':')[0] cookie = { 'name': settings.SESSION_COOKIE_NAME, 'value': session.session_key, 'path': '/', 'domain': domain } driver.add_cookie(cookie) driver.refresh()
from importlib import import_module from django.contrib.auth import SESSION_KEY, BACKEND_SESSION_KEY, HASH_SESSION_KEY def force_login(user, driver, base_url): from django.conf import settings SessionStore = import_module(settings.SESSION_ENGINE).SessionStore selenium_login_start_page = getattr(settings, 'SELENIUM_LOGIN_START_PAGE', '/page_404/') driver.get('{}{}'.format(base_url, selenium_login_start_page)) session = SessionStore() session[SESSION_KEY] = user.id session[BACKEND_SESSION_KEY] = settings.AUTHENTICATION_BACKENDS[0] session[HASH_SESSION_KEY] = user.get_session_auth_hash() session.save() domain = base_url.split(':')[-2].split('/')[-1] cookie = { 'name': settings.SESSION_COOKIE_NAME, 'value': session.session_key, 'path': '/', 'domain': domain } driver.add_cookie(cookie) driver.refresh()
Fix bug when animate body get wrong height.
$(window).ready(function(){ $("#config_button").unbind().click(function(){ if($("#config_button").data('switch_flag')=='open') { $("#config_container").animate({height:"0px"},500); $("body").animate({height:"134px"},500); $("#config_button").data('switch_flag','close'); }else{ $("#config_container").animate({height:"100px"},500); $("body").animate({height:"234px"},500); $("#config_button").data('switch_flag','open'); } }); $("#config_decimal_places").change(function(){ TMSGCCW.data("decimalPlaces", parseInt(config_decimal_places.value));TMSGCCW.saveSettings();TMSGCCW.startConvert(); }); $("#config_decimal_complemented_with_zero").change(function(){ TMSGCCW.data("decimalComplementedWithZero", config_decimal_complemented_with_zero.checked);TMSGCCW.saveSettings();TMSGCCW.startConvert(); }); $("#config_font_family").change(function(){ TMSGCCW.data("fontFamily", config_font_family.value);TMSGCCW.saveSettings(); $("body").css("font-family",TMSGCCW.data("fontFamily")); }); });
$(window).ready(function(){ $("#config_button").unbind().click(function(){ if($("#config_button").data('switch_flag')=='open') { $("#config_container").animate({height:"0px"},500); $("body").animate({height:"0px"},500); $("#config_button").data('switch_flag','close'); }else{ $("#config_container").animate({height:"100px"},500); $("#config_button").data('switch_flag','open'); } }); $("#config_decimal_places").change(function(){ TMSGCCW.data("decimalPlaces", parseInt(config_decimal_places.value));TMSGCCW.saveSettings();TMSGCCW.startConvert(); }); $("#config_decimal_complemented_with_zero").change(function(){ TMSGCCW.data("decimalComplementedWithZero", config_decimal_complemented_with_zero.checked);TMSGCCW.saveSettings();TMSGCCW.startConvert(); }); $("#config_font_family").change(function(){ TMSGCCW.data("fontFamily", config_font_family.value);TMSGCCW.saveSettings(); $("body").css("font-family",TMSGCCW.data("fontFamily")); }); });
Remove encoding which is breaking forward slash `/` in URL constructions
/** * Copyright 2015 The AMP HTML 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. */ import {checkData, validateDataExists, writeScript} from '../src/3p'; /** * @param {!Window} global * @param {!Object} data */ export function openadstream(global, data) { //all available fields checkData(data, ['adhost', 'sitepage', 'pos', 'query']); //required fields validateDataExists(data, ['adhost', 'sitepage', 'pos']); let url = 'https://' + encodeURIComponent(data.adhost) + '/3/' + data.sitepage + '/1' + String(Math.random()).substring(2, 11) + '@' + data.pos; if (data.query) { url = url + '?' + data.query; } writeScript(global, url); }
/** * Copyright 2015 The AMP HTML 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. */ import {checkData, validateDataExists, writeScript} from '../src/3p'; /** * @param {!Window} global * @param {!Object} data */ export function openadstream(global, data) { //all available fields checkData(data, ['adhost', 'sitepage', 'pos', 'query']); //required fields validateDataExists(data, ['adhost', 'sitepage', 'pos']); let url = 'https://' + encodeURIComponent(data.adhost) + '/3/' + encodeURIComponent(data.sitepage) + '/1' + new String(Math.random()).substring(2, 11) + '@' + data.pos; if (data.query) { url = url + '?' + data.query; } writeScript(global, url); }
Update instead of overriding `DATABASES` setting in `test` settings.
from ._base import * # DJANGO ###################################################################### DATABASE_NAME = 'test_%s' % DATABASES['default']['NAME'] DATABASES['default'].update({ 'NAME': DATABASE_NAME, 'TEST': { 'NAME': DATABASE_NAME, # See: https://docs.djangoproject.com/en/1.7/ref/settings/#serialize 'SERIALIZE': False, }, }) INSTALLED_APPS += ('icekit.tests', ) TEMPLATES_DJANGO['DIRS'].insert( 0, os.path.join(BASE_DIR, 'icekit', 'tests', 'templates')), # ICEKIT ###################################################################### # RESPONSE_PAGE_PLUGINS = ['ImagePlugin', ] # HAYSTACK #################################################################### # HAYSTACK_CONNECTIONS = { # 'default': { # 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', # }, # } # TRAVIS ###################################################################### if 'TRAVIS' in os.environ: NOSE_ARGS.remove('--with-progressive')
from ._base import * # DJANGO ###################################################################### DATABASE_NAME = 'test_%s' % DATABASES['default']['NAME'] DATABASES = { 'default': { 'NAME': DATABASE_NAME, 'TEST': { 'NAME': DATABASE_NAME, # See: https://docs.djangoproject.com/en/1.7/ref/settings/#serialize 'SERIALIZE': False, }, } } INSTALLED_APPS += ('icekit.tests', ) TEMPLATES_DJANGO['DIRS'].insert( 0, os.path.join(BASE_DIR, 'icekit', 'tests', 'templates')), # ICEKIT ###################################################################### # RESPONSE_PAGE_PLUGINS = ['ImagePlugin', ] # HAYSTACK #################################################################### # HAYSTACK_CONNECTIONS = { # 'default': { # 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', # }, # } # TRAVIS ###################################################################### if 'TRAVIS' in os.environ: NOSE_ARGS.remove('--with-progressive')
Use json instead of django.utils.simplejson.
import json from django import template from javascript_settings.configuration_builder import \ DEFAULT_CONFIGURATION_BUILDER register = template.Library() @register.tag(name='javascript_settings') def do_javascript_settings(parser, token): """ Returns a node with generated configuration. """ return JavascriptConfigurationNode() class JavascriptConfigurationNode(template.Node): """ Represents a node that renders JavaScript configuration. """ def __init__(self): pass def render(self, context): """ Renders JS configuration. """ return 'var configuration = ' + json.dumps( DEFAULT_CONFIGURATION_BUILDER.get_configuration() ) + ';'
from django import template from django.utils import simplejson from javascript_settings.configuration_builder import \ DEFAULT_CONFIGURATION_BUILDER register = template.Library() @register.tag(name='javascript_settings') def do_javascript_settings(parser, token): """ Returns a node with generated configuration. """ return JavascriptConfigurationNode() class JavascriptConfigurationNode(template.Node): """ Represents a node that renders JavaScript configuration. """ def __init__(self): pass def render(self, context): """ Renders JS configuration. """ return 'var configuration = ' + simplejson.dumps( DEFAULT_CONFIGURATION_BUILDER.get_configuration() ) + ';'
Set GAS_ESTIMATE_MULTIPLIER to 1.25 (seems to prevent tx failure)
"use strict"; var BigNumber = require("bignumber.js"); BigNumber.config({ MODULO_MODE: BigNumber.EUCLID, ROUNDING_MODE: BigNumber.ROUND_HALF_DOWN }); module.exports = { ACCOUNT_TYPES: { U_PORT: "uPort", LEDGER: "ledger", PRIVATE_KEY: "privateKey", UNLOCKED_ETHEREUM_NODE: "unlockedEthereumNode", META_MASK: "metaMask", TREZOR: "trezor", }, // Number of required confirmations for transact sequence REQUIRED_CONFIRMATIONS: 0, // Maximum number of retry attempts for dropped transactions TX_RETRY_MAX: 5, // Maximum number of transaction verification attempts TX_POLL_MAX: 1000, // Transaction polling interval TX_POLL_INTERVAL: 10000, // how frequently to poll when waiting for blocks BLOCK_POLL_INTERVAL: 30000, GAS_ESTIMATE_MULTIPLIER: new BigNumber("1.25", 10), // TODO adjust this empirically DEFAULT_ETH_CALL_GAS: "0x5d1420", ETHER: new BigNumber(10, 10).exponentiatedBy(18), };
"use strict"; var BigNumber = require("bignumber.js"); BigNumber.config({ MODULO_MODE: BigNumber.EUCLID, ROUNDING_MODE: BigNumber.ROUND_HALF_DOWN }); module.exports = { ACCOUNT_TYPES: { U_PORT: "uPort", LEDGER: "ledger", PRIVATE_KEY: "privateKey", UNLOCKED_ETHEREUM_NODE: "unlockedEthereumNode", META_MASK: "metaMask", TREZOR: "trezor", }, // Number of required confirmations for transact sequence REQUIRED_CONFIRMATIONS: 0, // Maximum number of retry attempts for dropped transactions TX_RETRY_MAX: 5, // Maximum number of transaction verification attempts TX_POLL_MAX: 1000, // Transaction polling interval TX_POLL_INTERVAL: 10000, // how frequently to poll when waiting for blocks BLOCK_POLL_INTERVAL: 30000, GAS_ESTIMATE_MULTIPLIER: new BigNumber("1.1", 10), // TODO adjust this empirically DEFAULT_ETH_CALL_GAS: "0x5d1420", ETHER: new BigNumber(10, 10).exponentiatedBy(18), };
Add comment for code clarity
// This file makes all join table relationships var Sequelize = require('sequelize'); var sequelize = new Sequelize('escape', 'escape', 'escapeacft', { dialect: 'mariadb', host: 'localhost' }); // Any vairable that starts with a capital letter is a model var User = require('./users.js')(sequelize, Sequelize); var Bookmark = require('./bookmarks.js')(sequelize, Sequelize); var BookmarkUsers = require('./bookmarkUsers')(sequelize, Sequelize); // BookmarkUsers join table: User.belongsToMany(Bookmark, { through: 'bookmark_users', foreignKey: 'user_id' }); Bookmark.belongsToMany(User, { through: 'bookmark_users', foreignKey: 'bookmark_id' }); //Create missing tables, if any // sequelize.sync({force: true}); sequelize.sync(); exports.User = User; exports.Bookmark = Bookmark; exports.BookmarkUsers = BookmarkUsers;
// This file makes all join table relationships var Sequelize = require('sequelize'); var sequelize = new Sequelize('escape', 'escape', 'escapeacft', { dialect: 'mariadb', host: 'localhost' }); // Any vairable that starts with a capital letter is a model var User = require('./users.js')(sequelize, Sequelize); var Bookmark = require('./bookmarks.js')(sequelize, Sequelize); var BookmarkUsers = require('./bookmarkUsers')(sequelize, Sequelize); // BookmarkUsers join table: User.belongsToMany(Bookmark, { through: 'bookmark_users', foreignKey: 'user_id' }); Bookmark.belongsToMany(User, { through: 'bookmark_users', foreignKey: 'bookmark_id' }); // sequelize.sync({force: true}); sequelize.sync(); exports.User = User; exports.Bookmark = Bookmark; exports.BookmarkUsers = BookmarkUsers;
Add packageType to the list of flags android builds understand and can parse This allows corber to perform bundle/aap builds for android https://github.com/apache/cordova-android/pull/764
const _pick = require('lodash').pick; const CORDOVA_OPTS = [ 'release', 'debug', 'emulator', 'device', 'buildConfig' ]; const IOS_OPTS = [ 'codeSignIdentity', 'provisioningProfile', 'codesignResourceRules', 'developmentTeam', 'packageType' ]; const ANDROID_OPTS = [ 'keystore', 'storePassword', 'alias', 'password', 'keystoreType', 'gradleArg', 'cdvBuildMultipleApks', 'cdvVersionCode', 'cdvReleaseSigningPropertiesFile', 'cdvDebugSigningPropertiesFile', 'cdvMinSdkVersion', 'cdvBuildToolsVersion', 'cdvCompileSdkVersion', 'packageType' ]; module.exports = function(platform, options) { let platformKeys = []; if (platform === 'ios') { platformKeys = IOS_OPTS; } else if (platform === 'android') { platformKeys = ANDROID_OPTS; } let ret = _pick(options, CORDOVA_OPTS.concat(platformKeys)); ret.argv = [].concat(...platformKeys .filter((key) => options.hasOwnProperty(key)) .map((key) => [`--${key}`, options[key]])); return ret; };
const _pick = require('lodash').pick; const CORDOVA_OPTS = [ 'release', 'debug', 'emulator', 'device', 'buildConfig' ]; const IOS_OPTS = [ 'codeSignIdentity', 'provisioningProfile', 'codesignResourceRules', 'developmentTeam', 'packageType' ]; const ANDROID_OPTS = [ 'keystore', 'storePassword', 'alias', 'password', 'keystoreType', 'gradleArg', 'cdvBuildMultipleApks', 'cdvVersionCode', 'cdvReleaseSigningPropertiesFile', 'cdvDebugSigningPropertiesFile', 'cdvMinSdkVersion', 'cdvBuildToolsVersion', 'cdvCompileSdkVersion' ]; module.exports = function(platform, options) { let platformKeys = []; if (platform === 'ios') { platformKeys = IOS_OPTS; } else if (platform === 'android') { platformKeys = ANDROID_OPTS; } let ret = _pick(options, CORDOVA_OPTS.concat(platformKeys)); ret.argv = [].concat(...platformKeys .filter((key) => options.hasOwnProperty(key)) .map((key) => [`--${key}`, options[key]])); return ret; };
[Android] Fix uiautomator test runner after r206096 TBR=craigdh@chromium.org NOTRY=True BUG= Review URL: https://chromiumcodereview.appspot.com/17004003 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@206257 0039d316-1c4b-4281-b951-d872f2087c98
# Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Class for running uiautomator tests on a single device.""" from pylib.instrumentation import test_runner as instr_test_runner class TestRunner(instr_test_runner.TestRunner): """Responsible for running a series of tests connected to a single device.""" def __init__(self, options, device, shard_index, test_pkg, ports_to_forward): """Create a new TestRunner. Args: options: An options object similar to the one in parent class plus: - package_name: Application package name under test. """ options.ensure_value('install_apk', True) options.ensure_value('wait_for_debugger', False) super(TestRunner, self).__init__( options, device, shard_index, test_pkg, ports_to_forward) self.package_name = options.package_name #override def InstallTestPackage(self): self.test_pkg.Install(self.adb) #override def PushDataDeps(self): pass #override def _RunTest(self, test, timeout): self.adb.ClearApplicationState(self.package_name) if 'Feature:FirstRunExperience' in self.test_pkg.GetTestAnnotations(test): self.flags.RemoveFlags(['--disable-fre']) else: self.flags.AddFlags(['--disable-fre']) return self.adb.RunUIAutomatorTest( test, self.test_pkg.GetPackageName(), timeout)
# Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Class for running uiautomator tests on a single device.""" from pylib.instrumentation import test_runner as instr_test_runner class TestRunner(instr_test_runner.TestRunner): """Responsible for running a series of tests connected to a single device.""" def __init__(self, options, device, shard_index, test_pkg, ports_to_forward): """Create a new TestRunner. Args: options: An options object similar to the one in parent class plus: - package_name: Application package name under test. """ options.ensure_value('install_apk', True) options.ensure_value('wait_for_debugger', False) super(TestRunner, self).__init__( options, device, shard_index, test_pkg, ports_to_forward) self.package_name = options.package_name #override def InstallTestPackage(self): self.test_pkg.Install(self.adb) #override def _RunTest(self, test, timeout): self.adb.ClearApplicationState(self.package_name) if 'Feature:FirstRunExperience' in self.test_pkg.GetTestAnnotations(test): self.flags.RemoveFlags(['--disable-fre']) else: self.flags.AddFlags(['--disable-fre']) return self.adb.RunUIAutomatorTest( test, self.test_pkg.GetPackageName(), timeout)
Remove broken workaround code for old mock. Mock <= 1.0.1 was indeed broken on 3.4, but unittest.mock from 3.4 is just as (or more) broken. Mock is now fixed, so don't play games with the global state of the import system. Change-Id: I5e04b773d33c63d5cf06ff60c321de70de453b69 Closes-Bug: #1488252 Partial-Bug: #1463867
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # 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. """ :mod:`Ironic.tests` -- ironic Unittests ===================================================== .. automodule:: ironic.tests :platform: Unix """ # TODO(deva): move eventlet imports to ironic.__init__ once we move to PBR import eventlet eventlet.monkey_patch(os=False) # See http://code.google.com/p/python-nose/issues/detail?id=373 # The code below enables nosetests to work with i18n _() blocks import six.moves.builtins as __builtin__ setattr(__builtin__, '_', lambda x: x)
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # 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. """ :mod:`Ironic.tests` -- ironic Unittests ===================================================== .. automodule:: ironic.tests :platform: Unix """ # TODO(deva): move eventlet imports to ironic.__init__ once we move to PBR import eventlet eventlet.monkey_patch(os=False) # See http://code.google.com/p/python-nose/issues/detail?id=373 # The code below enables nosetests to work with i18n _() blocks import six.moves.builtins as __builtin__ setattr(__builtin__, '_', lambda x: x) # NOTE(viktors): We can't use mock as third-party library in python 3.4 because # of bug https://code.google.com/p/mock/issues/detail?id=234 # so let's use mock from standard library in python 3.x import six if six.PY3: import sys import unittest.mock sys.modules['mock'] = unittest.mock
Remove input pattern test as it is not being used
/* * ADR Reporting * Copyright (C) 2017 Divay Prakash * GNU Affero General Public License 3.0 (https://github.com/divayprakash/adr/blob/master/LICENSE) */ var dataUriTest; Modernizr.on('datauri', function(result) { dataUriTest = result.valueOf() && result.over32kb; var formValidationTest = Modernizr.formvalidation; var hiddenTest = Modernizr.hidden; var inputTest = Modernizr.input.max && Modernizr.input.min && Modernizr.input.placeholder && Modernizr.input.required && Modernizr.input.step; var inputTypesTest = Modernizr.inputtypes.date && Modernizr.inputtypes.email && Modernizr.inputtypes.number && Modernizr.inputtypes.range && Modernizr.inputtypes.tel; var mediaQueriesTest = Modernizr.mediaqueries; var placeholderTest = Modernizr.placeholder; var totalTest = dataUriTest && formValidationTest && hiddenTest && inputTest && inputTypesTest && mediaQueriesTest && placeholderTest; if (totalTest) document.getElementById('warning').style.display = 'none'; else document.getElementById('main-div').style.display = 'none'; });
/* * ADR Reporting * Copyright (C) 2017 Divay Prakash * GNU Affero General Public License 3.0 (https://github.com/divayprakash/adr/blob/master/LICENSE) */ var dataUriTest; Modernizr.on('datauri', function(result) { dataUriTest = result.valueOf() && result.over32kb; var formValidationTest = Modernizr.formvalidation; var hiddenTest = Modernizr.hidden; var inputTest = Modernizr.input.max && Modernizr.input.min && Modernizr.input.pattern && Modernizr.input.placeholder && Modernizr.input.required && Modernizr.input.step; var inputTypesTest = Modernizr.inputtypes.date && Modernizr.inputtypes.email && Modernizr.inputtypes.number && Modernizr.inputtypes.range && Modernizr.inputtypes.tel; var mediaQueriesTest = Modernizr.mediaqueries; var placeholderTest = Modernizr.placeholder; var totalTest = dataUriTest && formValidationTest && hiddenTest && inputTest && inputTypesTest && mediaQueriesTest && placeholderTest; if (totalTest) document.getElementById('warning').style.display = 'none'; else document.getElementById('main-div').style.display = 'none'; });
Clean up old echoes stuff and correct tags/:id 404 code. Signed-off-by: Shai Sachs <47bd79f9420edf5d0991d1e2710179d4e040d480@ngpvan.com>
var config = require('../config'), request = require('request'); function getActivistCode(apiKey, dbMode, id, unauthorized, badRequest, success) { var options = { method: 'GET', url: config.get('vanEndpoint') + 'activistCodes/' + id, headers: { 'Content-Type': 'application/json' }, auth: { user: 'api', pass: apiKey + '|' + dbMode, sendImmediately: false } }; request(options, function(error, response, body) { if (error) { return badRequest(error); } else if (response.statusCode == 200) { return success(body); } else if (response.statusCode == 404) { return success({}); } else if (response.statusCode == 401) { return unauthorized(); } }); } module.exports = { getActivistCode: getActivistCode };
var config = require('../config'), request = require('request'); var vanEndpoint = 'https://api.securevan.com/v4'; function echo(apiKey, message, success, failedAuth, catchErr) { var url = vanEndpoint + '/echoes/' + message; request(url, function(error, response, body) { if (error) { return catchErr(error); } if (response.statusCode == 401) { return failedAuth(); } if (response.statusCode == 200) { return success(body.message); } }); } function getActivistCode(apiKey, dbMode, id, unauthorized, badRequest, success) { var options = { method: 'GET', url: config.get('vanEndpoint') + 'activistCodes/' + id, headers: { 'Content-Type': 'application/json' }, auth: { user: 'api', pass: apiKey + '|' + dbMode, sendImmediately: false } }; request(options, function(error, response, body) { if (error) { return badRequest(error); } else if (response.statusCode == 200) { return success(body); } else if (response.statusCode == 404) { return success({}); } else if (response.statusCode == 401) { return unauthorized(); } }); } module.exports = { getActivistCode: getActivistCode };
Exclude handling of the situation where Pillow is not available from test coverage.
""" Import the required subclasses of :class:`~qrcode.image.base.BaseImage` from the qrcode library with a fallback to SVG format when the Pillow library is not available. """ import logging from qrcode.image.svg import SvgPathImage as _SvgPathImage logger = logging.getLogger('django') try: from qrcode.image.pil import PilImage as _PilImageOrFallback except ImportError: # pragma: no cover logger.info("Pillow is not installed. No support available for PNG format.") from qrcode.image.svg import SvgPathImage as _PilImageOrFallback SVG_FORMAT_NAME = 'svg' PNG_FORMAT_NAME = 'png' SvgPathImage = _SvgPathImage PilImageOrFallback = _PilImageOrFallback def has_png_support(): return PilImageOrFallback is not SvgPathImage def get_supported_image_format(image_format): image_format = image_format.lower() if image_format not in [SVG_FORMAT_NAME, PNG_FORMAT_NAME]: logger.warning('Unknown image format: %s' % image_format) image_format = SVG_FORMAT_NAME elif image_format == PNG_FORMAT_NAME and not has_png_support(): logger.warning( "No support available for PNG format, SVG will be used instead. Please install Pillow for PNG support.") image_format = SVG_FORMAT_NAME return image_format
""" Import the required subclasses of :class:`~qrcode.image.base.BaseImage` from the qrcode library with a fallback to SVG format when the Pillow library is not available. """ import logging from qrcode.image.svg import SvgPathImage as _SvgPathImage logger = logging.getLogger('django') try: from qrcode.image.pil import PilImage as _PilImageOrFallback except ImportError: logger.info("Pillow is not installed. No support available for PNG format.") from qrcode.image.svg import SvgPathImage as _PilImageOrFallback SVG_FORMAT_NAME = 'svg' PNG_FORMAT_NAME = 'png' SvgPathImage = _SvgPathImage PilImageOrFallback = _PilImageOrFallback def has_png_support(): return PilImageOrFallback is not SvgPathImage def get_supported_image_format(image_format): image_format = image_format.lower() if image_format not in [SVG_FORMAT_NAME, PNG_FORMAT_NAME]: logger.warning('Unknown image format: %s' % image_format) image_format = SVG_FORMAT_NAME elif image_format == PNG_FORMAT_NAME and not has_png_support(): logger.warning("No support available for PNG format, SVG will be used instead. Please install Pillow for PNG support.") image_format = SVG_FORMAT_NAME return image_format
Implement helper method to determine if year is leap year
<?php declare(strict_types = 1); /** * This file is part of the jordanbrauer/unit-converter PHP package. * * @copyright 2018 Jordan Brauer <jbrauer.inc@gmail.com> * @license MIT * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace UnitConverter\Unit\Time; /** * Year unit data class. * * @version 2.0.0 * @since 0.3.9 * @author Teun Willems */ class Year extends TimeUnit { protected function configure (): void { $this ->setName("year") ->setSymbol("y") ->setUnits(31536000) ; } /** * Determines if the given (or current, if non supplied) year is a leap year. * * @param integer $year The year being checked. * @return boolean */ public static function isLeapYear (int $year = null): bool { $year = ($year ?? date('Y')); return ( (0 == ($year % 4)) && ((0 != ($year % 100)) XOR (0 == ($year % 400))) ); } }
<?php declare(strict_types = 1); /** * This file is part of the jordanbrauer/unit-converter PHP package. * * @copyright 2018 Jordan Brauer <jbrauer.inc@gmail.com> * @license MIT * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace UnitConverter\Unit\Time; /** * Year unit data class. * * @version 2.0.0 * @since 0.3.9 * @author Teun Willems */ class Year extends TimeUnit { protected function configure (): void { $this ->setName("year") ->setSymbol("y") ->setUnits(31536000) ; } }
Add then callback to render search-results template
var Recipe = function(data){ this.title = data.Title; this.stars = data.StarRating; this.imageUrl = data.ImageURL } function BigOvenRecipeSearchJson(query) { var allRecipes = []; var noImageLink = "http://redirect.bigoven.com/pics/recipe-no-image.jpg" var apiKey = "dvx7zJ0x53M8X5U4nOh6CMGpB3d0PEhH"; var titleKeyword = query; var url = "https://api.bigoven.com/recipes?pg=1&rpp=25&title_kw=" + titleKeyword + "&api_key="+apiKey; $.ajax({ type: "GET", dataType: 'json', cache: false, url: url }).then(function(data){ for(i = 0; i < data.Results.length; i ++) { allRecipes.push(new Recipe(data.Results[i])); }; return allRecipes }).then(function(recipes){ var template = $('#search-results').html(); var output = Mustache.render(template, {recipes: recipes}); $('#results').append(output); }) }; $(document).ready(function(){ BigOvenRecipeSearchJson('cookies'); });
var Recipe = function(data){ this.title = data.Title; this.stars = data.StarRating; this.imageUrl = data.ImageURL } function BigOvenRecipeSearchJson(query) { var allRecipes = []; var noImageLink = "http://redirect.bigoven.com/pics/recipe-no-image.jpg" var apiKey = APIKEY; var titleKeyword = query; var url = "https://api.bigoven.com/recipes?pg=1&rpp=25&title_kw=" + titleKeyword + "&api_key="+apiKey; $.ajax({ type: "GET", dataType: 'json', cache: false, url: url }).then(function(data){ for(i = 0; i < data.Results.length; i ++) { allRecipes.push(new Recipe(data.Results[i])); }; return allRecipes }).then(function(recipes){ // render allRecipes here }) }; $(document).ready(function(){ var bigOvenSearch = BigOvenRecipeSearchJson('cookies'); });
Enable Dictionaries or Lists to create the Machine
class StateMachine(object): def __init__(self,RequiredStates,InitialState=0): if type(RequiredStates) is dict: self.States = RequiredStates self.StateCodes = dict([(code,state) for state,code in RequiredStates.iteritems()]) # This is done for speed of the rest of the class elif type(RequiredStates) is list: self.States = dict([(code,state) for code,state in enumerate(RequiredStates)]) self.StateCodes = dict([(state,code) for code,state in enumerate(RequiredStates)]) self.SwitchTo(InitialState) for StateCodes,States in self.States.iteritems(): setattr(StateMachine,States,StateCodes) def SwitchTo(self,NewState): if type(NewState) is int: self.CurrentCode = NewState else: self.CurrentCode = self.StateCodes[NewState] def CurrentState(self): return self.States[self.CurrentCode] def __eq__(self,other): return self.CurrentCode == other SM = StateMachine(['A','B'])
class StateMachine(object): def __init__(self,RequiredStates,InitialState=0): self.States = RequiredStates self.StateCodes = dict([(v,k) for k,v in RequiredStates.iteritems()]) # This is done for speed of the rest of the class self.SwitchTo(InitialState) for StateCodes,States in self.States.iteritems(): setattr(StateMachine,States,StateCodes) def SwitchTo(self,NewState): if type(NewState) is int: self.CurrentCode = NewState else: self.CurrentCode = self.StateCodes[NewState] def CurrentState(self): return self.States[self.CurrentCode] def __eq__(self,other): return self.CurrentCode == other
Normalize the variance to 1.0 (from 0.5)
package am.app.mappingEngine.qualityEvaluation.metrics.ufl; import java.util.List; import am.app.mappingEngine.AbstractMatcher.alignType; import am.app.mappingEngine.qualityEvaluation.AbstractQualityMetric; import am.app.mappingEngine.similarityMatrix.SimilarityMatrix; import static am.evaluation.disagreement.variance.VarianceComputation.computeVariance; /** * Compute the disagreement between matching algorithms given their individual * similarity matrices. The constructor takes only one kind of matrix, either * the classes matrices or the properties matrices. You must instantiate a * separate object for each type of matrices. * * @author <a href="http://cstroe.com">Cosmin Stroe</a> * */ public class VarianceMatcherDisagreement extends AbstractQualityMetric { private SimilarityMatrix[] matrices; public VarianceMatcherDisagreement(List<SimilarityMatrix> matrices) { super(); this.matrices = matrices.toArray(new SimilarityMatrix[0]); } /** * @param type * This parameter is ignored. */ @Override public double getQuality(alignType type, int i, int j) { // create signature vector double[] signatureVector = new double[matrices.length]; for(int k = 0; k < matrices.length; k++) { signatureVector[k] = matrices[k].getSimilarity(i, j); } // return the computed variance // because variance of similarity values can be a maximum of 0.5, we // multiply by 2 to get a metric from 0 to 1.0 return 2 * computeVariance(signatureVector); } }
package am.app.mappingEngine.qualityEvaluation.metrics.ufl; import java.util.List; import am.app.mappingEngine.AbstractMatcher.alignType; import am.app.mappingEngine.qualityEvaluation.AbstractQualityMetric; import am.app.mappingEngine.similarityMatrix.SimilarityMatrix; import static am.evaluation.disagreement.variance.VarianceComputation.computeVariance; /** * Compute the disagreement between matching algorithms given their individual * similarity matrices. The constructor takes only one kind of matrix, either * the classes matrices or the properties matrices. You must instantiate a * separate object for each type of matrices. * * @author <a href="http://cstroe.com">Cosmin Stroe</a> * */ public class VarianceMatcherDisagreement extends AbstractQualityMetric { private SimilarityMatrix[] matrices; public VarianceMatcherDisagreement(List<SimilarityMatrix> matrices) { super(); this.matrices = matrices.toArray(new SimilarityMatrix[0]); } /** * @param type * This parameter is ignored. */ @Override public double getQuality(alignType type, int i, int j) { // create signature vector double[] signatureVector = new double[matrices.length]; for(int k = 0; k < matrices.length; k++) { signatureVector[k] = matrices[k].getSimilarity(i, j); } // return the computed variance return computeVariance(signatureVector); } }
Fix missing AppSectionsPass in Bundle
<?php /* * This file is part of the Park-Manager AppSectioningBundle package. * * (c) Sebastiaan Stok <s.stok@rollerscapes.net> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace ParkManager\Bundle\AppSectioning; use ParkManager\Bundle\AppSectioning\DependencyInjection\AppSectionExtension; use ParkManager\Bundle\AppSectioning\DependencyInjection\Compiler\AppSectionsPass; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\HttpKernel\Bundle\Bundle; class ParkManagerAppSectioningBundle extends Bundle { public function build(ContainerBuilder $container) { $container->addCompilerPass(new AppSectionsPass()); } public function getContainerExtension() { if (null === $this->extension) { $this->extension = new AppSectionExtension(); } return $this->extension; } protected function getContainerExtensionClass() { return AppSectionExtension::class; } }
<?php /* * This file is part of the Park-Manager AppSectioningBundle package. * * (c) Sebastiaan Stok <s.stok@rollerscapes.net> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace ParkManager\Bundle\AppSectioning; use ParkManager\Bundle\AppSectioning\DependencyInjection\AppSectionExtension; use Symfony\Component\HttpKernel\Bundle\Bundle; class ParkManagerAppSectioningBundle extends Bundle { public function getContainerExtension() { if (null === $this->extension) { $this->extension = new AppSectionExtension(); } return $this->extension; } protected function getContainerExtensionClass() { return AppSectionExtension::class; } }
Implement the Response's 'encode(...)' and 'decode(...)' Functions Implement 'encode(...)' and 'decode(...)' functions for the the response.
/** * @flow */ type ResData = { newStates: {[key: string]: string} }; /** * Encode the updated states, to send to the client. * * @param updatedStates {StatesObject} The updated states * @param encodeState {(string, any) => string} A function that will encode the state, of a given store, to be * passed over an HTTP request * * @return {ResData} The data to respond to the client with */ export function encode(updatedStates: StatesObject, encodeState: EncodeStateFunc): ResData { const newStates = {}; for(let storeName in updatedStates) { const updatedState = updatedStates[storeName]; newStates[storeName] = encodeState(storeName, updatedState); } return { newStates }; } /** * Decode the states from the server. * * @param response {ResData} The response form the server * @param decodeState {(string, string) => any} A function that will decode the state of a given store * * @return {StatesObject} The updated states */ export function decode(response: ResData, decodeState: DecodeStateFunc): StatesObject { const { newStates } = response; const updatedStates = {}; for(let storeName in newStates) { const newState = newStates[storeName]; updatedStates[storeName] = decodeState(storeName, newState); } return updatedStates; }
/** * @flow */ type ResData = { newStates: {[key: string]: string} }; /** * Encode the updated states, to send to the client. * * @param updatedStates {StatesObject} The updated states * @param encodeState {(string, any) => string} A function that will encode the state, of a given store, to be * passed over an HTTP request * * @return {ResData} The data to respond to the client with */ export function encode(updatedStates: StatesObject, encodeState: EncodeStateFunc): ResData { //TODO return {}; } /** * Decode the states from the server. * * @param response {ResData} The response form the server * @param decodeState {(string, string) => any} A function that will decode the state of a given store * * @return {StatesObject} The updated states */ export function decode(response: ResData, decodeState: DecodeStateFunc): StatesObject { //TODO return {}; }
Switch to using cURL to fetch data Toward #72.
<?php function get_content($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_URL, $URL); $data = curl_exec($ch); curl_close($ch); return $data; } /* * If no business ID has been passed in the URL */ if (!isset($_GET['id'])) { header($_SERVER["SERVER_PROTOCOL"]." 400 Bad Request", true, 400); exit(); } /* * If the business ID has an invalid format */ elseif (strlen($_GET['id'] != 9)) { header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found", true, 404); exit(); } $id = $_GET['id']; /* * Query our own API */ $api_url = 'https://vabusinesses.org/api/business/' . $id; $business_json = get_content($api_url); $business = json_decode($business_json); if ($business === FALSE) { header($_SERVER["SERVER_PROTOCOL"]." 500 Internal Server Error", true, 500); exit(); } /* * Display a table of all field values */ echo '<table>'; foreach ($business as $field_name => $field_value) { echo '<tr><td>'; echo $field_name; echo '</td><td>'; echo $field_value; echo '</td></tr>'; } echo '</table>';
<?php /* * If no business ID has been passed in the URL */ if (!isset($_GET['id'])) { header($_SERVER["SERVER_PROTOCOL"]." 400 Bad Request", true, 400); exit(); } /* * If the business ID has an invalid format */ elseif (strlen($_GET['id'] != 9)) { header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found", true, 404); exit(); } $id = $_GET['id']; /* * Query our own API */ $api_url = 'https://vabusinesses.org/api/business/' . $id; $business_json = get_file_contents($api_url); $business = json_decode($business_json); if ($business === FALSE) { header($_SERVER["SERVER_PROTOCOL"]." 500 Internal Server Error", true, 500); exit(); } /* * Display a table of all field values */ echo '<table>'; foreach ($business as $field_name => $field_value) { echo '<tr><td>'; echo $field_name; echo '</td><td>'; echo $field_value; echo '</td></tr>'; } echo '</table>';
Make sure StreamUtil.close also works for null git-svn-id: 71d8a689455c5fbb0f077bc40adcfc391e14cb9d@1541134 13f79535-47bb-0310-9956-ffa450edef68
/* * 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.karaf.util; import java.io.Closeable; import java.io.IOException; public class StreamUtils { private StreamUtils() { } public static void close(Closeable... closeables) { for (Closeable c : closeables) { try { if (c != null) { c.close(); } } catch (IOException e) { // Ignore } } } }
/* * 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.karaf.util; import java.io.Closeable; import java.io.IOException; public class StreamUtils { private StreamUtils() { } public static void close(Closeable... closeables) { for (Closeable c : closeables) { try { c.close(); } catch (IOException e) { // Ignore } } } }
Fix a bug that would add updated control ip address instead of replace
from pprint import pprint from netaddr import * def merge(dbag, ip): added = False for dev in dbag: if dev == "id": continue for address in dbag[dev]: if address['public_ip'] == ip['public_ip']: dbag[dev].remove(address) if ip['add']: ipo = IPNetwork(ip['public_ip'] + '/' + ip['netmask']) ip['device'] = 'eth' + str(ip['nic_dev_id']) ip['cidr'] = str(ipo.ip) + '/' + str(ipo.prefixlen) ip['network'] = str(ipo.network) + '/' + str(ipo.prefixlen) if 'nw_type' not in ip.keys(): ip['nw_type'] = 'public' if ip['nw_type'] == 'control': dbag['eth' + str(ip['nic_dev_id'])] = [ ip ] else: dbag.setdefault('eth' + str(ip['nic_dev_id']), []).append( ip ) return dbag
from pprint import pprint from netaddr import * def merge(dbag, ip): added = False for dev in dbag: if dev == "id": continue for address in dbag[dev]: if address['public_ip'] == ip['public_ip']: dbag[dev].remove(address) if ip['add']: ipo = IPNetwork(ip['public_ip'] + '/' + ip['netmask']) ip['device'] = 'eth' + str(ip['nic_dev_id']) ip['cidr'] = str(ipo.ip) + '/' + str(ipo.prefixlen) ip['network'] = str(ipo.network) + '/' + str(ipo.prefixlen) if 'nw_type' not in ip.keys(): ip['nw_type'] = 'public' dbag.setdefault('eth' + str(ip['nic_dev_id']), []).append( ip ) return dbag
Add missing license to pip package
# Copyright 2019 The TensorFlow 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. # ============================================================================== from __future__ import absolute_import from __future__ import division from __future__ import print_function import setuptools setuptools.setup( name="tensorboard_plugin_wit", version="1.6.0", description="What-If Tool TensorBoard plugin.", packages=setuptools.find_packages(), license='Apache 2.0', package_data={ "tensorboard_plugin_wit": ["static/**"], }, entry_points={ "tensorboard_plugins": [ "wit = tensorboard_plugin_wit.wit_plugin_loader:WhatIfToolPluginLoader", ], }, )
# Copyright 2019 The TensorFlow 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. # ============================================================================== from __future__ import absolute_import from __future__ import division from __future__ import print_function import setuptools setuptools.setup( name="tensorboard_plugin_wit", version="1.6.0", description="What-If Tool TensorBoard plugin.", packages=setuptools.find_packages(), package_data={ "tensorboard_plugin_wit": ["static/**"], }, entry_points={ "tensorboard_plugins": [ "wit = tensorboard_plugin_wit.wit_plugin_loader:WhatIfToolPluginLoader", ], }, )
[select] Add onChange as an option of the field (corelated selects).
var {isObject, isFunction} = require('lodash/lang'); var valueBehaviourMixin = { /** @inheritdoc */ getDefaultProps: function getDefaultValueBehaviourProps(){ return { error: undefined, value: undefined }; }, /** @inheritdoc */ getInitialState: function getFieldInitialState(){ return { error: this.props.error, value: this.props.value }; }, /** * Get the value from the field. */ getValue: function() { if(isObject(this.refs) && isObject(this.refs.input) && isFunction(this.refs.input.getValue)){ return this.refs.input.getValue(); } else if(this.state && this.state.value !== undefined ){ return this.state.value; } else if(this.props && this.props.value !== undefined ){ return this.props.value; } }, /** * Handler called when the input Change its value. * @param {event} event - The event to set. */ onInputChange: function fieldOnInputChanges(event){ if(this.props.onChange){ return this.props.onChange(event); } this.setState({error: undefined, value: this.getValue()}); } }; module.exports = valueBehaviourMixin;
var {isObject, isFunction} = require('lodash/lang'); var valueBehaviourMixin = { /** @inheritdoc */ getDefaultProps: function getDefaultValueBehaviourProps(){ return { error: undefined, value: undefined }; }, /** @inheritdoc */ getInitialState: function getFieldInitialState(){ return { error: this.props.error, value: this.props.value }; }, /** * Get the value from the field. */ getValue: function() { if(isObject(this.refs) && isObject(this.refs.input) && isFunction(this.refs.input.getValue)){ return this.refs.input.getValue(); } else if(this.state && this.state.value !== undefined ){ return this.state.value; } else if(this.props && this.props.value !== undefined ){ return this.props.value; } }, /** * Handler called when the input Change its value. * @param {event} event - The event to set. */ onInputChange: function fieldOnInputChanges(event){ this.setState({error: undefined, value: this.getValue()}); } }; module.exports = valueBehaviourMixin;
Fix send error messages in wsProxy.
import assign from 'lodash.assign' import createDebug from 'debug' import WebSocket from 'ws' const debug = createDebug('xo:wsProxy') const defaults = { // Automatically close the client connection when the remote close. autoClose: true } // Proxy a WebSocket `client` to a remote server which has `url` as // address. export default function wsProxy (client, url, opts) { opts = assign({}, defaults, opts) const autoClose = !!opts.autoClose delete opts.autoClose function onClientSend (error) { if (error) { debug('client send error', error) } } function onRemoteSend (error) { if (error) { debug('remote send error', error) } } const remote = new WebSocket(url, opts).once('open', function () { debug('connected to %s', url) }).once('close', function () { debug('remote closed') if (autoClose) { client.close() } }).once('error', function (error) { debug('remote error: %s', error) }).on('message', function (message) { client.send(message, onClientSend) }) client.once('close', function () { debug('client closed') remote.close() }).on('message', function (message) { remote.send(message, onRemoteSend) }) }
import assign from 'lodash.assign' import createDebug from 'debug' import WebSocket from 'ws' const debug = createDebug('xo:wsProxy') const defaults = { // Automatically close the client connection when the remote close. autoClose: true } // Proxy a WebSocket `client` to a remote server which has `url` as // address. export default function wsProxy (client, url, opts) { opts = assign({}, defaults, opts) const autoClose = !!opts.autoClose delete opts.autoClose function onClientSendError (error) { debug('client send error', error) } function onRemoteSendError (error) { debug('remote send error', error) } const remote = new WebSocket(url, opts).once('open', function () { debug('connected to %s', url) }).once('close', function () { debug('remote closed') if (autoClose) { client.close() } }).once('error', function (error) { debug('remote error: %s', error) }).on('message', function (message) { client.send(message, onClientSendError) }) client.once('close', function () { debug('client closed') remote.close() }).on('message', function (message) { remote.send(message, onRemoteSendError) }) }
Remove default global name from loadClient
/** * Treasure Client Loader */ // Modules var _ = require('./utils/lodash') // Helpers function applyToClient (client, method) { var _method = '_' + method if (client[_method]) { var arr = client[_method] || [] while (arr.length) { client[method].apply(client, arr.shift()) } delete client[_method] } } // Constants var TREASURE_KEYS = ['init', 'set', 'addRecord', 'trackPageview', 'trackEvent', 'ready'] /** * Load clients */ module.exports = function loadClients (Treasure, name) { if (_.isObject(global[name])) { var snippet = global[name] var clients = snippet.clients // Copy over Treasure.prototype functions over to snippet's prototype // This allows already-instanciated clients to work _.mixin(snippet.prototype, Treasure.prototype) // Iterate over each client instance _.forEach(clients, function (client) { // Call each key and with any stored values _.forEach(TREASURE_KEYS, function (value) { applyToClient(client, value) }) }) } }
/** * Treasure Client Loader */ // Modules var _ = require('./utils/lodash') // Helpers function applyToClient (client, method) { var _method = '_' + method if (client[_method]) { var arr = client[_method] || [] while (arr.length) { client[method].apply(client, arr.shift()) } delete client[_method] } } // Constants var TREASURE_KEYS = ['init', 'set', 'addRecord', 'trackPageview', 'trackEvent', 'ready'] /** * Load clients */ module.exports = function loadClients (Treasure, name) { name = name || 'Treasure' if (_.isObject(global[name])) { var snippet = global[name] var clients = snippet.clients // Copy over Treasure.prototype functions over to snippet's prototype // This allows already-instanciated clients to work _.mixin(snippet.prototype, Treasure.prototype) // Iterate over each client instance _.forEach(clients, function (client) { // Call each key and with any stored values _.forEach(TREASURE_KEYS, function (value) { applyToClient(client, value) }) }) } }
Move error formatting into validation object
'use strict'; // Load requirements const ajv = require('ajv')({allErrors: true, removeAdditional: 'all'}); // Load our schemas ajv.addSchema(require('./schema/tasks.schema'), 'tasks'); ajv.addSchema(require('./schema/task.schema'), 'task'); // Build the module structure module.exports = { // Error formatting error: (errors) => { return { status: false, errors: errors.map((err) => { return {path: err.dataPath || '', message: err.message || ''}; }) }; }, // Validate a single task object object: (obj) => { if ( ! ajv.validate('task', obj) ) { return this.error(ajv.errors); } return {status: true, errors: []}; }, // Validate a task config file file: (obj) => { if ( ! ajv.validate('tasks', obj) ) { return this.error(ajv.errors); } return {status: true, errors: []}; } };
'use strict'; // Load requirements const ajv = require('ajv')({allErrors: true, removeAdditional: 'all'}); // Load our schemas ajv.addSchema(require('./schema/tasks.schema'), 'tasks'); ajv.addSchema(require('./schema/task.schema'), 'task'); // Error formatting function error(errors) { return { status: false, errors: errors.map((err) => { return {path: err.dataPath, message: err.message}; }) }; } // Build the module structure module.exports = { // Validate a single task object object: (obj) => { if ( ! ajv.validate('task', obj) ) { return error(ajv.errors); } return {status: true, errors: []}; }, // Validate a task config file file: (obj) => { if ( ! ajv.validate('tasks', obj) ) { return error(ajv.errors); } return {status: true, errors: []}; } };
Read returned page, just to make sure
#This file is part of the ISIS IBEX application. #Copyright (C) 2012-2016 Science & Technology Facilities Council. #All rights reserved. # #This program is distributed in the hope that it will be useful. #This program and the accompanying materials are made available under the #terms of the Eclipse Public License v1.0 which accompanies this distribution. #EXCEPT AS EXPRESSLY SET FORTH IN THE ECLIPSE PUBLIC LICENSE V1.0, THE PROGRAM #AND ACCOMPANYING MATERIALS ARE PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES #OR CONDITIONS OF ANY KIND. See the Eclipse Public License v1.0 for more details. # #You should have received a copy of the Eclipse Public License v1.0 #along with this program; if not, you can obtain a copy from #https://www.eclipse.org/org/documents/epl-v10.php or #http://opensource.org/licenses/eclipse-1.0.php import urllib2 class ArchiverWrapper(object): def restart_archiver(self): # Set to ignore proxy for localhost proxy_handler = urllib2.ProxyHandler({}) opener = urllib2.build_opener(proxy_handler) urllib2.install_opener(opener) res = urllib2.urlopen("http://localhost:4813/restart") d = res.read()
#This file is part of the ISIS IBEX application. #Copyright (C) 2012-2016 Science & Technology Facilities Council. #All rights reserved. # #This program is distributed in the hope that it will be useful. #This program and the accompanying materials are made available under the #terms of the Eclipse Public License v1.0 which accompanies this distribution. #EXCEPT AS EXPRESSLY SET FORTH IN THE ECLIPSE PUBLIC LICENSE V1.0, THE PROGRAM #AND ACCOMPANYING MATERIALS ARE PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES #OR CONDITIONS OF ANY KIND. See the Eclipse Public License v1.0 for more details. # #You should have received a copy of the Eclipse Public License v1.0 #along with this program; if not, you can obtain a copy from #https://www.eclipse.org/org/documents/epl-v10.php or #http://opensource.org/licenses/eclipse-1.0.php import urllib2 class ArchiverWrapper(object): def restart_archiver(self): # Set to ignore proxy for localhost proxy_handler = urllib2.ProxyHandler({}) opener = urllib2.build_opener(proxy_handler) urllib2.install_opener(opener) urllib2.urlopen("http://localhost:4813/restart")