text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Fix i18nPlugin issue introduced with g/277926
Test Plan
1. Pull down code
2. `yarn storybook` should open storybook
3. Should not throw an error for storybook regarding i18nPlugin
Change-Id: I2fc15dfae332819d8e45993314f4d0529427520c
Reviewed-on: https://gerrit.instructure.com/c/canvas-lms/+/278846
Tested-by: Service Cloud Jenkins <[email protected]>
Reviewed-by: Charley Kline <[email protected]>
Product-Review: Charley Kline <[email protected]>
QA-Review: Chawn Neal <[email protected]> | const I18nPlugin = require('../ui-build/webpack/i18nPlugin')
const path = require('path')
const baseWebpackConfig = require('../ui-build/webpack')
const root = path.resolve(__dirname, '..')
module.exports = {
stories: [
'../ui/**/*.stories.mdx',
'../ui/**/*.stories.@(js|jsx|ts|tsx)'
],
addons: [
'@storybook/addon-links',
'@storybook/addon-essentials'
],
webpackFinal: async (config) => {
config.module.noParse = [/i18nliner\/dist\/lib\/i18nliner/]
config.plugins.push(I18nPlugin)
config.resolveLoader.modules = [
path.resolve(__dirname, '../ui-build/webpack'),
'node_modules'
]
config.resolve.modules = [
path.resolve(__dirname, '../ui/shims'),
path.resolve(__dirname, '../public/javascripts'), // for translations
'node_modules'
]
config.resolve.alias = {...baseWebpackConfig.resolve.alias, ...config.resolve.alias}
config.module.rules = [
...config.module.rules,
{
test: /\.coffee$/,
include: [path.resolve(__dirname, '../ui')],
loaders: ['coffee-loader']
},
{
test: /\.handlebars$/,
include: [path.resolve(__dirname, '../ui')],
loaders: ['i18nLinerHandlebars']
}
]
return config
}
}
| const I18nPlugin = require('../ui-build/webpack/i18nPlugin')
const path = require('path')
const baseWebpackConfig = require('../ui-build/webpack')
const root = path.resolve(__dirname, '..')
module.exports = {
stories: [
'../ui/**/*.stories.mdx',
'../ui/**/*.stories.@(js|jsx|ts|tsx)'
],
addons: [
'@storybook/addon-links',
'@storybook/addon-essentials'
],
webpackFinal: async (config) => {
config.module.noParse = [/i18nliner\/dist\/lib\/i18nliner/]
config.plugins.push(new I18nPlugin())
config.resolveLoader.modules = [
path.resolve(__dirname, '../ui-build/webpack'),
'node_modules'
]
config.resolve.modules = [
path.resolve(__dirname, '../ui/shims'),
path.resolve(__dirname, '../public/javascripts'), // for translations
'node_modules'
]
config.resolve.alias = {...baseWebpackConfig.resolve.alias, ...config.resolve.alias}
config.module.rules = [
...config.module.rules,
{
test: /\.coffee$/,
include: [path.resolve(__dirname, '../ui')],
loaders: ['coffee-loader']
},
{
test: /\.handlebars$/,
include: [path.resolve(__dirname, '../ui')],
loaders: ['i18nLinerHandlebars']
}
]
return config
}
}
|
Remove unused log message param | package com.nelsonjrodrigues.pchud;
import java.io.IOException;
import com.nelsonjrodrigues.pchud.net.MessageListener;
import com.nelsonjrodrigues.pchud.net.NetThread;
import com.nelsonjrodrigues.pchud.net.PcMessage;
import com.nelsonjrodrigues.pchud.world.Worlds;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class PcHud {
public static void main(String[] args) {
Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
log.error("Uncaught thread exception, exiting", e);
System.exit(-1);
});
Worlds worlds = new Worlds();
worlds.addPropertyChangeListener(evt -> {
log.debug("{}", worlds);
});
try {
NetThread netThread = new NetThread();
netThread.addMessageListener(new LogMessageListener());
netThread.addMessageListener(worlds);
netThread.start();
netThread.join();
}
catch (IOException | InterruptedException e) {
log.error(e.getMessage(), e);
}
log.debug("Exiting");
}
@Slf4j
private static class LogMessageListener implements MessageListener {
@Override
public void onMessage(PcMessage message) {
log.debug("OnMessage {}", message);
}
@Override
public void onTimeout() {
log.debug("OnTimeout");
}
}
}
| package com.nelsonjrodrigues.pchud;
import java.io.IOException;
import com.nelsonjrodrigues.pchud.net.MessageListener;
import com.nelsonjrodrigues.pchud.net.NetThread;
import com.nelsonjrodrigues.pchud.net.PcMessage;
import com.nelsonjrodrigues.pchud.world.Worlds;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class PcHud {
public static void main(String[] args) {
Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
log.error("Uncaught thread exception, exiting", t.getName(), e);
System.exit(-1);
});
Worlds worlds = new Worlds();
worlds.addPropertyChangeListener(evt -> {
log.debug("{}", worlds);
});
try {
NetThread netThread = new NetThread();
netThread.addMessageListener(new LogMessageListener());
netThread.addMessageListener(worlds);
netThread.start();
netThread.join();
}
catch (IOException | InterruptedException e) {
log.error(e.getMessage(), e);
}
log.debug("Exiting");
}
@Slf4j
private static class LogMessageListener implements MessageListener {
@Override
public void onMessage(PcMessage message) {
log.debug("OnMessage {}", message);
}
@Override
public void onTimeout() {
log.debug("OnTimeout");
}
}
}
|
Remove double count in staging | <?php
class DisplayImportABCD implements IDisplayModels
{
public function getName()
{
return "ABCD(EFG) XML";
}
public function getColumns()
{
return array(
'category'=>'Category',
'expedition_name' => 'Expedition',
'gtu' => 'Sampling Location',
'taxon' => 'Taxon.',
'ig' => 'I.G.',
'acquisition' => 'Acquisition',
'individual_type' => 'Type',
'individual_sex' => 'Sex',
'individual_state' => 'State',
'individual_stage' => 'Stage',
'individual_social_status' => 'Social Status',
'individual_rock_form' => 'Rock Form',
'part' => 'Part',
'specimen_status' => 'Status',
'institution' => 'Institution',
'building' => 'Building',
'floor' => 'Floor',
'room' => 'Room',
'row' => 'Row',
'shelf' => 'Shelf',
'container_type' => 'Container Type',
'container_storage' => 'Container storage',
'container' => 'Container',
'sub_container_type' => 'Sub container type',
'sub_container_storage' => 'Sub container storage',
'sub_container' => 'Sub container',
'part_count' => 'Number',
'chrono' => 'Chrono.',
'litho' => 'Litho.',
'lithology' => 'Lithology',
'mineral' => 'Mineral.',
);
}
}
| <?php
class DisplayImportABCD implements IDisplayModels
{
public function getName()
{
return "ABCD(EFG) XML";
}
public function getColumns()
{
return array(
'category'=>'Category',
'expedition_name' => 'Expedition',
'gtu' => 'Sampling Location',
'taxon' => 'Taxon.',
'ig' => 'I.G.',
'acquisition' => 'Acquisition',
'individual_type' => 'Type',
'individual_sex' => 'Sex',
'individual_state' => 'State',
'individual_stage' => 'Stage',
'individual_social_status' => 'Social Status',
'individual_rock_form' => 'Rock Form',
'individual_count' => 'Number',
'part' => 'Part',
'specimen_status' => 'Status',
'institution' => 'Institution',
'building' => 'Building',
'floor' => 'Floor',
'room' => 'Room',
'row' => 'Row',
'shelf' => 'Shelf',
'container_type' => 'Container Type',
'container_storage' => 'Container storage',
'container' => 'Container',
'sub_container_type' => 'Sub container type',
'sub_container_storage' => 'Sub container storage',
'sub_container' => 'Sub container',
'part_count' => 'Number',
'chrono' => 'Chrono.',
'litho' => 'Litho.',
'lithology' => 'Lithology',
'mineral' => 'Mineral.',
);
}
}
|
Add filter input on server var | <?php
namespace Acd;
/**
* Http class
* @author Acidvertigo MIT Licence
*/
class Http
{
/**
* Check HTTP version
* @return string
*/
public function protocol()
{
return filter_input(INPUT_SERVER,'SERVER_PROTOCOL');
}
/**
* Check if communication is on SSL or not
* @return bool true on HTTPS
*/
public function isSsl()
{
return (!empty(filter_input(INPUT_SERVER,'HTTPS')) && filter_input(INPUT_SERVER,'HTTPS') !== 'off' || filter_input(INPUT_SERVER,'SERVER_PORT') == 443) ? TRUE : FALSE;
}
/**
* @param string $method HTTP method
* @return bool true if the mothod is safe
*/
public function isSafeMethod($method)
{
$safeMethods = ['HEAD', 'GET', 'OPTIONS', 'TRACE'];
return isset($safeMethods[$method]);
}
/**
* @param string $method HTTP method
* @return bool true if the method is idempotent
*/
public function isIdempotentMethod($method)
{
// Though it is possible to be idempotent, POST
// is not guarunteed to be, and more often than
// not, it is not.
$idempotentMethods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'PATCH', 'PUT', 'TRACE'];
return isset($idempotentMethods[$method]);
}
}
| <?php
namespace Acd;
/**
* Http class
* @author Acidvertigo MIT Licence
*/
class Http
{
/**
* Check HTTP version
* @return string
*/
public function protocol()
{
return $_SERVER['SERVER_PROTOCOL'];
}
/**
* Check if communication is on SSL or not
* @return bool true on HTTPS
*/
public function isSsl()
{
return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? true : false;
}
/**
* @param string $method HTTP method
* @return bool true if the mothod is safe
*/
public function isSafeMethod($method)
{
$safeMethods = ['HEAD', 'GET', 'OPTIONS', 'TRACE'];
return isset($safeMethods[$method]);
}
/**
* @param string $method HTTP method
* @return bool true if the method is idempotent
*/
public function isIdempotentMethod($method)
{
// Though it is possible to be idempotent, POST
// is not guarunteed to be, and more often than
// not, it is not.
$idempotentMethods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'PATCH', 'PUT', 'TRACE'];
return isset($idempotentMethods[$method]);
}
}
|
Add fix bug in animation | /*! Animate.js | The MIT License (MIT) | Copyright (c) 2017 GibboK */
; (function (animate) {
'use strict';
animate.zoomOutUp = function (selector, options) {
var keyframeset = [
{
opacity: 1,
transform: 'none',
transformOrigin: 'center bottom',
offset: 0
},
{
opacity: 1,
transform: 'scale3d(.475, .475, .475) translate3d(0, 60px, 0)',
animationTimingFunction: 'cubic-bezier(0.550, 0.055, 0.675, 0.190)',
offset: 0.4
},
{
opacity: 0,
transform: 'scale3d(.1, .1, .1) translate3d(0, -2000px, 0)',
transformOrigin: 'center bottom',
animationTimingFunction: 'cubic-bezier(0.175, 0.885, 0.320, 1)',
offset: 1
}
];
return animate._animate(selector, keyframeset, options);
}
})(window.animate = window.animate || {});
| /*! Animate.js | The MIT License (MIT) | Copyright (c) 2017 GibboK */
; (function (animate) {
'use strict';
animate.zoomOutUp = function (selector, options) {
var keyframeset = [
{
opacity: 1,
transform: 'none',
transformOrigin: 'left center',
offset: 0
},
{
opacity: 1,
transform: 'scale3d(.475, .475, .475) translate3d(0, 60px, 0)',
animationTimingFunction: 'cubic-bezier(0.550, 0.055, 0.675, 0.190)',
offset: 0.4
},
{
opacity: 0,
transform: 'scale3d(.1, .1, .1) translate3d(0, -2000px, 0)',
transformOrigin: 'center bottom',
animationTimingFunction: 'cubic-bezier(0.175, 0.885, 0.320, 1)',
offset: 1
}
];
return animate._animate(selector, keyframeset, options);
}
})(window.animate = window.animate || {});
|
Declare and use normalOffset variable as value of original offset from top. | 'use strict';
module.exports = function(app) {
app.controller('NavController', ['$rootScope', 'AuthService', function($rs, AuthService) {
this.signout = AuthService.signout;
let $window = $(window);
let $hamMenu = $('#hamburger-menu-icon');
let $banner = $('.banner-container');
let $navBar = $('nav-bar');
let $gffNav = $('.gff-nav');
let $navMenu = $('#nav-menu');
this.toggleMenu = function($el) {
$el.toggleClass('open');
$navMenu.toggleClass('open');
};
this.backgroundParallax = function() {
let normalOffset = $navBar.offset().top;
let offsetTop = 0;
$window.on('scroll', () => {
offsetTop = $navBar.offset().top;
offsetTop = normalOffset - ((offsetTop - normalOffset) * 0.2);
if (offsetTop < 0) offsetTop = 0;
if (offsetTop > normalOffset) offsetTop = normalOffset;
if (offsetTop === 0) {
$gffNav.css('width', '100%');
$navBar.css('height', '60px');
}
else {
$gffNav.css('width', '97%');
$navBar.css('height', '80px');
}
$navBar.css('top', offsetTop + 'px');
});
}
$hamMenu.on('click', () => {
this.toggleMenu($hamMenu);
});
this.backgroundParallax();
}]);
};
| 'use strict';
module.exports = function(app) {
app.controller('NavController', ['$rootScope', 'AuthService', function($rs, AuthService) {
this.signout = AuthService.signout;
let $window = $(window);
let $hamMenu = $('#hamburger-menu-icon');
let $banner = $('.banner-container');
let $navBar = $('nav-bar');
let $gffNav = $('.gff-nav');
let $navMenu = $('#nav-menu');
this.toggleMenu = function($el) {
$el.toggleClass('open');
$navMenu.toggleClass('open');
};
this.backgroundParallax = function() {
let offsetTop = 0;
$window.on('scroll', () => {
offsetTop = $navBar.offset().top;
offsetTop = 15 - ((offsetTop - 15) * 0.2);
if (offsetTop < 0) offsetTop = 0;
if (offsetTop > 15) offsetTop = 15;
if (offsetTop === 0) {
$gffNav.css('width', '100%');
$navBar.css('height', '60px');
}
else {
$gffNav.css('width', '97%');
$navBar.css('height', '80px');
}
$navBar.css('top', offsetTop + 'px');
});
}
$hamMenu.on('click', () => {
this.toggleMenu($hamMenu);
});
this.backgroundParallax();
}]);
};
|
Fix trigger exception when no listeners specified | let GlobalEvents = () => {
let events = {};
return {
off: (eventHandle) => {
let index = events[eventHandle.eventName].findIndex((singleEventHandler) => {
return singleEventHandler.id !== eventHandle.handlerId;
});
events[eventHandle.eventName].splice(index, 1);
},
on: (eventName, handlerCallback) => {
if (!events[eventName]) {
events[eventName] = [];
}
let handlers = events[eventName];
let newHandlerId = new Date().getTime();
handlers.push({
id: newHandlerId,
callback: handlerCallback
});
return {
id: newHandlerId,
eventName
};
},
trigger: (eventName, data) => {
if (events[eventName]) {
events[eventName].forEach((singleHandler) => {
singleHandler.callback(data);
});
}
}
};
}
export default GlobalEvents; | let GlobalEvents = () => {
let events = {};
return {
off: (eventHandle) => {
let index = events[eventHandle.eventName].findIndex((singleEventHandler) => {
return singleEventHandler.id !== eventHandle.handlerId;
});
events[eventHandle.eventName].splice(index, 1);
},
on: (eventName, handlerCallback) => {
if (!events[eventName]) {
events[eventName] = [];
}
let handlers = events[eventName];
let newHandlerId = new Date().getTime();
handlers.push({
id: newHandlerId,
callback: handlerCallback
});
return {
id: newHandlerId,
eventName
};
},
trigger: (eventName, data) => {
events[eventName].forEach((singleHandler) => {
singleHandler.callback(data);
});
}
};
}
export default GlobalEvents; |
Clarify variables for Google Play credentials | package org.linuxguy.MarketBot;
import org.linuxguy.MarketBot.FlowdockNotifier.FlowdockNotificationType;
public class MarketBot {
public static void main(String[] args) throws InterruptedException {
String googlePlayUsername = "[email protected]";
String googlePlayPassword = "foo";
String groupMeBotId = "XYZPDQ";
String flowdockInboxId = "123456789";
String botName = "MarketBot";
final String androidPackage = "com.mycompany.MyApp";
GooglePlayWatcher playWatcher = new GooglePlayWatcher(googlePlayUsername, googlePlayPassword, androidPackage, "My Android App");
FlowdockNotifier flowdockNotifier = new FlowdockNotifier(botName,
flowdockInboxId,
FlowdockNotificationType.INBOX);
playWatcher.addListener(flowdockNotifier);
playWatcher.start();
// You can find this app ID in iTunes Connect
String iOSAppId = "123456789";
AppStoreRSSWatcher appStoreWatcherUS = new AppStoreRSSWatcher("us", iOSAppId, "My iOS App");
appStoreWatcherUS.addListener(new GroupMeNotifier(groupMeBotId));
appStoreWatcherUS.start();
System.out.println("All pollers started");
// Keep running until the watchers get tired. (Never!)
playWatcher.join();
appStoreWatcherUS.join();
}
}
| package org.linuxguy.MarketBot;
import org.linuxguy.MarketBot.FlowdockNotifier.FlowdockNotificationType;
public class MarketBot {
public static void main(String[] args) throws InterruptedException {
String username = "[email protected]";
String password = "foo";
String groupMeBotId = "XYZPDQ";
String flowdockInboxId = "123456789";
String botName = "MarketBot";
final String androidPackage = "com.mycompany.MyApp";
GooglePlayWatcher playWatcher = new GooglePlayWatcher(username, password, androidPackage, "My Android App");
FlowdockNotifier flowdockNotifier = new FlowdockNotifier(botName,
flowdockInboxId,
FlowdockNotificationType.INBOX);
playWatcher.addListener(flowdockNotifier);
playWatcher.start();
// You can find this app ID in iTunes Connect
String iOSAppId = "123456789";
AppStoreRSSWatcher appStoreWatcherUS = new AppStoreRSSWatcher("us", iOSAppId, "My iOS App");
appStoreWatcherUS.addListener(new GroupMeNotifier(groupMeBotId));
appStoreWatcherUS.start();
System.out.println("All pollers started");
// Keep running until the watchers get tired. (Never!)
playWatcher.join();
appStoreWatcherUS.join();
}
}
|
Add ability to override the port grizzly server starts on. | package com.fenixinfotech.grizzly.framework.playpen;
import com.fenixinfotech.web.common.FrameworkServerBase;
import org.glassfish.grizzly.http.server.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class GrizzlyFrameworkServer extends FrameworkServerBase
{
private static final Logger logger = LoggerFactory.getLogger(GrizzlyFrameworkServer.class);
public void runServer() throws IOException
{
runServer(defaultPort);
}
public void runServer(int port) throws IOException
{
logger.info("starting grizzly framework server on port {}", port);
final NetworkListener listener = new NetworkListener("Grizzly", "localhost", port);
listener.setSecure(false);
HttpServer httpServer = new HttpServer();
httpServer.addListener(listener);
final ServerConfiguration serverConfiguration = httpServer.getServerConfiguration();
serverConfiguration.addHttpHandler(new HttpHandler()
{
public void service(Request requestm, Response response) throws Exception
{
final SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.UK);
final String date = format.format(new Date(System.currentTimeMillis()));
response.setContentType("text/plain");
response.setContentLength(date.length());
response.getWriter().write(date);
}
}
);
httpServer.start();
logger.info("bootstrap of grizzly framework server complete, running on http://localhost:{}", port);
}
}
| package com.fenixinfotech.grizzly.framework.playpen;
import com.fenixinfotech.web.common.FrameworkServerBase;
import org.glassfish.grizzly.http.server.HttpHandler;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.grizzly.http.server.Request;
import org.glassfish.grizzly.http.server.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class GrizzlyFrameworkServer extends FrameworkServerBase
{
private static final Logger logger = LoggerFactory.getLogger(GrizzlyFrameworkServer.class);
public void runServer() throws IOException {
HttpServer httpServer = HttpServer.createSimpleServer();
httpServer.getServerConfiguration().addHttpHandler(new HttpHandler() {
public void service(Request requestm, Response response) throws Exception {
final SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.UK);
final String date = format.format(new Date(System.currentTimeMillis()));
response.setContentType("text/plain");
response.setContentLength(date.length());
response.getWriter().write(date);
}
},
"/hello"
);
httpServer.start();
}
}
|
Revert "Dashboard API routes are not meant for the browser"
This reverts commit 8fcef7b711423816260aba7669283fe2840f7893. | <?php
/*
* This file is part of Cachet.
*
* (c) Alt Three Services Limited
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CachetHQ\Cachet\Http\Routes\Dashboard;
use Illuminate\Contracts\Routing\Registrar;
/**
* This is the dashboard api routes class.
*
* @author James Brooks <[email protected]>
* @author Connor S. Parks <[email protected]>
*/
class ApiRoutes
{
/**
* Defines if these routes are for the browser.
*
* @var bool
*/
public static $browser = true;
/**
* Define the dashboard api routes.
*
* @param \Illuminate\Contracts\Routing\Registrar $router
*
* @return void
*/
public function map(Registrar $router)
{
$router->group([
'middleware' => ['auth'],
'namespace' => 'Dashboard',
'prefix' => 'dashboard/api',
], function (Registrar $router) {
$router->get('incidents/templates', 'ApiController@getIncidentTemplate');
$router->post('components/groups/order', 'ApiController@postUpdateComponentGroupOrder');
$router->post('components/order', 'ApiController@postUpdateComponentOrder');
$router->any('components/{component}', 'ApiController@postUpdateComponent');
});
}
}
| <?php
/*
* This file is part of Cachet.
*
* (c) Alt Three Services Limited
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CachetHQ\Cachet\Http\Routes\Dashboard;
use Illuminate\Contracts\Routing\Registrar;
/**
* This is the dashboard api routes class.
*
* @author James Brooks <[email protected]>
* @author Connor S. Parks <[email protected]>
*/
class ApiRoutes
{
/**
* Defines if these routes are for the browser.
*
* @var bool
*/
public static $browser = false;
/**
* Define the dashboard api routes.
*
* @param \Illuminate\Contracts\Routing\Registrar $router
*
* @return void
*/
public function map(Registrar $router)
{
$router->group([
'middleware' => ['auth'],
'namespace' => 'Dashboard',
'prefix' => 'dashboard/api',
], function (Registrar $router) {
$router->get('incidents/templates', 'ApiController@getIncidentTemplate');
$router->post('components/groups/order', 'ApiController@postUpdateComponentGroupOrder');
$router->post('components/order', 'ApiController@postUpdateComponentOrder');
$router->any('components/{component}', 'ApiController@postUpdateComponent');
});
}
}
|
Fix copying of files in herc/data during installation. | from setuptools import setup, find_packages
import os
import os.path
import urllib.parse
def readme():
with open('README.md') as f:
return f.read()
setup(name='herc',
version='0.1',
description='Herc is a webservice that dispatches jobs to Apache Aurora.',
long_description=readme(),
url='http://github.com/broadinstitute/herc',
author='The Broad Institute',
packages=find_packages(exclude='tests'),
data_files=[('data/aurora', ['data/aurora/api.thrift']),
('data/schemas', ['data/schemas/jobsubmit.json'])],
install_requires=[
'tornado>=4.0',
'jsonschema',
'futures',
'Jinja2>=2.2',
'jsonref',
'pyhocon',
'mock',
'arrow',
'nose',
'requests',
'thrift==1.0.0-py3',
'munch'
],
entry_points={'console_scripts': ['herc = herc.webservice:main']},
dependency_links = [urllib.parse.urljoin('file:', os.path.join(os.getcwd(), 'thrift-1.0.0-py3.tar.gz'))],
zip_safe=False,
test_suite='nose.collector',
tests_require=['nose']
)
| from setuptools import setup, find_packages
import os
import os.path
import urllib.parse
def readme():
with open('README.md') as f:
return f.read()
setup(name='herc',
version='0.1',
description='Herc is a webservice that dispatches jobs to Apache Aurora.',
long_description=readme(),
url='http://github.com/broadinstitute/herc',
author='The Broad Institute',
packages=find_packages(exclude='tests'),
package_data={
# Include everything in data/, both schemas and examples.
'': ['data/*']
},
install_requires=[
'tornado>=4.0',
'jsonschema',
'futures',
'Jinja2>=2.2',
'jsonref',
'pyhocon',
'mock',
'arrow',
'nose',
'requests',
'thrift==1.0.0-py3',
'munch'
],
entry_points={'console_scripts': ['herc = herc.webservice:main']},
dependency_links = [urllib.parse.urljoin('file:', os.path.join(os.getcwd(), 'thrift-1.0.0-py3.tar.gz'))],
zip_safe=False,
test_suite='nose.collector',
tests_require=['nose']
)
|
Remove the use of mapDispatchToProps | import React, { PropTypes, Component } from 'react'
import { connect } from 'react-redux'
import { incrementCounter, decrementCounter, incrementCounterAsync } from '../../actions/counter'
import {} from './Counter.scss'
class Counter extends Component {
constructor () {
super()
this.onIncrementCounter = this.onIncrementCounter.bind(this)
this.onDecrementCounter = this.onDecrementCounter.bind(this)
this.onIncrementCounterAsync = this.onIncrementCounterAsync.bind(this)
}
onIncrementCounter () {
this.props.dispatch(incrementCounter())
}
onDecrementCounter () {
this.props.dispatch(decrementCounter())
}
onIncrementCounterAsync () {
this.props.dispatch(incrementCounterAsync())
}
render () {
return (
<div className="counter">
<h2 className="counter__number">{this.props.counter}</h2>
<button onClick={this.onIncrementCounter}
className="counter__button">
+
</button>
<button onClick={this.onDecrementCounter}
className="counter__button">
-
</button>
<button onClick={this.onIncrementCounterAsync}
className="counter__button counter__button--async">
async
</button>
</div>
)
}
}
Counter.propTypes = {
counter: PropTypes.number.isRequired,
dispatch: PropTypes.func.isRequired
}
const mapStateToProps = (state) => {
return {
counter: state.counter
}
}
export default connect(mapStateToProps)(Counter)
| import React, { PropTypes, Component } from 'react'
import { connect } from 'react-redux'
import { incrementCounter, decrementCounter, incrementCounterAsync } from '../../actions/counter'
import {} from './Counter.scss'
class Counter extends Component {
render () {
return (
<div className="counter">
<h2 className="counter__number">{this.props.counter}</h2>
<button onClick={this.props.onIncrementCounter}
className="counter__button">
+
</button>
<button onClick={this.props.onDecrementCounter}
className="counter__button">
-
</button>
<button onClick={this.props.onIncrementCounterAsync}
className="counter__button counter__button--async">
async
</button>
</div>
)
}
}
Counter.propTypes = {
counter: PropTypes.number.isRequired,
onIncrementCounter: PropTypes.func.isRequired,
onDecrementCounter: PropTypes.func.isRequired,
onIncrementCounterAsync: PropTypes.func.isRequired
}
const mapStateToProps = (state) => {
return {
counter: state.counter
}
}
const mapDispatchToProps = (dispatch) => {
return {
onIncrementCounter () {
dispatch(incrementCounter())
},
onDecrementCounter () {
dispatch(decrementCounter())
},
onIncrementCounterAsync () {
dispatch(incrementCounterAsync())
}
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(Counter)
|
Add __repr__() and __str__() to Result | from ..util import cached_property
class Result:
def __init__(self, return_code, stdout_data, stderr_data, encoding):
self.return_code = return_code
self.stdout_data = stdout_data
self.stderr_data = stderr_data
self.encoding = encoding
self.succeeded = self.return_code == 0
self.failed = not self.succeeded
@cached_property
def stdout(self):
if self.stdout_data:
stdout = b''.join(self.stdout_data)
stdout = stdout.decode(self.encoding)
else:
stdout = ''
return stdout
@cached_property
def stderr(self):
if self.stderr_data:
stderr = b''.join(self.stderr_data)
stderr = stderr.decode(self.encoding)
else:
stderr = ''
return stderr
@cached_property
def stdout_lines(self):
return self.stdout.splitlines() if self.stdout else []
@cached_property
def stderr_lines(self):
return self.stderr.splitlines() if self.stderr else []
def __bool__(self):
return self.succeeded
def __str__(self):
return self.stdout
def __repr__(self):
return repr(self.stdout)
| from ..util import cached_property
class Result:
def __init__(self, return_code, stdout_data, stderr_data, encoding):
self.return_code = return_code
self.stdout_data = stdout_data
self.stderr_data = stderr_data
self.encoding = encoding
self.succeeded = self.return_code == 0
self.failed = not self.succeeded
@cached_property
def stdout(self):
if self.stdout_data:
stdout = b''.join(self.stdout_data)
stdout = stdout.decode(self.encoding)
else:
stdout = ''
return stdout
@cached_property
def stderr(self):
if self.stderr_data:
stderr = b''.join(self.stderr_data)
stderr = stderr.decode(self.encoding)
else:
stderr = ''
return stderr
@cached_property
def stdout_lines(self):
return self.stdout.splitlines() if self.stdout else []
@cached_property
def stderr_lines(self):
return self.stderr.splitlines() if self.stderr else []
def __bool__(self):
return self.succeeded
|
Remove i18n of the JS daterange filter | import moment from 'moment';
import granularities from 'models/geogranularities';
import frequencies from 'models/frequencies';
import resource_types from 'models/resource_types';
export default {
filters: {
/**
* Display a date range in the shorter possible manner.
*/
daterange: function(range) {
if (!range || !range.start) {
return;
}
const start = moment(range.start);
const end = range.end ? moment(range.end) : undefined;
const start_label = start.format('YYYY');
const end_label = end.format('YYYY');
return end_label
? `${start_label}-${end_label}`
: start_label;
},
frequency_label(dataset) {
if (dataset && dataset.frequency) {
return frequencies.by_id(dataset.frequency).label;
}
},
resource_type_label(resource) {
if (resource && resource.type) {
const resource_type = resource_types.by_id(resource.type);
if (!resource_type) return 'Type not found';
return resource_type.label;
}
},
granularity_label(dataset) {
if (dataset && dataset.spatial && dataset.spatial.granularity) {
return granularities.by_id(dataset.spatial.granularity).name;
}
}
}
};
| import moment from 'moment';
import granularities from 'models/geogranularities';
import frequencies from 'models/frequencies';
import resource_types from 'models/resource_types';
export default {
filters: {
/**
* Display a date range in the shorter possible manner.
*/
daterange: function(range) {
if (!range || !range.start) {
return;
}
const start = moment(range.start);
const end = range.end ? moment(range.end) : undefined;
const start_label = start.format('YYYY');
const end_label = end.format('YYYY');
return end_label
? this._('{start_label}-{end_label}', {start_label, end_label, interpolation: { escapeValue: false }})
: start_label;
},
frequency_label(dataset) {
if (dataset && dataset.frequency) {
return frequencies.by_id(dataset.frequency).label;
}
},
resource_type_label(resource) {
if (resource && resource.type) {
const resource_type = resource_types.by_id(resource.type);
if (!resource_type) return 'Type not found';
return resource_type.label;
}
},
granularity_label(dataset) {
if (dataset && dataset.spatial && dataset.spatial.granularity) {
return granularities.by_id(dataset.spatial.granularity).name;
}
}
}
};
|
Fix modals by making spinner_options accessible
This patch makes the spinner_options variable accessible to the modal functions
again.
Change-Id: I84b6c7e5813d5818b18675e385214feda178c482
Closes-Bug: 1459115 | /*global angularModuleExtension*/
(function () {
'use strict';
angular.module('horizon.dashboard-app', [
'horizon.dashboard-app.utils',
'horizon.dashboard-app.login',
'horizon.framework',
'hz.api',
'ngCookies'].concat(angularModuleExtension))
.constant('horizon.dashboard-app.conf', {
// Placeholders; updated by Django.
debug: null, //
static_url: null,
ajax: {
queue_limit: null
}
})
.run([
'horizon.framework.conf.spinner_options',
'horizon.dashboard-app.conf',
'horizon.dashboard-app.utils.helper-functions',
'$cookieStore',
'$http',
'$cookies',
function (spinnerOptions, hzConfig, hzUtils, $cookieStore, $http, $cookies) {
$http.defaults.headers.post['X-CSRFToken'] = $cookies.csrftoken;
//expose the configuration for horizon legacy variable
horizon.conf = angular.extend({spinner_options: spinnerOptions}, hzConfig);
horizon.utils = hzUtils;
angular.extend(horizon.cookies = {}, $cookieStore);
horizon.cookies.put = function (key, value) {
//cookies are updated at the end of current $eval, so for the horizon
//namespace we need to wrap it in a $apply function.
angular.element('body').scope().$apply(function () {
$cookieStore.put(key, value);
});
};
horizon.cookies.getRaw = function (key) {
return $cookies[key];
};
}]);
}());
| /*global angularModuleExtension*/
(function () {
'use strict';
angular.module('horizon.dashboard-app', [
'horizon.dashboard-app.utils',
'horizon.dashboard-app.login',
'horizon.framework',
'hz.api',
'ngCookies'].concat(angularModuleExtension))
.constant('horizon.dashboard-app.conf', {
// Placeholders; updated by Django.
debug: null, //
static_url: null,
ajax: {
queue_limit: null
}
})
.run([
'horizon.dashboard-app.conf',
'horizon.dashboard-app.utils.helper-functions',
'$cookieStore',
'$http',
'$cookies',
function (hzConfig, hzUtils, $cookieStore, $http, $cookies) {
$http.defaults.headers.post['X-CSRFToken'] = $cookies.csrftoken;
//expose the configuration for horizon legacy variable
horizon.conf = hzConfig;
horizon.utils = hzUtils;
angular.extend(horizon.cookies = {}, $cookieStore);
horizon.cookies.put = function (key, value) {
//cookies are updated at the end of current $eval, so for the horizon
//namespace we need to wrap it in a $apply function.
angular.element('body').scope().$apply(function () {
$cookieStore.put(key, value);
});
};
horizon.cookies.getRaw = function (key) {
return $cookies[key];
};
}]);
}());
|
Add support for 5d20 instead of d20 | import random
import re
from cardinal.decorators import command
def parse_roll(arg):
# some people might separate with commas
arg = arg.rstrip(',')
if match := re.match(r'^(\d+)?d(\d+)$', arg):
num_dice = match.group(1)
sides = match.group(2)
elif match := re.match(r'^d?(\d+)$', arg):
num_dice = 1
sides = match.group(1)
else:
return []
return [int(sides)] * int(num_dice)
class RandomPlugin:
@command('roll')
def roll(self, cardinal, user, channel, msg):
args = msg.split(' ')
args.pop(0)
dice = []
for arg in args:
dice = dice + parse_roll(arg)
results = []
limit = 10
for sides in dice:
if sides < 2 or sides > 120:
continue
limit -= 1
# Don't allow more than ten dice rolled at a time
if limit < 0:
break
results.append((sides, random.randint(1, sides)))
messages = ', '.join(
[f"d{sides}: {result}" for sides, result in results]
)
cardinal.sendMsg(channel, messages)
entrypoint = RandomPlugin
| import random
from cardinal.decorators import command
class RandomPlugin:
@command('roll')
def roll(self, cardinal, user, channel, msg):
args = msg.split(' ')
args.pop(0)
dice = []
for arg in args:
try:
sides = int(arg)
dice.append(sides)
except (TypeError, ValueError):
if arg[0] != 'd':
continue
try:
sides = int(arg[1:])
dice.append(sides)
except (TypeError, ValueError):
pass
results = []
limit = 10
for sides in dice:
if sides < 2 or sides > 120:
continue
limit -= 1
# Don't allow more than ten dice rolled at a time
if limit < 0:
break
results.append((sides, random.randint(1, sides)))
messages = ', '.join(
[f"d{sides}: {result}" for sides, result in results]
)
cardinal.sendMsg(channel, messages)
entrypoint = RandomPlugin
|
Add optional _ character to displayNameReg.
Babel, at least in my configuration, transpiles to "function _class", so we need to catch that too. | var excludeMethods = [
/^constructor$/,
/^render$/,
/^component[A-Za-z]+$/,
/^shouldComponentUpdate$/
];
var displayNameReg = /^function\s+(_?[a-zA-Z]+)/;
function isExcluded(methodName) {
return excludeMethods.some(function (reg) {
return reg.test(methodName) === false;
});
}
function bindToClass(scope, methods) {
var componentName = scope.constructor.toString().match(displayNameReg)[1];
methods = Array.isArray(methods) ? methods : [];
methods.forEach(function(methodName) {
if (methodName in scope) {
scope[methodName] = scope[methodName].bind(scope);
} else {
throw new Error('Method "' + methodName + '" does not exists in "' + componentName + '"');
}
});
// for debugging purposes only?
// if (process.env.NODE_ENV != 'production') {
if (Object.getOwnPropertyNames) {
var proto = scope.constructor.prototype;
Object.getOwnPropertyNames(proto).forEach(function(methodName) {
var original = scope[methodName];
if (typeof original === 'function' && isExcluded(methodName) && methods.indexOf(methodName) === -1) {
scope[methodName] = function () {
// test whether the scope is different
if (this !== scope) {
var e = 'Warning: Method "' + methodName + '" of "' + componentName + '" is not bound. Bad you!';
console.error(e);
}
return original.apply(scope, arguments);
};
}
});
}
// }
}
module.exports = bindToClass;
| var excludeMethods = [
/^constructor$/,
/^render$/,
/^component[A-Za-z]+$/,
/^shouldComponentUpdate$/
];
var displayNameReg = /^function\s+([a-zA-Z]+)/;
function isExcluded(methodName) {
return excludeMethods.some(function (reg) {
return reg.test(methodName) === false;
});
}
function bindToClass(scope, methods) {
var componentName = scope.constructor.toString().match(displayNameReg)[1];
methods = Array.isArray(methods) ? methods : [];
methods.forEach(function(methodName) {
if (methodName in scope) {
scope[methodName] = scope[methodName].bind(scope);
} else {
throw new Error('Method "' + methodName + '" does not exists in "' + componentName + '"');
}
});
// for debugging purposes only?
// if (process.env.NODE_ENV != 'production') {
if (Object.getOwnPropertyNames) {
var proto = scope.constructor.prototype;
Object.getOwnPropertyNames(proto).forEach(function(methodName) {
var original = scope[methodName];
if (typeof original === 'function' && isExcluded(methodName) && methods.indexOf(methodName) === -1) {
scope[methodName] = function () {
// test whether the scope is different
if (this !== scope) {
var e = 'Warning: Method "' + methodName + '" of "' + componentName + '" is not bound. Bad you!';
console.error(e);
}
return original.apply(scope, arguments);
};
}
});
}
// }
}
module.exports = bindToClass;
|
Add webargs requirement, and sort requirements. | import re
import subprocess
from setuptools import setup
def _get_git_description():
try:
return subprocess.check_output(["git", "describe"]).decode("utf-8").strip()
except subprocess.CalledProcessError:
return None
def get_version():
description = _get_git_description()
match = re.match(r'(?P<tag>[\d\.]+)-(?P<offset>[\d]+)-(?P<sha>\w{8})', description)
if match:
version = "{tag}.post{offset}".format(**match.groupdict())
else:
version = description
return version
def main():
setup(
name="workwork",
url="https://github.com/DoWhileGeek/workwork",
description="A flask api for managing aws ec2 instances",
license="MIT License",
author="Joeseph Rodrigues",
author_email="[email protected]",
version=get_version(),
packages=["workwork", ],
package_data={"workwork": ["workwork/*"], },
include_package_data=True,
install_requires=[
"boto3==1.2.3",
"Flask==0.10.1",
"webargs==1.2.0",
],
extras_require={
"develop": [
"pytest==2.8.7",
],
},
)
if __name__ == "__main__":
main()
| import re
import subprocess
from setuptools import setup
def _get_git_description():
try:
return subprocess.check_output(["git", "describe"]).decode("utf-8").strip()
except subprocess.CalledProcessError:
return None
def get_version():
description = _get_git_description()
match = re.match(r'(?P<tag>[\d\.]+)-(?P<offset>[\d]+)-(?P<sha>\w{8})', description)
if match:
version = "{tag}.post{offset}".format(**match.groupdict())
else:
version = description
return version
def main():
setup(
name="workwork",
url="https://github.com/DoWhileGeek/workwork",
description="A flask api for managing aws ec2 instances",
license="MIT License",
author="Joeseph Rodrigues",
author_email="[email protected]",
version=get_version(),
packages=["workwork", ],
package_data={"workwork": ["workwork/*"], },
include_package_data=True,
install_requires=[
"Flask==0.10.1",
"boto3==1.2.3",
],
extras_require={
"develop": [
"pytest==2.8.7",
],
},
)
if __name__ == "__main__":
main()
|
Fix use of request service. | <?php
namespace Kula\Core\Bundle\FrameworkBundle\EventListener;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Exception\FlattenException;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
class AuthenticatedUserListener implements EventSubscriberInterface {
private $router;
private $container;
public function __construct($router, $container) {
$this->router = $router;
$this->container = $container;
}
public static function getSubscribedEvents() {
return array(
KernelEvents::REQUEST => array('onKernelRequest', 0),
);
}
public function onKernelRequest(GetResponseEvent $event) {
if ($this->container->get('session')->get('user_id') > 0 AND $this->container->get('session')->get('portal') == 'core' ) {
$routeName = $this->container->get('request_stack')->getCurrentRequest()->get('_route');
if ($routeName != 'core_home' AND $routeName == 'top') {
$event->setResponse(new RedirectResponse($this->router->generate('sis_home')));
}
}
}
} | <?php
namespace Kula\Core\Bundle\FrameworkBundle\EventListener;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Exception\FlattenException;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
class AuthenticatedUserListener implements EventSubscriberInterface {
private $router;
private $container;
public function __construct($router, $container) {
$this->router = $router;
$this->container = $container;
}
public static function getSubscribedEvents() {
return array(
KernelEvents::REQUEST => array('onKernelRequest', 0),
);
}
public function onKernelRequest(GetResponseEvent $event) {
if ($this->container->get('session')->get('user_id') > 0 AND $this->container->get('session')->get('portal') == 'core' ) {
$routeName = $this->container->get('request')->get('_route');
if ($routeName != 'core_home' AND $routeName == 'top') {
$event->setResponse(new RedirectResponse($this->router->generate('sis_home')));
}
}
}
} |
Add timeout config parameter with a default of 20 seconds | import logging
import requests
logger = logging.getLogger(__name__)
class APIError(Exception):
pass
class BaseService(object):
def __init__(self, api, **config):
self.api = api
self.requester = requests.session()
self.config = {
'base_url': 'http://data.police.uk/api/',
}
self.config.update(config)
self.set_credentials(self.config.get('username'),
self.config.get('password'))
def set_credentials(self, username, password):
if username and password:
self.requester.auth = (username, password)
def raise_for_status(self, request):
try:
request.raise_for_status()
except requests.models.HTTPError as e:
raise APIError(e)
def request(self, verb, method, **kwargs):
verb = verb.upper()
request_kwargs = {
'timeout': self.config.get('timeout', 20),
}
if verb == 'GET':
request_kwargs['params'] = kwargs
else:
request_kwargs['data'] = kwargs
url = self.config['base_url'] + method
logger.debug('%s %s' % (verb, url))
r = self.requester.request(verb, url, **request_kwargs)
self.raise_for_status(r)
return r.json()
| import logging
import requests
logger = logging.getLogger(__name__)
class APIError(Exception):
pass
class BaseService(object):
def __init__(self, api, **config):
self.api = api
self.requester = requests.session()
self.config = {
'base_url': 'http://data.police.uk/api/',
}
self.config.update(config)
self.set_credentials(self.config.get('username'),
self.config.get('password'))
def set_credentials(self, username, password):
if username and password:
self.requester.auth = (username, password)
def raise_for_status(self, request):
try:
request.raise_for_status()
except requests.models.HTTPError as e:
raise APIError(e)
def request(self, verb, method, **kwargs):
verb = verb.upper()
request_kwargs = {}
if verb == 'GET':
request_kwargs['params'] = kwargs
else:
request_kwargs['data'] = kwargs
url = self.config['base_url'] + method
logger.debug('%s %s' % (verb, url))
r = self.requester.request(verb, url, **request_kwargs)
self.raise_for_status(r)
return r.json()
|
Allow plugins to manage multiple properties | 'use strict';
var module = angular.module('kheoApp');
module.controller('ServerDetailCtrl', ['$scope', '$resource', '$routeParams', 'configuration', '_', function ($scope, $resource, $routeParams, configuration, _) {
$scope.privateCount = 0;
$scope.server = $resource(configuration.backend + '/servers/' + $routeParams.hostname).get();
$scope.plugins = $resource(configuration.backend + '/plugins').query();
$scope.pluginProperties = [];
$scope.filterPluginProperties = function(plugin) {
$scope.pluginProperties = _.filter($scope.server.serverProperties, function(property) {
return _.contains(plugin.propertiesNames, property.type);
});
};
$scope.getKeys = function(property) {
return _.reject(_.keys(property), function(element) {
return element === 'type' || element === '$$hashKey' || element === 'key' || element === '@kheo-type';
});
};
$scope.stringValue = function(obj) {
if(obj === null) {
return 'no value';
}
var value = _.map(_.filter(_.keys(obj), function(item) {
return item !== 'type' && item !== '@kheo-type';
}), function(item) {
return item + '=' + obj[item];
});
return value.join(', ');
};
$scope.getEventAlignment = function() {
$scope.privateCount = $scope.privateCount+1;
return $scope.privateCount % 2 == 0 ? 'left' : 'right';
}
}]);
| 'use strict';
var module = angular.module('kheoApp');
module.controller('ServerDetailCtrl', ['$scope', '$resource', '$routeParams', 'configuration', '_', function ($scope, $resource, $routeParams, configuration, _) {
$scope.privateCount = 0;
$scope.server = $resource(configuration.backend + '/servers/' + $routeParams.hostname).get();
$scope.plugins = $resource(configuration.backend + '/plugins').query();
$scope.pluginProperties = [];
$scope.filterPluginProperties = function(plugin) {
$scope.pluginProperties = _.filter($scope.server.serverProperties, function(property) {
return property.type === plugin.propertyName;
});
};
$scope.getKeys = function(property) {
console.log(property)
return _.reject(_.keys(property), function(element) {
return element === 'type' || element === '$$hashKey' || element === 'key' || element === '@kheo-type';
});
};
$scope.stringValue = function(obj) {
if(obj === null) {
return 'no value';
}
var value = _.map(_.filter(_.keys(obj), function(item) {
return item !== 'type' && item !== '@kheo-type';
}), function(item) {
return item + '=' + obj[item];
});
return value.join(', ');
};
$scope.getEventAlignment = function() {
console.log($scope.privateCount);
$scope.privateCount = $scope.privateCount+1;
return $scope.privateCount % 2 == 0 ? 'left' : 'right';
}
}]);
|
Fix error message on fetching in todo detail page | import React from 'react'
import { provideHooks } from 'redial'
import { reduxForm } from 'redux-form'
import Loader from 'react-loaders'
import { viewTodo } from '../actions';
import { connect } from 'react-redux';
import { TodoUpdateForm } from './TodoForm';
import { Link } from 'react-router'
@provideHooks({
fetch: ({ dispatch, params: { id }, store }) => dispatch(
viewTodo({
id: id,
reject: (e) => {alert(e);},
store
}))
})
@connect((state) => {
return {
viewedTodo: state.todo.viewedTodo,
fetchState: state.todo.fetchState,
};
})
export default class TodoDetail extends React.Component {
render() {
const { viewedTodo, fetchState, history } = this.props;
if (fetchState[viewTodo].fetching) {
return (
<div className="todo-detail">
<div key="loader" className="loader">
<Loader type="line-scale" active="true"/>
</div>
</div>
)
}
if (!viewedTodo) {
return <div className="todo-detail"/>
}
return(
<div className="todo-detail">
<Link className="back-link" to={"/todos"}>{"< Back"}</Link>
<h1>{viewedTodo.title}</h1>
<hr />
<TodoUpdateForm history={history}/>
</div>
)
}
}
| import React from 'react'
import { provideHooks } from 'redial'
import { reduxForm } from 'redux-form'
import Loader from 'react-loaders'
import { viewTodo } from '../actions';
import { connect } from 'react-redux';
import { TodoUpdateForm } from './TodoForm';
import { Link } from 'react-router'
@provideHooks({
fetch: ({ dispatch, params: { id }, store }) => dispatch(
viewTodo({
id: id,
reject: (e) => {alert(e.message);},
store
}))
})
@connect((state) => {
return {
viewedTodo: state.todo.viewedTodo,
fetchState: state.todo.fetchState,
};
})
export default class TodoDetail extends React.Component {
render() {
const { viewedTodo, fetchState, history } = this.props;
if (fetchState[viewTodo].fetching) {
return (
<div className="todo-detail">
<div key="loader" className="loader">
<Loader type="line-scale" active="true"/>
</div>
</div>
)
}
if (!viewedTodo) {
return <div className="todo-detail"/>
}
return(
<div className="todo-detail">
<Link className="back-link" to={"/todos"}>{"< Back"}</Link>
<h1>{viewedTodo.title}</h1>
<hr />
<TodoUpdateForm history={history}/>
</div>
)
}
}
|
Add wrapper functions to deal with EINTR and exceptions in dispatched-to-functions | #!/usr/bin/python
import ctypes
import errno
import os
import select
import traceback
import cepoll
import ctimerfd
def on_timer ():
pass
def eintr_wrap (fn, *args, **kwargs):
while True:
try:
return fn (*args, **kwargs)
except IOError, e:
if e.errno == errno.EINTR:
continue
raise
def wrap (fn, *args, **kwargs):
try:
fn (*args, **kwargs)
except:
traceback.print_exc ()
def main ():
spec = ctimerfd.itimerspec ()
spec.it_interval.tv_sec = 0
spec.it_interval.tv_nsec = long (1e9/60)
spec.it_value.tv_sec = 0
spec.it_value.tv_nsec = 1
t = ctimerfd.timerfd_create (ctimerfd.CLOCK_MONOTONIC, ctimerfd.TFD_CLOEXEC|ctimerfd.TFD_NONBLOCK)
ctimerfd.timerfd_settime (t, 0, ctypes.pointer (spec), None)
epoll = select.epoll.fromfd (cepoll.epoll_create (cepoll.EPOLL_CLOEXEC))
epoll.register (t, select.EPOLLIN)
while True:
for fd, event in eintr_wrap (epoll.poll):
if fd == t:
os.read (t, 8)
wrap (on_timer)
if __name__ == '__main__':
main ()
| #!/usr/bin/python
import ctypes
import errno
import os
import select
import traceback
import cepoll
import ctimerfd
def on_timer ():
pass
def main ():
spec = ctimerfd.itimerspec ()
spec.it_interval.tv_sec = 0
spec.it_interval.tv_nsec = long (1e9/60)
spec.it_value.tv_sec = 0
spec.it_value.tv_nsec = 1
t = ctimerfd.timerfd_create (ctimerfd.CLOCK_MONOTONIC, ctimerfd.TFD_CLOEXEC|ctimerfd.TFD_NONBLOCK)
ctimerfd.timerfd_settime (t, 0, ctypes.pointer (spec), None)
poll = select.epoll.fromfd (cepoll.epoll_create (cepoll.EPOLL_CLOEXEC))
poll.register (t, select.EPOLLIN)
while True:
try:
for fd, event in poll.poll ():
try:
if fd == t:
on_timer ()
except:
traceback.print_exc ()
except IOError, e:
if e.errno == errno.EINTR:
continue
raise
if __name__ == '__main__':
main ()
|
Add cache buster to bundle.js | import React from 'react'
import DocumentTitle from 'react-document-title'
import { prefixLink } from 'gatsby-helpers'
import { TypographyStyle } from 'utils/typography'
const BUILD_TIME = new Date().getTime()
module.exports = React.createClass({
propTypes () {
return {
title: React.PropTypes.string,
}
},
render () {
const title = DocumentTitle.rewind()
let cssLink
if (process.env.NODE_ENV === 'production') {
cssLink = <link rel="stylesheet" href={prefixLink('/styles.css')} />
}
return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta httpEquiv="X-UA-Compatible" content="IE=edge" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0 maximum-scale=1.0"
/>
<title>{title}</title>
<link rel="shortcut icon" href={this.props.favicon} />
<TypographyStyle />
{cssLink}
</head>
<body>
<div id="react-mount" dangerouslySetInnerHTML={{ __html: this.props.body }} />
<script src={prefixLink(`/bundle.js?t=${BUILD_TIME}`)} />
</body>
</html>
)
},
})
| import React from 'react'
import DocumentTitle from 'react-document-title'
import { prefixLink } from 'gatsby-helpers'
import { TypographyStyle } from 'utils/typography'
module.exports = React.createClass({
propTypes () {
return {
title: React.PropTypes.string,
}
},
render () {
const title = DocumentTitle.rewind()
let cssLink
if (process.env.NODE_ENV === 'production') {
cssLink = <link rel="stylesheet" href={prefixLink('/styles.css')} />
}
return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta httpEquiv="X-UA-Compatible" content="IE=edge" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0 maximum-scale=1.0"
/>
<title>{title}</title>
<link rel="shortcut icon" href={this.props.favicon} />
<TypographyStyle />
{cssLink}
</head>
<body>
<div id="react-mount" dangerouslySetInnerHTML={{ __html: this.props.body }} />
<script src={prefixLink('/bundle.js')} />
</body>
</html>
)
},
})
|
Enforce consistent results for generated code | # Copyright 2008 Paul Hodge
import os, string
def run(functionsDirectory, outputFilename):
print "dir is: " +functionsDirectory
files = os.listdir(functionsDirectory)
functionNames = []
for file in files:
if file.endswith('.cpp'):
function_name = os.path.split(file)[1][:-4]
functionNames.append(function_name)
#print "added "+function_name
def makeNamespace(functionName):
return functionName.replace('-','_')+"_function"
namespaces = map(makeNamespace, functionNames)
def makePredeclaration(namespace):
return "namespace "+namespace+" { void setup(Branch& kernel); }"
def makeCall(namespace):
return namespace+"::setup(kernel);"
predeclarations = map(makePredeclaration, namespaces)
calls = map(makeCall, namespaces)
predeclarations.sort()
calls.sort()
output = string.Template(TEMPLATE).substitute({
'predeclarations':"\n".join(predeclarations),
'calls':"\n ".join(calls)})
output_file = open(outputFilename, 'w')
output_file.write(output)
output_file.close()
TEMPLATE = """
// Copyright 2008 Paul Hodge
#include "common_headers.h"
#include "branch.h"
namespace circa {
$predeclarations
void setup_builtin_functions(Branch& kernel)
{
$calls
}
} // namespace circa
"""
if __name__ == "__main__":
run("../src/builtin_functions", "../src/setup_builtin_functions.cpp")
| # Copyright 2008 Paul Hodge
import os, string
def run(functionsDirectory, outputFilename):
print "dir is: " +functionsDirectory
files = os.listdir(functionsDirectory)
functionNames = []
for file in files:
if file.endswith('.cpp'):
function_name = os.path.split(file)[1][:-4]
functionNames.append(function_name)
#print "added "+function_name
def makeNamespace(functionName):
return functionName.replace('-','_')+"_function"
namespaces = map(makeNamespace, functionNames)
def makePredeclaration(namespace):
return "namespace "+namespace+" { void setup(Branch& kernel); }"
def makeCall(namespace):
return namespace+"::setup(kernel);"
predeclarations = map(makePredeclaration, namespaces)
calls = map(makeCall, namespaces)
output = string.Template(TEMPLATE).substitute({
'predeclarations':"\n".join(predeclarations),
'calls':"\n ".join(calls)})
output_file = open(outputFilename, 'w')
output_file.write(output)
output_file.close()
TEMPLATE = """
// Copyright 2008 Paul Hodge
#include "common_headers.h"
#include "branch.h"
namespace circa {
$predeclarations
void setup_builtin_functions(Branch& kernel)
{
$calls
}
} // namespace circa
"""
if __name__ == "__main__":
run("../src/builtin_functions", "../src/setup_builtin_functions.cpp")
|
Set application title in titlebar. | package net.cdahmedeh.ultimeter.ui.main;
import net.cdahmedeh.ultimeter.persistence.dao.TodoManager;
import net.cdahmedeh.ultimeter.persistence.manager.PersistenceManager;
import net.cdahmedeh.ultimeter.ui.controller.TodoController;
import net.cdahmedeh.ultimeter.ui.view.TodoView;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
/**
* This class starts the Ultimeter UI.
*
* @author Ahmed El-Hajjar
*
*/
public class Ultimeter {
public static void main(String[] args) throws Exception {
// Prepare persistence utilities.
final PersistenceManager persistenceManager = new PersistenceManager();
final TodoManager todoManager = new TodoManager(persistenceManager);
// Prepare controllers
final TodoController todoController = new TodoController(todoManager);
// Create the UI display
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setText("Ultimeter - Time Management System");
shell.setLayout(new FillLayout());
// Create Views
@SuppressWarnings("unused")
final TodoView todoView = new TodoView(shell, todoController);
// Display the UI
shell.open();
// Start event loop
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
// Clean up.
display.dispose();
}
}
| package net.cdahmedeh.ultimeter.ui.main;
import net.cdahmedeh.ultimeter.persistence.dao.TodoManager;
import net.cdahmedeh.ultimeter.persistence.manager.PersistenceManager;
import net.cdahmedeh.ultimeter.ui.controller.TodoController;
import net.cdahmedeh.ultimeter.ui.view.TodoView;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
/**
* This class starts the Ultimeter UI.
*
* @author Ahmed El-Hajjar
*
*/
public class Ultimeter {
public static void main(String[] args) throws Exception {
// Prepare persistence utilities.
final PersistenceManager persistenceManager = new PersistenceManager();
final TodoManager todoManager = new TodoManager(persistenceManager);
// Prepare controllers
final TodoController todoController = new TodoController(todoManager);
// Create the UI display
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
// Create Views
@SuppressWarnings("unused")
final TodoView todoView = new TodoView(shell, todoController);
// Display the UI
shell.open();
// Start event loop
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
// Clean up.
display.dispose();
}
}
|
Add support for command line parameters | 'use strict';
var cp = require('child_process');
var log = console.log;
module.exports = function (npmOptions) {
if (typeof npmOptions != 'string' && npmOptions.constructor !== Array) {
throw new Error('Parameter must be an array or a single string!')
}
npmOptions = [].concat(npmOptions);
module.constructor.prototype.require = function (path) {
var self = this;
try {
return self.constructor._load(path, self);
} catch (e) {
if (e.code !== 'MODULE_NOT_FOUND') {
// Bail out, something went seriously wrong here!
throw e;
}
// Trying to import local file, not much we can help with here!
else if (path.charAt(0) === '.' || path.charAt(0) === '/' ) {
log('Local module at path ' + path + ' was not found!')
throw e;
}
else {
log('Looks like module ' + path + ' was not found! Installing...');
var cmdParameters = npmOptions.join(' ');
console.log(cmdParameters);
var results = cp.execSync('npm i ' + cmdParameters + ' ' + path, {stdio : [0, 1, 2]})
if (results && results.err) {
throw results.err;
} else {
return self.constructor._load(path, self);
}
}
}
}
}
| 'use strict';
var cp = require('child_process');
var log = console.log;
module.exports = function () {
module.constructor.prototype.require = function (path) {
var self = this;
try {
return self.constructor._load(path, self);
} catch (e) {
if (e.code !== 'MODULE_NOT_FOUND') {
// Bail out, something went seriously wrong here!
throw e;
}
// Trying to import local file, not much we can help with here!
else if (path.charAt(0) === '.' || path.charAt(0) === '/' ) {
log('Local module at path ' + path + ' was not found!')
throw e;
}
else {
log('Looks like module ' + path + ' was not found! Installing...');
var results = cp.execSync('npm i ' + path, {stdio : [0, 1, 2]})
if (results && results.err) {
throw results.err;
} else {
return self.constructor._load(path, self);
}
}
}
}
}
|
Update Java segmenter to use the same formula as the C version. | package talkhouse;
public class Segmenter {
private double[] buf=null;
int winsz;
int winshift;
static final int MIN_SEGMENTS = 3;
public Segmenter(int winsz, int winshift) {
this.winsz = winsz;
this.winshift = winshift;
}
public double[][] apply(double[] data) {
double[] combo;
if (buf != null) {
combo = new double[buf.length + data.length];
System.arraycopy(buf, 0, combo, 0, buf.length);
System.arraycopy(data, 0, combo, buf.length, data.length);
} else {
combo = data;
}
if (combo.length < winsz + winshift * MIN_SEGMENTS){
buf = combo;
return null;
} else {
buf = null;
}
int rows = (combo.length - combo.length % winshift - winsz +
winshift)/ winshift;
double[][] result = new double[rows][];
for (int i=0;i<rows;++i) {
double[] seg = new double[winsz];
System.arraycopy(combo, i*winshift, seg, 0, winsz);
result[i] = seg;
}
int bufsize = combo.length - rows * winshift;
if (bufsize > 0) {
if (buf == null || buf.length != bufsize) {
buf = new double[bufsize];
}
System.arraycopy(combo, combo.length - bufsize, buf, 0, bufsize);
} else {
buf = null;
}
return result;
}
};
| package talkhouse;
public class Segmenter {
private double[] buf=null;
int winsz;
int winshift;
static final int MIN_SEGMENTS = 3;
public Segmenter(int winsz, int winshift) {
this.winsz = winsz;
this.winshift = winshift;
}
public double[][] apply(double[] data) {
double[] combo;
if (buf != null) {
combo = new double[buf.length + data.length];
System.arraycopy(buf, 0, combo, 0, buf.length);
System.arraycopy(data, 0, combo, buf.length, data.length);
} else {
combo = data;
}
if (combo.length < winsz + winshift * MIN_SEGMENTS){
buf = combo;
return null;
} else {
buf = null;
}
double[][] result = new double[(combo.length-winsz)/winshift+1][];
int i = 0;
int j=0;
while (i+winsz <= combo.length) {
double[] seg = new double[winsz];
System.arraycopy(combo, i, seg, 0, winsz);
result[j++] = seg;
i+=winshift;
}
int bufsize = combo.length - i;
if (bufsize > 0) {
if (buf == null || buf.length != bufsize) {
buf = new double[bufsize];
}
System.arraycopy(combo, combo.length - bufsize, buf, 0, bufsize);
} else {
buf = null;
}
return result;
}
};
|
Align validation. Only allow one response. Fix variable name, Include hash key in row insertion | 'use strict';
const AWS = require('aws-sdk');
const dynamoDb = new AWS.DynamoDB.DocumentClient();
const validateResponses = function(responsesList) {
if (!(Array.isArray(responsesList))) return false;
for (var i=0; i < responsesList.length; i++) {
if (typeof responsesList[i].question !== 'string' ||
typeof responsesList[i].response !== 'string' ) return false;
}
return true;
}
module.exports.create = (event, context, callback) => {
const timestamp = new Date().getTime();
const data = JSON.parse(event.body);
if (typeof data.surveyId !== 'number' || !(validateResponses(data.responses))
|| typeof data.id !== 'number') {
console.error('Validation Failed');
callback(new Error('Could not create survey response'));
return;
}
const params = {
TableName: process.env.RESPONSES_TABLE,
Item: {
id: data.id,
surveyId: data.surveyId,
MapAttribute: data.responses,
createdAt: timestamp,
updatedAt: timestamp
},
ConditionExpression: 'attribute_not_exists(surveyId)'
};
dynamoDb.put(params, (error, result) => {
if (error) {
console.error(error);
callback(new Error('Could not create survey response'));
return;
}
const response = {
statusCode: 200,
body: JSON.stringify(params.Item),
};
callback(null, response);
});
};
| 'use strict';
const AWS = require('aws-sdk');
const dynamoDb = new AWS.DynamoDB.DocumentClient();
const validateResponses = function(responsesList) {
if (!(Array.isArray(questionList))) return false;
for (var i=0; i < responsesList.length; i++) {
if (typeof responsesList[i].question !== 'string' ||
!(Array.isArray(responsesList[i].answers)) ) return false;
for (var j=0; j < responsesList[i].answers.length; j++) {
if (typeof responsesList[i].answers[j] !== 'string') return false;
}
}
return true;
}
module.exports.create = (event, context, callback) => {
const timestamp = new Date().getTime();
const data = JSON.parse(event.body);
if (typeof data.surveyId !== 'number' || !(validateResponses(data.responses))) {
console.error('Validation Failed');
callback(new Error('Could not create survey response'));
return;
}
const params = {
TableName: process.env.RESPONSES_TABLE,
Item: {
surveyId: data.surveyId,
MapAttribute: data.responses,
createdAt: timestamp,
updatedAt: timestamp
},
ConditionExpression: 'attribute_not_exists(surveyId)'
};
dynamoDb.put(params, (error, result) => {
if (error) {
console.error(error);
callback(new Error('Could not create survey response'));
return;
}
const response = {
statusCode: 200,
body: JSON.stringify(params.Item),
};
callback(null, response);
});
};
|
Make sure the attribute key exists before setting it | <?php
namespace PHPushbullet;
class Device
{
/**
* The fields that we want to retrieve for the device
*
* @var array $fields
*/
protected $fields = [
'nickname',
'iden',
'model',
'type',
'active',
'pushable',
'manufacturer',
'created',
];
public function __construct(array $attr)
{
foreach ($this->fields as $field) {
$method = 'set' . ucwords($field);
if (method_exists($this, $method)) {
// If there is a setter for this field, use that
$this->$field = $this->$method($attr[$field]);
} else {
// Otherwise just set the property
$this->$field = isset($attr[$field]) ? $attr[$field] : null;
}
}
}
/**
* Format the date so that it's readable
*
* @param integer $date
* @return string
*/
protected function setCreated($date)
{
return date('Y-m-d h:i:sA T', $date);
}
}
| <?php
namespace PHPushbullet;
class Device
{
/**
* The fields that we want to retrieve for the device
*
* @var array $fields
*/
protected $fields = [
'nickname',
'iden',
'model',
'type',
'active',
'pushable',
'manufacturer',
'created',
];
public function __construct(array $attr)
{
foreach ($this->fields as $field) {
$method = 'set' . ucwords($field);
if (method_exists($this, $method)) {
// If there is a setter for this field, use that
$this->$field = $this->$method($attr[$field]);
} else {
// Otherwise just set the property
$this->$field = $attr[$field];
}
}
}
/**
* Format the date so that it's readable
*
* @param integer $date
* @return string
*/
protected function setCreated($date)
{
return date('Y-m-d h:i:sA T', $date);
}
}
|
Set unique together on news article. | """Models used by the news publication application."""
from django.db import models
from cms.apps.pages.models import Page, PageBase, PageField, HtmlField
from cms.apps.news.content import NewsFeed, NewsArticle
class Article(PageBase):
"""A news article."""
news_feed = PageField(Page,
"newsfeed")
content = HtmlField(blank=True,
null=True)
summary = models.TextField(blank=True,
null=True,
help_text="A short summary of this article. This will be used on news pages and RSS feeds. If not specified, then a summarized version of the content will be used.")
is_featured = models.BooleanField("featured",
default=False,
help_text="Featured articles will remain at the top of any news feeds.")
def get_absolute_url(self):
"""Returns the absolute URL of the article."""
return self.parent.content.reverse("article_detail", self.publication_date.year, self.publication_date.month, self.url_title, "")
class Meta:
verbose_name = "news article"
unique_together = (("news_feed", "url_title",),)
Page.register_content(NewsFeed)
| """Models used by the news publication application."""
from django.db import models
from cms.apps.pages.models import Page, PageBase, PageField, HtmlField
from cms.apps.news.content import NewsFeed, NewsArticle
class Article(PageBase):
"""A news article."""
news_feed = PageField(Page,
"newsfeed")
content = HtmlField(blank=True,
null=True)
summary = models.TextField(blank=True,
null=True,
help_text="A short summary of this article. This will be used on news pages and RSS feeds. If not specified, then a summarized version of the content will be used.")
is_featured = models.BooleanField("featured",
default=False,
help_text="Featured articles will remain at the top of any news feeds.")
def get_absolute_url(self):
"""Returns the absolute URL of the article."""
return self.parent.content.reverse("article_detail", self.publication_date.year, self.publication_date.month, self.url_title, "")
class Meta:
verbose_name = "news article"
Page.register_content(NewsFeed)
|
Update YUI error handling logic |
from collections import OrderedDict
import os
import StringIO
from django.conf import settings
from django.utils.encoding import smart_str
from ..base import Processor
ERROR_STRING = ("Failed to execute Java VM or yuicompressor. "
"Please make sure that you have installed Java "
"and that it's in your PATH and that you've configured "
"YUICOMPRESSOR_PATH in your settings correctly.\n"
"Error was: %s")
class YUI(Processor):
def process(self, inputs):
from subprocess import Popen, PIPE
outputs = OrderedDict()
compressor = settings.YUI_COMPRESSOR_BINARY
for filename, contents in inputs.items():
filetype = os.path.splitext(filename)[-1].lstrip(".")
try:
cmd = Popen([
'java', '-jar', compressor,
'--charset', 'utf-8', '--type', filetype],
stdin=PIPE, stdout=PIPE, stderr=PIPE,
universal_newlines=True
)
output, error = cmd.communicate(smart_str(contents.read()))
except Exception, e:
raise ValueError(ERROR_STRING % e)
if error != '':
raise ValueError(ERROR_STRING % error)
file_out = StringIO.StringIO()
file_out.write(output)
file_out.seek(0)
outputs[filename] = file_out
return outputs
|
from collections import OrderedDict
import os
import StringIO
from django.conf import settings
from django.utils.encoding import smart_str
from ..base import Processor
ERROR_STRING = ("Failed to execute Java VM or yuicompressor. "
"Please make sure that you have installed Java "
"and that it's in your PATH and that you've configured "
"YUICOMPRESSOR_PATH in your settings correctly.\n"
"Error was: %s")
class YUI(Processor):
def process(self, inputs):
from subprocess import Popen, PIPE
outputs = OrderedDict()
compressor = settings.YUI_COMPRESSOR_BINARY
try:
for filename, contents in inputs.items():
filetype = os.path.splitext(filename)[-1].lstrip(".")
cmd = Popen([
'java', '-jar', compressor,
'--charset', 'utf-8', '--type', filetype],
stdin=PIPE, stdout=PIPE, stderr=PIPE,
universal_newlines=True
)
output, error = cmd.communicate(smart_str(contents.read()))
if error != '':
raise ValueError(ERROR_STRING % error)
file_out = StringIO.StringIO()
file_out.write(output)
file_out.seek(0)
outputs[filename] = file_out
except Exception, e:
raise ValueError(ERROR_STRING % e)
return outputs
|
Fix bug with inner reset time | var Store = module.exports = function () {
};
Store.prototype.hit = function (req, configuration, callback) {
var self = this;
var ip = req.ip;
var path;
if (configuration.pathLimiter) {
path = (req.baseUrl) ? req.baseUrl.replace(req.path, '') : '';
ip += configuration.path || path;
}
var now = Date.now();
self.get(ip, function (err, limit) {
if (err) {
callback(err, undefined, now);
return;
};
if (limit) {
//Existing user
var limitDate = limit.date;
var timeLimit = limitDate + configuration.innerTimeLimit;
var resetInner = now > timeLimit;
if (resetInner) {
limit.date = now;
}
self.decreaseLimits(ip, limit, resetInner, configuration, function (error, result) {
callback(error, result, limitDate);
});
} else {
//New User
var outerReset = Math.floor((now + configuration.outerTimeLimit) / 1000);
limit = {
date: now,
inner: configuration.innerLimit,
outer: configuration.outerLimit,
firstDate: now,
outerReset: outerReset
};
self.create(ip, limit, configuration, function (error, result) {
callback(error, result, now);
});
}
}, configuration);
}
| var Store = module.exports = function () {
};
Store.prototype.hit = function (req, configuration, callback) {
var self = this;
var ip = req.ip;
var path;
if (configuration.pathLimiter) {
path = (req.baseUrl) ? req.baseUrl.replace(req.path, '') : '';
ip += configuration.path || path;
}
var now = Date.now();
self.get(ip, function (err, limit) {
if (err) {
callback(err, undefined, now);
return;
};
if (limit) {
//Existing user
var limitDate = limit.date;
var timeLimit = limitDate + configuration.innerTimeLimit;
var resetInner = now > timeLimit;
limit.date = now;
self.decreaseLimits(ip, limit, resetInner, configuration, function (error, result) {
callback(error, result, limitDate);
});
} else {
//New User
var outerReset = Math.floor((now + configuration.outerTimeLimit) / 1000);
limit = {
date: now,
inner: configuration.innerLimit,
outer: configuration.outerLimit,
firstDate: now,
outerReset: outerReset
};
self.create(ip, limit, configuration, function (error, result) {
callback(error, result, now);
});
}
}, configuration);
}
|
Fix type in property name variable | <?php
namespace PhpSpec\Util;
use ReflectionClass;
use ReflectionProperty;
class Instantiator
{
public function instantiate($className)
{
return unserialize($this->createSerializedObject($className));
}
private function createSerializedObject($className)
{
$reflection = new ReflectionClass($className);
$properties = $reflection->getProperties();
return "O:" . strlen($className) . ":\"$className\":" . count($properties) .
':{' . $this->serializeProperties($reflection, $properties) ."}";
}
private function serializeProperties(ReflectionClass $reflection, array $properties)
{
$serializedProperties = '';
foreach ($properties as $property) {
$serializedProperties .= $this->serializePropertyName($property);
$serializedProperties .= $this->serializePropertyValue($reflection, $property);
}
return $serializedProperties;
}
private function serializePropertyName(ReflectionProperty $property)
{
$propertyName = $property->getName();
if ($property->isProtected()) {
$propertyName = chr(0) . '*' . chr(0) . $propertyName;
} elseif ($property->isPrivate()) {
$propertyName = chr(0) . $class . chr(0) . $propertyName;
}
return serialize($propertyName);
}
private function serializePropertyValue(ReflectionClass $class, ReflectionProperty $property)
{
if (array_key_exists($property->getName(), $class->getDefaultProperties())) {
return serialize($defaults[$property->getName()]);
}
return serialize(null);
}
}
| <?php
namespace PhpSpec\Util;
use ReflectionClass;
use ReflectionProperty;
class Instantiator
{
public function instantiate($className)
{
return unserialize($this->createSerializedObject($className));
}
private function createSerializedObject($className)
{
$reflection = new ReflectionClass($className);
$properties = $reflection->getProperties();
return "O:" . strlen($className) . ":\"$className\":" . count($properties) .
':{' . $this->serializeProperties($reflection, $properties) ."}";
}
private function serializeProperties(ReflectionClass $reflection, array $properties)
{
$serializedProperties = '';
foreach ($properties as $property) {
$serializedProperties .= $this->serializePropertyName($property);
$serializedProperties .= $this->serializePropertyValue($reflection, $property);
}
return $serializedProperties;
}
private function serializePropertyName(ReflectionProperty $property)
{
$propertyName = $property->getName();
if ($property->isProtected()) {
$propertyName = chr(0) . '*' . chr(0) .$name;
} elseif ($property->isPrivate()) {
$propertyName = chr(0) . $class. chr(0).$name;
}
return serialize($propertyName);
}
private function serializePropertyValue(ReflectionClass $class, ReflectionProperty $property)
{
if (array_key_exists($property->getName(), $class->getDefaultProperties())) {
return serialize($defaults[$property->getName()]);
}
return serialize(null);
}
}
|
Fix mocha test (ts support) | 'use strict';
module.exports = {
// TODO: cache
transpile(src, filename, babelConfig, tsCompilerOptions) {
const babel = require('babel-core');
const tsc = require('typescript');
const gulpTsc = require('gulp-typescript');
const transformWithBabel = content =>
babel.transform(content, Object.assign({}, babelConfig, {
filename,
retainLines: true
})).code;
if (filename.indexOf('node_modules') !== -1) {
// skip node_modules
return src;
} else if (/\.tsx?$/.test(filename)) {
// use gulp-typescript to convert the settings for tsc
const tsProject = gulpTsc.createProject(Object.assign({}, tsCompilerOptions, {
typescript: tsc,
inlineSourceMap: true,
declaration: false
}));
return transformWithBabel(tsc.transpile(src, tsProject.options));
} else if (!babel.util.canCompile(filename)) {
// You might use a webpack loader in your project
// that allows you to load custom files (e.g. css, less, scss).
// Although it is working with webpack but jest
// don't know how to handle these files.
// You should never use these files unmocked
// otherwise you might encounter unexpected behavior.
// Changing the content of these files
// to return the raw content.
return `module.exports = ${JSON.stringify(src)}`;
}
return transformWithBabel(src);
}
};
| 'use strict';
module.exports = {
// TODO: cache
transpile(src, filename, babelConfig, tsCompilerOptions) {
const babel = require('babel-core');
const tsc = require('typescript');
const gulpTsc = require('gulp-typescript');
const transformWithBabel = content =>
babel.transform(content, Object.assign({}, babelConfig, {
filename,
retainLines: true
})).code;
if (filename.indexOf('node_modules') !== -1) {
// skip node_modules
return src;
} else if (/\.tsx?$/.test(filename)) {
// use gulp-typescript to convert the settings for tsc
const tsProject = gulpTsc.createProject(Object.assign({}, tsCompilerOptions, {
inlineSourceMap: true,
declaration: false
}));
return transformWithBabel(tsc.transpile(src, tsProject.options));
} else if (!babel.util.canCompile(filename)) {
// You might use a webpack loader in your project
// that allows you to load custom files (e.g. css, less, scss).
// Although it is working with webpack but jest
// don't know how to handle these files.
// You should never use these files unmocked
// otherwise you might encounter unexpected behavior.
// Changing the content of these files
// to return the raw content.
return `module.exports = ${JSON.stringify(src)}`;
}
return transformWithBabel(src);
}
};
|
Stop exposing asset_id in Hook Viewset | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import constance
from django.utils.translation import ugettext as _
from rest_framework import serializers
from rest_framework.reverse import reverse
from ..models.hook import Hook
class HookSerializer(serializers.ModelSerializer):
class Meta:
model = Hook
fields = ("url", "logs_url", "uid", "name", "endpoint", "active", "export_type",
"security_level", "success_count", "failed_count", "pending_count", "settings",
"date_modified", "email_notification", "subset_fields")
read_only_fields = ("asset", "uid", "date_modified", "success_count", "failed_count", "pending_count")
url = serializers.SerializerMethodField()
logs_url = serializers.SerializerMethodField()
def get_url(self, hook):
return reverse("hook-detail", args=(hook.asset.uid, hook.uid),
request=self.context.get("request", None))
def get_logs_url(self, hook):
return reverse("hook-log-list", args=(hook.asset.uid, hook.uid),
request=self.context.get("request", None))
def validate_endpoint(self, value):
"""
Check if endpoint is valid
"""
if not value.startswith("http"):
raise serializers.ValidationError(_("Invalid scheme"))
elif not constance.config.ALLOW_UNSECURED_HOOK_ENDPOINTS and \
value.startswith("http:"):
raise serializers.ValidationError(_("Unsecured endpoint is not allowed"))
return value | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import constance
from django.utils.translation import ugettext as _
from rest_framework import serializers
from rest_framework.reverse import reverse
from ..models.hook import Hook
class HookSerializer(serializers.ModelSerializer):
class Meta:
model = Hook
fields = ("url", "logs_url", "asset", "uid", "name", "endpoint", "active", "export_type",
"security_level", "success_count", "failed_count", "pending_count", "settings",
"date_modified", "email_notification", "subset_fields")
read_only_fields = ("asset", "uid", "date_modified", "success_count", "failed_count", "pending_count")
url = serializers.SerializerMethodField()
logs_url = serializers.SerializerMethodField()
def get_url(self, hook):
return reverse("hook-detail", args=(hook.asset.uid, hook.uid),
request=self.context.get("request", None))
def get_logs_url(self, hook):
return reverse("hook-log-list", args=(hook.asset.uid, hook.uid),
request=self.context.get("request", None))
def validate_endpoint(self, value):
"""
Check if endpoint is valid
"""
if not value.startswith("http"):
raise serializers.ValidationError(_("Invalid scheme"))
elif not constance.config.ALLOW_UNSECURED_HOOK_ENDPOINTS and \
value.startswith("http:"):
raise serializers.ValidationError(_("Unsecured endpoint is not allowed"))
return value |
Fix bug on initialization of controllers | <?php
namespace TaskManagement;
use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
use Zend\Mvc\MvcEvent;
use Zend\Stdlib\InitializableInterface;
class Module implements AutoloaderProviderInterface, ConfigProviderInterface
{
public function onBootstrap(MvcEvent $e)
{
$sm = $e->getApplication()->getServiceManager();
$controllers = $sm->get('ControllerLoader');
$controllers->addInitializer(function($controller, $cl) {
if ($controller instanceof InitializableInterface) {
$controller->init();
}
}, false); // false tells the loader to run this initializer after all others
}
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\ClassMapAutoloader' => array(
__DIR__ . '/autoload_classmap.php',
),
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
)
)
);
}
public function getServiceConfig()
{
return array (
'factories' => array (
'TaskManagement\ProjectService' => 'TaskManagement\Service\ProjectServiceFactory',
'TaskManagement\TaskService' => 'TaskManagement\Service\TaskServiceFactory'
),
);
}
} | <?php
namespace TaskManagement;
use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
class Module implements AutoloaderProviderInterface, ConfigProviderInterface
{
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\ClassMapAutoloader' => array(
__DIR__ . '/autoload_classmap.php',
),
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
)
)
);
}
public function getServiceConfig()
{
return array (
'factories' => array (
'TaskManagement\ProjectService' => 'TaskManagement\Service\ProjectServiceFactory',
'TaskManagement\TaskService' => 'TaskManagement\Service\TaskServiceFactory'
),
);
}
} |
Set RQ timeout when enqueuing | import logging
from django.conf import settings
from django.core.management.base import BaseCommand
from django.db import connection
from raven import Client
from ....tasks import enqueue
from ...models import UniqueFeed, Feed
from ...tasks import update_feed
from ...utils import FeedUpdater
logger = logging.getLogger('feedupdater')
class Command(BaseCommand):
"""Updates the users' feeds"""
def handle(self, *args, **kwargs):
if args:
pk = args[0]
feed = Feed.objects.get(pk=pk)
feed.etag = ''
return FeedUpdater(feed.url).update(use_etags=False)
# Making a list of unique URLs. Makes one call whatever the number of
# subscribers is.
urls = Feed.objects.filter(muted=False).values_list('url', flat=True)
unique_urls = {}
map(unique_urls.__setitem__, urls, [])
for url in unique_urls:
try:
try:
unique = UniqueFeed.objects.get(url=url)
if unique.should_update():
enqueue(update_feed, url, timeout=20)
except UniqueFeed.DoesNotExist:
enqueue(update_feed, url, timeout=20)
except Exception: # We don't know what to expect, and anyway
# we're reporting the exception
if settings.DEBUG or not hasattr(settings, 'SENTRY_DSN'):
raise
else:
client = Client(dsn=settings.SENTRY_DSN)
client.captureException()
connection.close()
| import logging
from django.conf import settings
from django.core.management.base import BaseCommand
from django.db import connection
from raven import Client
from ....tasks import enqueue
from ...models import UniqueFeed, Feed
from ...tasks import update_feed
from ...utils import FeedUpdater
logger = logging.getLogger('feedupdater')
class Command(BaseCommand):
"""Updates the users' feeds"""
def handle(self, *args, **kwargs):
if args:
pk = args[0]
feed = Feed.objects.get(pk=pk)
feed.etag = ''
return FeedUpdater(feed.url).update(use_etags=False)
# Making a list of unique URLs. Makes one call whatever the number of
# subscribers is.
urls = Feed.objects.filter(muted=False).values_list('url', flat=True)
unique_urls = {}
map(unique_urls.__setitem__, urls, [])
for url in unique_urls:
try:
try:
unique = UniqueFeed.objects.get(url=url)
if unique.should_update():
enqueue(update_feed, url)
except UniqueFeed.DoesNotExist:
enqueue(update_feed, url)
except Exception: # We don't know what to expect, and anyway
# we're reporting the exception
if settings.DEBUG or not hasattr(settings, 'SENTRY_DSN'):
raise
else:
client = Client(dsn=settings.SENTRY_DSN)
client.captureException()
connection.close()
|
Use BrewPhase in Brew tests | var Brew = require('./brew');
var BrewPhase = require('./BrewPhase');
var expect = require('chai').expect;
describe('Brew model', function() {
describe('get actual phase', function() {
it('should find the phase in progress', function() {
var actualPhase = new BrewPhase({
min: 10,
temp: 50,
status: 'active'
});
var scheduledPhase = new BrewPhase({
min: 20,
temp: 70,
status: 'scheduled'
});
var brew = new Brew({
name: 'Very IPA',
startDate: new Date(),
phases: [actualPhase, scheduledPhase]
});
var actual = brew.getActualPhase();
expect(actual).to.be.eql(actualPhase);
});
it('should handle when there is no phase in progress', function() {
var scheduledPhase1 = new BrewPhase({
min: 10,
temp: 50,
status: 'scheduled'
});
var scheduledPhase2 = new BrewPhase({
min: 20,
temp: 70,
status: 'scheduled'
});
var brew = new Brew({
name: 'Very IPA',
startDate: new Date(),
phases: [scheduledPhase1, scheduledPhase2]
});
var actual = brew.getActualPhase();
expect(actual).to.be.undefined;
});
});
});
| var Brew = require('./brew');
var expect = require('chai').expect;
describe('Brew model', function() {
describe('get actual phase', function() {
it('should find the phase in progress', function() {
var brew = new Brew({
name: 'Very IPA',
startDate: new Date(),
phases: [{
min: 10,
temp: 50,
status: 'active'
}, {
min: 20,
temp: 70,
status: 'scheduled'
}]
});
var actual = brew.getActualPhase();
expect(actual).to.be.eql({
min: 10,
temp: 50,
status: 'active'
});
});
it('should handle when there is no phase in progress', function() {
var brew = new Brew({
name: 'Very IPA',
startDate: new Date(),
phases: [{
min: 10,
temp: 50,
status: 'scheduled'
}, {
min: 20,
temp: 70,
status: 'scheduled'
}]
});
var actual = brew.getActualPhase();
expect(actual).to.be.undefined;
});
});
});
|
Add scalar node with skin | <?php
namespace Avanzu\AdminThemeBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('avanzu_admin_theme');
$rootNode->children()
->scalarNode('bower_bin')
->defaultValue('/usr/local/bin/bower')
->end()
->scalarNode('use_assetic')
->defaultValue(true)
->end()
->scalarNode('use_twig')
->defaultValue(true)
->end()
->arrayNode('options')
->children()
->scalarNode('skin')->end()
->beforeNormalization()->castToArray()->end()
->end()
->end();
// Here you should define the parameters that are allowed to
// configure your bundle. See the documentation linked above for
// more information on that topic.
return $treeBuilder;
}
}
| <?php
namespace Avanzu\AdminThemeBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('avanzu_admin_theme');
$rootNode->children()
->scalarNode('bower_bin')
->defaultValue('/usr/local/bin/bower')
->end()
->scalarNode('use_assetic')
->defaultValue(true)
->end()
->scalarNode('use_twig')
->defaultValue(true)
->end()
->arrayNode('options')
->beforeNormalization()->castToArray()->end()
->end()
->end();
// Here you should define the parameters that are allowed to
// configure your bundle. See the documentation linked above for
// more information on that topic.
return $treeBuilder;
}
}
|
Add credentials option in order to send headers | var Timers = require('timers')
var SenecaModule = require('seneca')
global.setImmediate = global.setImmediate || Timers.setImmediate
var SenecaExport = function(options, more_options) {
options = options || {}
options.legacy = options.legacy || {}
options.legacy.transport = false
var seneca = SenecaModule(options, more_options)
seneca.use(function browser() {
this.add('role:transport,hook:client,type:browser', hook_client_browser)
var tu = this.export('transport/utils')
function hook_client_browser(msg, reply) {
var seneca = this
reply({
send: function(msg, reply, meta) {
fetch('/seneca', {
credentials: 'same-origin',
method: 'post',
body: tu.stringifyJSON(tu.externalize_msg(seneca, msg, meta))
}).then(function(response) {
if(response.ok) {
return response.json()
}
else {
// FIX: handle transport errors
return null
}
}).then(function(json) {
// FIX: seneca.reply broken in browser
var rep = tu.internalize_reply(seneca, json)
reply(rep.err, rep.out)
})
}
})
}
})
return seneca
}
SenecaExport.prototype = SenecaModule.prototype
module.exports = SenecaExport
| var Timers = require('timers')
var SenecaModule = require('seneca')
global.setImmediate = global.setImmediate || Timers.setImmediate
var SenecaExport = function(options, more_options) {
options = options || {}
options.legacy = options.legacy || {}
options.legacy.transport = false
var seneca = SenecaModule(options, more_options)
seneca.use(function browser() {
this.add('role:transport,hook:client,type:browser', hook_client_browser)
var tu = this.export('transport/utils')
function hook_client_browser(msg, reply) {
var seneca = this
reply({
send: function(msg, reply, meta) {
fetch('/seneca', {
method: 'post',
body: tu.stringifyJSON(tu.externalize_msg(seneca, msg, meta))
}).then(function(response) {
if(response.ok) {
return response.json()
}
else {
// FIX: handle transport errors
return null
}
}).then(function(json) {
// FIX: seneca.reply broken in browser
var rep = tu.internalize_reply(seneca, json)
reply(rep.err, rep.out)
})
}
})
}
})
return seneca
}
SenecaExport.prototype = SenecaModule.prototype
module.exports = SenecaExport
|
Fix missing import. Add method to get all nodes with a particular attribute | """
Registry class and global node registry.
"""
import inspect
class NotRegistered(KeyError):
pass
class NodeRegistry(dict):
NotRegistered = NotRegistered
def register(self, node):
"""Register a node class in the node registry."""
self[node.name] = inspect.isclass(node) and node or node.__class__
def unregister(self, name):
"""Unregister node by name."""
try:
# Might be a node class
name = name.name
except AttributeError:
pass
self.pop(name)
def get_by_attr(self, attr, value=None):
"""Return all nodes of a specific type that have a matching attr.
If `value` is given, only return nodes where the attr value matches."""
ret = {}
for name, node in self.iteritems():
if hasattr(node, attr) and value is None\
or hasattr(node, name) and getattr(node, name) == value:
ret[name] = node
return ret
def __getitem__(self, key):
try:
return dict.__getitem__(self, key)
except KeyError:
raise self.NotRegistered(key)
def pop(self, key, *args):
try:
return dict.pop(self, key, *args)
except KeyError:
raise self.NotRegistered(key)
nodes = NodeRegistry()
| """
Registry class and global node registry.
"""
class NotRegistered(KeyError):
pass
__all__ = ["NodeRegistry", "nodes"]
class NodeRegistry(dict):
NotRegistered = NotRegistered
def register(self, node):
"""Register a node in the node registry.
The node will be automatically instantiated if not already an
instance.
"""
self[node.name] = inspect.isclass(node) and node() or node
def unregister(self, name):
"""Unregister node by name."""
try:
# Might be a node class
name = name.name
except AttributeError:
pass
self.pop(name)
def filter_types(self, type):
"""Return all nodes of a specific type."""
return dict((name, node) for name, node in self.iteritems()
if node.type == type)
def __getitem__(self, key):
try:
return dict.__getitem__(self, key)
except KeyError:
raise self.NotRegistered(key)
def pop(self, key, *args):
try:
return dict.pop(self, key, *args)
except KeyError:
raise self.NotRegistered(key)
nodes = NodeRegistry()
|
Put getMaxPriority in a separate function. | define([
'angular'
], function(angular) {
'use strict';
angular.module('superdesk.menu', []).
directive('sdMenu', function($route) {
var sdMenu = {
templateUrl: 'scripts/superdesk/menu/menu.html',
replace: false,
priority: -1,
link: function(scope, element, attrs) {
scope.items = [];
angular.forEach($route.routes, function(route) {
if ('menu' in route) {
var item = {label: route.menu.label, priority: route.menu.priority, href: route.originalPath};
if (route.menu.parent === undefined) {
scope.items.push(item);
} else {
var found = false;
for (var i = 0; i < scope.items.length; i++) {
if (scope.items[i].label === route.menu.parent) {
found = true;
scope.items[i].items.push(item);
break;
}
}
if (found === false) {
var maxPriority = sdMenu.getMaxPriority(scope.items);
var parent = {label: route.menu.parent, priority: maxPriority + 1, items: [item]};
scope.items.push(parent);
}
}
}
});
},
getMaxPriority: function(items) {
var maxPriority = 0;
for (var i = 0; i < items.length; i++) {
if (items.priority > maxPriority) {
maxPriority = items.priority;
}
}
return maxPriority;
}
};
return sdMenu;
});
});
| define([
'angular'
], function(angular) {
'use strict';
angular.module('superdesk.menu', []).
directive('sdMenu', function($route) {
return {
templateUrl: 'scripts/superdesk/menu/menu.html',
replace: false,
priority: -1,
link: function(scope, element, attrs) {
scope.items = [];
angular.forEach($route.routes, function(route) {
if ('menu' in route) {
var item = {label: route.menu.label, priority: route.menu.priority, href: route.originalPath};
if (route.menu.parent === undefined) {
scope.items.push(item);
} else {
var found = false;
for (var i = 0; i < scope.items.length; i++) {
if (scope.items[i].label === route.menu.parent) {
found = true;
scope.items[i].items.push(item);
break;
}
}
if (found === false) {
var maxPriority = 0;
for (var i = 0; i < scope.items.length; i++) {
if (scope.items.priority > maxPriority) {
maxPriority = scope.items.priority;
}
}
var parent = {label: route.menu.parent, priority: maxPriority + 1, items: [item]};
scope.items.push(parent);
}
}
}
});
}
};
});
});
|
Use closing for Python 2.6 compatibility | import os
import zipfile
import contextlib
import pytest
from setuptools.command.upload_docs import upload_docs
from setuptools.dist import Distribution
from .textwrap import DALS
from . import contexts
SETUP_PY = DALS(
"""
from setuptools import setup
setup(name='foo')
""")
@pytest.fixture
def sample_project(tmpdir_cwd):
# setup.py
with open('setup.py', 'wt') as f:
f.write(SETUP_PY)
os.mkdir('build')
# A test document.
with open('build/index.html', 'w') as f:
f.write("Hello world.")
# An empty folder.
os.mkdir('build/empty')
@pytest.mark.usefixtures('sample_project')
@pytest.mark.usefixtures('user_override')
class TestUploadDocsTest:
def test_create_zipfile(self):
"""
Ensure zipfile creation handles common cases, including a folder
containing an empty folder.
"""
dist = Distribution()
cmd = upload_docs(dist)
cmd.target_dir = cmd.upload_dir = 'build'
with contexts.tempdir() as tmp_dir:
tmp_file = os.path.join(tmp_dir, 'foo.zip')
zip_file = cmd.create_zipfile(tmp_file)
assert zipfile.is_zipfile(tmp_file)
with contextlib.closing(zipfile.ZipFile(tmp_file)) as zip_file:
assert zip_file.namelist() == ['index.html']
| import os
import zipfile
import pytest
from setuptools.command.upload_docs import upload_docs
from setuptools.dist import Distribution
from .textwrap import DALS
from . import contexts
SETUP_PY = DALS(
"""
from setuptools import setup
setup(name='foo')
""")
@pytest.fixture
def sample_project(tmpdir_cwd):
# setup.py
with open('setup.py', 'wt') as f:
f.write(SETUP_PY)
os.mkdir('build')
# A test document.
with open('build/index.html', 'w') as f:
f.write("Hello world.")
# An empty folder.
os.mkdir('build/empty')
@pytest.mark.usefixtures('sample_project')
@pytest.mark.usefixtures('user_override')
class TestUploadDocsTest:
def test_create_zipfile(self):
"""
Ensure zipfile creation handles common cases, including a folder
containing an empty folder.
"""
dist = Distribution()
cmd = upload_docs(dist)
cmd.target_dir = cmd.upload_dir = 'build'
with contexts.tempdir() as tmp_dir:
tmp_file = os.path.join(tmp_dir, 'foo.zip')
zip_file = cmd.create_zipfile(tmp_file)
assert zipfile.is_zipfile(tmp_file)
with zipfile.ZipFile(tmp_file) as zip_file:
assert zip_file.namelist() == ['index.html']
|
Update for new extension API | <?php namespace Flarum\Sticky;
use Flarum\Support\ServiceProvider;
use Flarum\Extend\EventSubscribers;
use Flarum\Extend\ForumAssets;
use Flarum\Extend\PostType;
use Flarum\Extend\SerializeAttributes;
use Flarum\Extend\DiscussionGambit;
use Flarum\Extend\NotificationType;
use Flarum\Extend\Permission;
class StickyServiceProvider extends ServiceProvider
{
public function boot()
{
$this->extend(
new EventSubscribers([
'Flarum\Sticky\Handlers\StickySaver',
'Flarum\Sticky\Handlers\StickySearchModifier',
'Flarum\Sticky\Handlers\DiscussionStickiedNotifier'
]),
new ForumAssets([
__DIR__.'/../js/dist/extension.js',
__DIR__.'/../less/sticky.less'
]),
new PostType('Flarum\Sticky\DiscussionStickiedPost'),
new SerializeAttributes('Flarum\Api\Serializers\DiscussionSerializer', function (&$attributes, $model, $serializer) {
$attributes['isSticky'] = (bool) $model->is_sticky;
$attributes['canSticky'] = (bool) $model->can($serializer->actor->getUser(), 'sticky');
}),
new DiscussionGambit('Flarum\Sticky\StickyGambit'),
(new NotificationType('Flarum\Sticky\DiscussionStickiedNotification'))->enableByDefault('alert'),
new Permission('discussion.sticky')
);
}
}
| <?php namespace Flarum\Sticky;
use Flarum\Support\ServiceProvider;
use Illuminate\Contracts\Events\Dispatcher;
class StickyServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot(Dispatcher $events)
{
$events->subscribe('Flarum\Sticky\Handlers\StickySaver');
$events->subscribe('Flarum\Sticky\Handlers\StickySearchModifier');
$events->subscribe('Flarum\Sticky\Handlers\DiscussionStickiedNotifier');
$this->forumAssets([
__DIR__.'/../js/dist/extension.js',
__DIR__.'/../less/sticky.less'
]);
$this->postType('Flarum\Sticky\DiscussionStickiedPost');
$this->serializeAttributes('Flarum\Api\Serializers\DiscussionSerializer', function (&$attributes, $model, $serializer) {
$attributes['isSticky'] = (bool) $model->is_sticky;
$attributes['canSticky'] = (bool) $model->can($serializer->actor->getUser(), 'sticky');
});
$this->discussionGambit('Flarum\Sticky\StickyGambit');
$this->notificationType('Flarum\Sticky\DiscussionStickiedNotification', ['alert' => true]);
$this->permission('discussion.sticky');
}
}
|
Change index page for webpack dev server | var path = require("path");
module.exports = {
entry: {
app: './src/app.tsx'
},
output: {
path: path.resolve(__dirname, 'build'),
publicPath: "/build/",
filename: "[name].bundle.js"
},
resolve: {
modules: [
"node_modules",
path.resolve(__dirname, "app")
],
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: [".webpack.js", ".web.js", ".ts", ".tsx", ".js"]
},
// Enable sourcemaps for debugging webpack's output.
devtool: "source-map",
devServer: {
historyApiFallback: {
index: '404.html'
}
},
module: {
rules: [
// All files with a '.ts' extension will be handled by 'ts-loader'.
{
test: /\.tsx?$/,
loader: "awesome-typescript-loader"
},
// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
{
test: /\.js$/,
loader: "source-map-loader"
}
]
}
} | var path = require("path");
module.exports = {
entry: {
app: './src/app.tsx'
},
output: {
path: path.resolve(__dirname, 'build'),
publicPath: "/build/",
filename: "[name].bundle.js"
},
resolve: {
modules: [
"node_modules",
path.resolve(__dirname, "app")
],
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: [".webpack.js", ".web.js", ".ts", ".tsx", ".js"]
},
// Enable sourcemaps for debugging webpack's output.
devtool: "source-map",
devServer: {
historyApiFallback: true
},
module: {
rules: [
// All files with a '.ts' extension will be handled by 'ts-loader'.
{
test: /\.tsx?$/,
loader: "awesome-typescript-loader"
},
// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
{
test: /\.js$/,
loader: "source-map-loader"
}
]
}
} |
Add builds to project api | from rest_framework import serializers
from .models import Build, BuildResult, Project
class BuildResultSerializer(serializers.ModelSerializer):
class Meta:
model = BuildResult
fields = (
'id',
'coverage',
'succeeded',
'tasks',
)
class BuildInlineSerializer(serializers.ModelSerializer):
result = BuildResultSerializer(read_only=True)
class Meta:
model = Build
fields = (
'id',
'build_number',
'branch',
'sha',
'pull_request_id',
'start_time',
'end_time',
'result'
)
class ProjectSerializer(serializers.ModelSerializer):
builds = BuildInlineSerializer(read_only=True, many=True)
class Meta:
model = Project
fields = (
'id',
'owner',
'name',
'private',
'approved',
'git_repository',
'builds'
)
class ProjectInlineSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = (
'id',
'owner',
'name',
'private',
'approved',
'git_repository'
)
class BuildSerializer(serializers.ModelSerializer):
project = ProjectInlineSerializer(read_only=True)
result = BuildResultSerializer(read_only=True)
class Meta:
model = Build
fields = (
'id',
'project',
'result',
'build_number',
'branch',
'pull_request_id',
'sha',
'start_time',
'end_time',
)
| from rest_framework import serializers
from .models import Build, BuildResult, Project
class ProjectSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = (
'id',
'owner',
'name',
'private',
'approved',
'git_repository'
)
class BuildResultSerializer(serializers.ModelSerializer):
class Meta:
model = BuildResult
fields = (
'id',
'coverage',
'succeeded',
'tasks',
)
class BuildSerializer(serializers.ModelSerializer):
project = ProjectSerializer(read_only=True)
result = BuildResultSerializer(read_only=True)
class Meta:
model = Build
fields = (
'id',
'project',
'result',
'build_number',
'branch',
'pull_request_id',
'sha',
'start_time',
'end_time',
)
|
Increase the time before the status call during the nodes upgrade.
Upgrade of nodes takes many minutes, probably even hours. We
do not need to execute the status query every 5 seconds. | (function() {
angular
.module('crowbarApp.upgrade')
.constant('ADDONS_PRECHECK_MAP', {
'ha': ['clusters_healthy'],
'ceph': ['ceph_healthy']
})
.constant('UNEXPECTED_ERROR_DATA', {
title: 'unexpected_error',
errors: {
unexpected_error: {
data: 'An unexpected error ocurred',
help: 'Please check logs for more details'
}
}
})
.constant('UPGRADE_LAST_STATE_KEY', 'crowbar.upgrade.lastUIState')
.constant('PREPARE_TIMEOUT_INTERVAL', 1000)
.constant('ADMIN_UPGRADE_ALLOWED_DOWNTIME', 30 * 60 * 1000)
.constant('ADMIN_UPGRADE_TIMEOUT_INTERVAL', 5000)
.constant('NODES_UPGRADE_TIMEOUT_INTERVAL', 30 * 1000)
.constant('STOP_OPENSTACK_SERVICES_TIMEOUT_INTERVAL', 5000)
.constant('OPENSTACK_BACKUP_TIMEOUT_INTERVAL', 1000)
.constant('UPGRADE_MODES', {
nondisruptive: 'non-disruptive',
disruptive: 'disruptive',
none: 'none',
});
})();
| (function() {
angular
.module('crowbarApp.upgrade')
.constant('ADDONS_PRECHECK_MAP', {
'ha': ['clusters_healthy'],
'ceph': ['ceph_healthy']
})
.constant('UNEXPECTED_ERROR_DATA', {
title: 'unexpected_error',
errors: {
unexpected_error: {
data: 'An unexpected error ocurred',
help: 'Please check logs for more details'
}
}
})
.constant('UPGRADE_LAST_STATE_KEY', 'crowbar.upgrade.lastUIState')
.constant('PREPARE_TIMEOUT_INTERVAL', 1000)
.constant('ADMIN_UPGRADE_ALLOWED_DOWNTIME', 30 * 60 * 1000)
.constant('ADMIN_UPGRADE_TIMEOUT_INTERVAL', 5000)
.constant('NODES_UPGRADE_TIMEOUT_INTERVAL', 5000)
.constant('STOP_OPENSTACK_SERVICES_TIMEOUT_INTERVAL', 5000)
.constant('OPENSTACK_BACKUP_TIMEOUT_INTERVAL', 1000)
.constant('UPGRADE_MODES', {
nondisruptive: 'non-disruptive',
disruptive: 'disruptive',
none: 'none',
});
})();
|
Fix validation of OpenStack select fields in request-based item form [WAL-4035] | from rest_framework import serializers
class StringListSerializer(serializers.ListField):
child = serializers.CharField()
FIELD_CLASSES = {
'integer': serializers.IntegerField,
'date': serializers.DateField,
'time': serializers.TimeField,
'money': serializers.IntegerField,
'boolean': serializers.BooleanField,
'select_string': serializers.ChoiceField,
'select_string_multi': serializers.MultipleChoiceField,
'select_openstack_tenant': serializers.CharField,
'select_multiple_openstack_tenants': StringListSerializer,
'select_openstack_instance': serializers.CharField,
'select_multiple_openstack_instances': StringListSerializer,
}
def validate_options(options, attributes):
fields = {}
for name, option in options.items():
params = {}
field_type = option.get('type', '')
field_class = FIELD_CLASSES.get(field_type, serializers.CharField)
default_value = option.get('default')
if default_value:
params['default'] = default_value
else:
params['required'] = option.get('required', False)
if field_class == serializers.IntegerField:
if 'min' in option:
params['min_value'] = option.get('min')
if 'max' in option:
params['max_value'] = option.get('max')
if 'choices' in option:
params['choices'] = option['choices']
fields[name] = field_class(**params)
serializer_class = type('AttributesSerializer', (serializers.Serializer,), fields)
serializer = serializer_class(data=attributes)
serializer.is_valid(raise_exception=True)
| from rest_framework import serializers
def validate_options(options, attributes):
fields = {}
for name, option in options.items():
params = {}
field_type = option.get('type', '')
field_class = serializers.CharField
if field_type == 'integer':
field_class = serializers.IntegerField
elif field_type == 'money':
field_class = serializers.IntegerField
elif field_type == 'boolean':
field_class = serializers.BooleanField
default_value = option.get('default')
if default_value:
params['default'] = default_value
else:
params['required'] = option.get('required', False)
if field_class == serializers.IntegerField:
if 'min' in option:
params['min_value'] = option.get('min')
if 'max' in option:
params['max_value'] = option.get('max')
if 'choices' in option:
field_class = serializers.ChoiceField
params['choices'] = option.get('choices')
if field_type == 'select_string_multi':
field_class = serializers.MultipleChoiceField
params['choices'] = option.get('choices')
fields[name] = field_class(**params)
serializer_class = type('AttributesSerializer', (serializers.Serializer,), fields)
serializer = serializer_class(data=attributes)
serializer.is_valid(raise_exception=True)
|
Test LICQ condition of constraint gradient | import unittest
import numpy as np
from constraints import (generate_constraints_function,
generate_constraint_gradients_function, )
from robot_arm import RobotArm
class TestConstraintFunctions(unittest.TestCase):
def setUp(self):
self.lengths = (3, 2, 2,)
self.destinations = (
(5, 4, 6, 4, 5),
(0, 2, 0.5, -2, -1),
)
self.theta = (np.pi, np.pi / 2, 0,)
self.thetas = np.ones((3 * 5,))
self.robot_arm = RobotArm(self.lengths, self.destinations, self.theta)
self.constraints_func = generate_constraints_function(self.robot_arm)
self.constraint_gradients_func = generate_constraint_gradients_function(self.robot_arm)
def test_constraints_func_return_type(self):
constraints = self.constraints_func(self.thetas)
self.assertEqual(constraints.shape, (2 * 5,))
def test_constraint_gradients_func_return_type(self):
constraint_gradients = self.constraint_gradients_func(self.thetas)
self.assertEqual(constraint_gradients.shape, (3 * 5, 2 * 5))
# print(np.array2string(constraint_gradients, max_line_width=np.inf))
def test_licq(self):
constraint_gradients = self.constraint_gradients_func(self.thetas)
rank = np.linalg.matrix_rank(constraint_gradients)
self.assertEqual(rank, 2 * 5)
| import unittest
import numpy as np
from constraints import (generate_constraints_function,
generate_constraint_gradients_function, )
from robot_arm import RobotArm
class TestConstraintFunctions(unittest.TestCase):
def setUp(self):
self.lengths = (3, 2, 2,)
self.destinations = (
(5, 4, 6, 4, 5),
(0, 2, 0.5, -2, -1),
)
self.theta = (np.pi, np.pi / 2, 0,)
self.thetas = np.ones((3 * 5,))
self.robot_arm = RobotArm(self.lengths, self.destinations, self.theta)
self.constraints_func = generate_constraints_function(self.robot_arm)
self.constraint_gradients_func = generate_constraint_gradients_function(self.robot_arm)
def test_constraints_func_return_type(self):
constraints = self.constraints_func(self.thetas)
self.assertEqual(constraints.shape, (2 * 5,))
def test_constraint_gradients_func_return_type(self):
constraint_gradients = self.constraint_gradients_func(self.thetas)
self.assertEqual(constraint_gradients.shape, (3 * 5, 2 * 5))
# print(np.array2string(constraint_gradients, max_line_width=np.inf))
|
Remove instance config from closure | <?php
return array(
'table' => '',
'instance' => 'Algorit\Synchronizer\Storage\SyncInterface',
'create' => function($system, $resource, $entity, $type)
{
$company_id = null;
$representative_id = null;
// Not the best code in the world.
$class = explode('\\', get_class($this->resource));
switch(end($class))
{
case 'Erp':
$erp_id = $resource->id;
break;
case 'Company':
$company_id = $resource->id;
$erp_id = $resource->erp->id;
break;
case 'Representative':
$representative_id = $resource->id;
$company_id = $resource->company->id;
$erp_id = $resource->company->erp->id;
break;
}
return array(
'erp_id' => $erp_id,
'company_id' => $company_id,
'representative_id' => $representative_id,
'entity' => $entity,
'type' => $type,
'class' => get_class($system),
'status' => 'processing',
);
},
); | <?php
return array(
'table' => '',
'instance' => function()
{
return App::make('Algorit\Synchronizer\Storage\SyncInterface');
},
'create' => function($system, $resource, $entity, $type)
{
$company_id = null;
$representative_id = null;
// Not the best code in the world.
$class = explode('\\', get_class($this->resource));
switch(end($class))
{
case 'Erp':
$erp_id = $resource->id;
break;
case 'Company':
$company_id = $resource->id;
$erp_id = $resource->erp->id;
break;
case 'Representative':
$representative_id = $resource->id;
$company_id = $resource->company->id;
$erp_id = $resource->company->erp->id;
break;
}
return array(
'erp_id' => $erp_id,
'company_id' => $company_id,
'representative_id' => $representative_id,
'entity' => $entity,
'type' => $type,
'class' => get_class($system),
'status' => 'processing',
);
},
); |
Test that the serializer doesn't break on an exception | <?php
namespace FluentDOM\HTML5 {
use FluentDOM\Document;
use FluentDOM\TestCase;
require_once(__DIR__.'/../vendor/autoload.php');
class SerializerTest extends \PHPUnit_Framework_TestCase {
/**
* @covers FluentDOM\HTML5\Serializer
*/
public function testLoadReturnsImportedDocument() {
$xhtml = '<?xml version="1.0"?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>TEST</title>
</head>
<body id="foo">
<h1>Hello World</h1>
<p>This is a test of the HTML5 parser.</p>
</body>
</html>';
$dom = new Document();
$dom->preserveWhiteSpace = FALSE;
$dom->loadXml($xhtml);
$serializer = new Serializer($dom);
$html =
'<!DOCTYPE html>'.PHP_EOL.
'<html>'.
'<head>'.
'<title>TEST</title>'.
'</head>'.
'<body id="foo">'.
'<h1>Hello World</h1>'.
'<p>This is a test of the HTML5 parser.</p>'.
'</body>'.
'</html>'.PHP_EOL;
$this->assertEquals(
$html,
(string)$serializer
);
}
public function testToStringCatchesExceptionAndReturnEmptyString() {
$serializer = new Serializer_TestProxy(new Document());
$this->assertEquals(
'', (string)$serializer
);
}
}
class Serializer_TestProxy extends Serializer {
public function asString() {
throw new \LogicException('Catch It.');
}
}
} | <?php
namespace FluentDOM\HTML5 {
use FluentDOM\Document;
use FluentDOM\TestCase;
require_once(__DIR__.'/../vendor/autoload.php');
class SerializerTest extends \PHPUnit_Framework_TestCase {
/**
* @covers FluentDOM\HTML5\Serializer
*/
public function testLoadReturnsImportedDocument() {
$xhtml = '<?xml version="1.0"?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>TEST</title>
</head>
<body id="foo">
<h1>Hello World</h1>
<p>This is a test of the HTML5 parser.</p>
</body>
</html>';
$dom = new Document();
$dom->preserveWhiteSpace = FALSE;
$dom->loadXml($xhtml);
$serializer = new Serializer($dom);
$html =
'<!DOCTYPE html>'.PHP_EOL.
'<html>'.
'<head>'.
'<title>TEST</title>'.
'</head>'.
'<body id="foo">'.
'<h1>Hello World</h1>'.
'<p>This is a test of the HTML5 parser.</p>'.
'</body>'.
'</html>'.PHP_EOL;
$this->assertEquals(
$html,
(string)$serializer
);
}
}
} |
Fix installer for completely new add-on | <?php
class SV_AttachmentImprovements_Installer
{
const AddonNameSpace = 'SV_AttachmentImprovements_';
public static function install($existingAddOn, $addOnData)
{
$version = isset($existingAddOn['version_id']) ? $existingAddOn['version_id'] : 0;
if ($version && $version < 1000200)
{
XenForo_Application::defer(self::AddonNameSpace.'Deferred_SVGAttachmentThumb', array());
}
else if ($version == 0)
{
$addon = XenForo_Model::create('XenForo_Model_AddOn')->getAddOnById('SV_SVGAttachment');
if (!empty($addon))
{
XenForo_Application::defer(self::AddonNameSpace.'Deferred_SVGAttachmentThumb', array());
}
}
$addonsToUninstall = array('SV_SVGAttachment' => array(),
'SV_XARAttachment' => array());
SV_Utils_Install::removeOldAddons($addonsToUninstall);
return true;
}
public static function uninstall()
{
$db = XenForo_Application::get('db');
$db->query("
DELETE FROM xf_permission_entry
WHERE permission_id in ('attach_count', 'attach_size')
");
$db->query("
DELETE FROM xf_permission_entry_content
WHERE permission_id in ('attach_count', 'attach_size')
");
return true;
}
}
| <?php
class SV_AttachmentImprovements_Installer
{
const AddonNameSpace = 'SV_AttachmentImprovements_';
public static function install($existingAddOn, $addOnData)
{
$version = isset($existingAddOn['version_id']) ? $existingAddOn['version_id'] : 0;
if ($version && $version < 1000200)
{
XenForo_Application::defer(self::AddonNameSpace.'Deferred_SVGAttachmentThumb', array());
}
else if ($version == 0)
{
$addon = $addonModel->getAddOnById('SV_SVGAttachment');
if (!empty($addon))
{
XenForo_Application::defer(self::AddonNameSpace.'Deferred_SVGAttachmentThumb', array());
}
}
$addonsToUninstall = array('SV_SVGAttachment' => array(),
'SV_XARAttachment' => array());
SV_Utils_Install::removeOldAddons($addonsToUninstall);
return true;
}
public static function uninstall()
{
$db = XenForo_Application::get('db');
$db->query("
DELETE FROM xf_permission_entry
WHERE permission_id in ('attach_count', 'attach_size')
");
$db->query("
DELETE FROM xf_permission_entry_content
WHERE permission_id in ('attach_count', 'attach_size')
");
return true;
}
}
|
BLD: Update version to match version reported on website | import os
# BEFORE importing distutils, remove MANIFEST. distutils doesn't
# properly update it when the contents of directories change.
if os.path.exists('MANIFEST'): os.remove('MANIFEST')
from distutils.core import setup
MAJOR = 0
MINOR = 1
MICRO = 1
VERSION = '%d.%d.%d' % (MAJOR, MINOR, MICRO)
if __name__ == '__main__':
setup(name='wradlib',
version=VERSION,
description='Open Source Library for Weather Radar Data Processing',
long_description = """\
wradlib - An Open Source Library for Weather Radar Data Processing
==================================================================
wradlib is designed to assist you in the most important steps of
processing weather radar data. These may include: reading common data
formats, georeferencing, converting reflectivity to rainfall
intensity, identifying and correcting typical error sources (such as
clutter or attenuation) and visualising the data.
""",
license='BSD',
url='http://wradlib.bitbucket.org/',
download_url='https://bitbucket.org/wradlib/wradlib',
packages=['wradlib'],
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: BSD License',
'Environment :: Console',
'Operating System :: OS Independent',
'Intended Audience :: Science/Research',
'Programming Language :: Python',
'Topic :: Scientific/Engineering',
],
)
| import os
# BEFORE importing distutils, remove MANIFEST. distutils doesn't
# properly update it when the contents of directories change.
if os.path.exists('MANIFEST'): os.remove('MANIFEST')
from distutils.core import setup
MAJOR = 0
MINOR = 1
MICRO = 0
VERSION = '%d.%d.%d' % (MAJOR, MINOR, MICRO)
if __name__ == '__main__':
setup(name='wradlib',
version=VERSION,
description='Open Source Library for Weather Radar Data Processing',
long_description = """\
wradlib - An Open Source Library for Weather Radar Data Processing
==================================================================
wradlib is designed to assist you in the most important steps of
processing weather radar data. These may include: reading common data
formats, georeferencing, converting reflectivity to rainfall
intensity, identifying and correcting typical error sources (such as
clutter or attenuation) and visualising the data.
""",
license='BSD',
url='http://wradlib.bitbucket.org/',
download_url='https://bitbucket.org/wradlib/wradlib',
packages=['wradlib'],
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: BSD License',
'Environment :: Console',
'Operating System :: OS Independent',
'Intended Audience :: Science/Research',
'Programming Language :: Python',
'Topic :: Scientific/Engineering',
],
)
|
Move QUESTIONS_BUILDER from blueprint to a global variable | from flask import Flask, request, redirect
from flask.ext.bootstrap import Bootstrap
from config import configs
from dmutils import apiclient, init_app, flask_featureflags
from dmutils.content_loader import ContentLoader
bootstrap = Bootstrap()
data_api_client = apiclient.DataAPIClient()
search_api_client = apiclient.SearchAPIClient()
feature_flags = flask_featureflags.FeatureFlag()
questions_loader = ContentLoader(
"app/helpers/questions_manifest.yml",
"app/content/g6/"
)
def create_app(config_name):
application = Flask(__name__)
init_app(
application,
configs[config_name],
bootstrap=bootstrap,
data_api_client=data_api_client,
feature_flags=feature_flags,
search_api_client=search_api_client
)
from .main import main as main_blueprint
from .status import status as status_blueprint
application.register_blueprint(status_blueprint)
application.register_blueprint(main_blueprint)
main_blueprint.config = {
'BASE_TEMPLATE_DATA': application.config['BASE_TEMPLATE_DATA'],
}
@application.before_request
def remove_trailing_slash():
if request.path != '/' and request.path.endswith('/'):
if request.query_string:
return redirect(
'{}?{}'.format(
request.path[:-1],
request.query_string.decode('utf-8')
),
code=301
)
else:
return redirect(request.path[:-1], code=301)
return application
| from flask import Flask, request, redirect
from flask.ext.bootstrap import Bootstrap
from config import configs
from dmutils import apiclient, init_app, flask_featureflags
from dmutils.content_loader import ContentLoader
bootstrap = Bootstrap()
data_api_client = apiclient.DataAPIClient()
search_api_client = apiclient.SearchAPIClient()
feature_flags = flask_featureflags.FeatureFlag()
def create_app(config_name):
application = Flask(__name__)
init_app(
application,
configs[config_name],
bootstrap=bootstrap,
data_api_client=data_api_client,
feature_flags=feature_flags,
search_api_client=search_api_client
)
questions_builder = ContentLoader(
"app/helpers/questions_manifest.yml",
"app/content/g6/"
).get_builder()
from .main import main as main_blueprint
from .status import status as status_blueprint
application.register_blueprint(status_blueprint)
application.register_blueprint(main_blueprint)
main_blueprint.config = {
'BASE_TEMPLATE_DATA': application.config['BASE_TEMPLATE_DATA'],
'QUESTIONS_BUILDER': questions_builder
}
@application.before_request
def remove_trailing_slash():
if request.path != '/' and request.path.endswith('/'):
if request.query_string:
return redirect(
'{}?{}'.format(
request.path[:-1],
request.query_string.decode('utf-8')
),
code=301
)
else:
return redirect(request.path[:-1], code=301)
return application
|
Use napms method from curses rather than sleep method from time | #!/usr/bin/env python
import curses
import os
from box import Box
from utils import load_yaml
def main(screen):
"""
Draws and redraws the screen.
"""
# Hide the cursor.
curses.curs_set(0)
# Load config from file.
config = load_yaml(os.path.expanduser('~/.suave/config.yml'))
# Create boxes from config.
boxes = []
for box in config:
boxes.append(
Box(
screen=screen,
rows=box['rows'],
columns=box['columns'],
rows_offset=box['rows-offset'],
columns_offset=box['columns-offset'],
command=box['command'],
interval=box['interval'],
)
)
while True:
# Redraw the screen only when it changes.
if screen.is_wintouched():
screen.clear()
screen.refresh()
# Give every box an opportunity to redraw if it has changed.
[box.redraw_if_changed() for box in boxes]
# Wait before redrawing again.
curses.napms(1000)
curses.wrapper(main)
| #!/usr/bin/env python
import curses
import os
import time
from box import Box
from utils import load_yaml
def main(screen):
"""
Draws and redraws the screen.
"""
# Hide the cursor.
curses.curs_set(0)
# Load config from file.
config = load_yaml(os.path.expanduser('~/.suave/config.yml'))
# Create boxes from config.
boxes = []
for box in config:
boxes.append(
Box(
screen=screen,
rows=box['rows'],
columns=box['columns'],
rows_offset=box['rows-offset'],
columns_offset=box['columns-offset'],
command=box['command'],
interval=box['interval'],
)
)
while True:
# Redraw the screen only when it changes.
if screen.is_wintouched():
screen.clear()
screen.refresh()
# Give every box an opportunity to redraw if it has changed.
[box.redraw_if_changed() for box in boxes]
# Wait before redrawing again.
time.sleep(1)
curses.wrapper(main)
|
Use currentUser service to set session.profileId | import Ember from 'ember';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';
import ExpPlayerRouteMixin from 'exp-player/mixins/exp-player-route';
export default Ember.Route.extend(AuthenticatedRouteMixin, ExpPlayerRouteMixin, {
currentUser: Ember.inject.service(),
_getExperiment() {
return new Ember.RSVP.Promise((resolve) => {
resolve(this.modelFor('experiments.info'));
});
},
_getSession(params, experiment) {
return this.get('currentUser').getCurrentUser().then(([account, profile]) => {
return this.store.createRecord(experiment.get('sessionCollectionId'), {
experimentId: experiment.id,
profileId: profile.get('id'),
profileVersion: '', // TODO
completed: false,
feedback: '',
hasReadFeedback: '',
softwareVersion: '',
expData: {},
sequence: []
});
});
},
actions: {
willTransition: function(transition) {
// FIXME: This won't prevent back button or manual URL change. See https://guides.emberjs.com/v2.3.0/routing/preventing-and-retrying-transitions/#toc_preventing-transitions-via-code-willtransition-code
if (this.controller.isDirty() && !confirm('Are you sure you want to exit the experiment?')) {
transition.abort();
return false;
} else {
// Bubble this action to parent routes
return true;
}
}
}
});
| import Ember from 'ember';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';
import ExpPlayerRouteMixin from 'exp-player/mixins/exp-player-route';
export default Ember.Route.extend(AuthenticatedRouteMixin, ExpPlayerRouteMixin, {
_getExperiment() {
return new Ember.RSVP.Promise((resolve) => {
resolve(this.modelFor('experiments.info'));
});
},
_getSession(params, experiment) {
var session = this.store.createRecord(experiment.get('sessionCollectionId'), {
experimentId: experiment.id,
profileId: 'tester0.prof1', // TODO fetch from service
profileVersion: '',
completed: false,
feedback: '',
hasReadFeedback: '',
softwareVersion: '',
expData: {},
sequence: []
});
return experiment.getCurrentVersion().then(versionId => {
session.set('experimentVersion', versionId);
return session.save().then(() => session);
});
return new Ember.RSVP.Promise((resolve) => {
resolve(session);
});
},
actions: {
willTransition: function(transition) {
// FIXME: This won't prevent back button or manual URL change. See https://guides.emberjs.com/v2.3.0/routing/preventing-and-retrying-transitions/#toc_preventing-transitions-via-code-willtransition-code
if (this.controller.isDirty() && !confirm('Are you sure you want to exit the experiment?')) {
transition.abort();
return false;
} else {
// Bubble this action to parent routes
return true;
}
}
}
});
|
Clean cache before doing benchmark + copyright | <?php
/**
* Copyright 2014 Krzysztof Magosa
*
* 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.
*/
require 'vendor/autoload.php';
class TestController
{
public function indexAction($slug, $id)
{
}
}
$_SERVER['REQUEST_URI'] = '/test/slugifiedtext/123';
$_SERVER['REQUEST_METHOD'] = 'GET';
$_SERVER['HTTP_HOST'] = 'example.com';
// Clear cache
array_map('unlink', glob(__DIR__ . '/cache/*.php'));
$bench = new \KM\Benchmark();
$bench
->execute(
'Saffron',
function () {
require 'test/saffron.php';
}
)
->execute(
'Saffron (e)',
function () {
require 'test/saffron.execute.php';
}
)
->execute(
'Pux',
function () {
require 'test/pux.php';
}
)
->execute(
'Symfony',
function () {
require 'test/symfony.php';
}
)
->execute(
'Klein (e)',
function () {
require 'test/klein.php';
}
)
->execute(
'Aura',
function () {
require 'test/aura.php';
}
)
->summary();
| <?php
require 'vendor/autoload.php';
$_SERVER['REQUEST_URI'] = '/test/slugifiedtext/123';
$_SERVER['REQUEST_METHOD'] = 'GET';
$_SERVER['HTTP_HOST'] = 'example.com';
class TestController
{
public function indexAction($slug, $id)
{
}
}
$bench = new \KM\Benchmark();
$bench
->execute(
'Saffron',
function () {
require 'test/saffron.php';
}
)
->execute(
'Saffron (e)',
function () {
require 'test/saffron.execute.php';
}
)
->execute(
'Pux',
function () {
require 'test/pux.php';
}
)
->execute(
'Symfony',
function () {
require 'test/symfony.php';
}
)
->execute(
'Klein (e)',
function () {
require 'test/klein.php';
}
)
->execute(
'Aura',
function () {
require 'test/aura.php';
}
)
->summary();
|
Remove <p> tags from rendered markdown | $("[name='submit']").click(function(e) {
e.preventDefault();
var form = $(this).parents('form:first');
var flag = $("input[name='flag']", form).val();
var pid = $("input[name='pid']", form).val();
if (flag == "") {
Materialize.toast("Flag cannot be empty!", 2000);
return;
}
submit_flag(pid, flag);
})
function submit_flag(pid, flag) {
$.post("/api/submit_flag", {
pid: pid,
flag: flag
}, function(data) {
if (data == 1) {
Materialize.toast("Correct!", 2000);
} else if (data == 0) {
Materialize.toast("Incorrect", 2000);
} else if (data == -1) {
Materialize.toast("You already solved this problem!", 2000)
}
});
}
function render_descriptions() {
Renderer.prototype.paragraph = function(text) {
return text;
};
var desc = $('p[name=problem-desc]').map(function(){
return $.trim($(this).text());
}).get();
$("p[name=problem-desc]").each(function() {
$(this).html(marked(desc[0]));
desc = desc.splice(1, desc.length);
});
}
$(document).ready(function() {
render_descriptions();
});
| $("[name='submit']").click(function(e) {
e.preventDefault();
var form = $(this).parents('form:first');
var flag = $("input[name='flag']", form).val();
var pid = $("input[name='pid']", form).val();
if (flag == "") {
Materialize.toast("Flag cannot be empty!", 2000);
return;
}
submit_flag(pid, flag);
})
function submit_flag(pid, flag) {
$.post("/api/submit_flag", {
pid: pid,
flag: flag
}, function(data) {
if (data == 1) {
Materialize.toast("Correct!", 2000);
} else if (data == 0) {
Materialize.toast("Incorrect", 2000);
} else if (data == -1) {
Materialize.toast("You already solved this problem!", 2000)
}
});
}
function render_descriptions() {
var desc = $('p[name=problem-desc]').map(function(){
return $.trim($(this).text());
}).get();
$("p[name=problem-desc]").each(function() {
$(this).html(marked(desc[0]));
desc = desc.splice(1, desc.length);
});
}
$(document).ready(function() {
render_descriptions();
});
|
Switch to use two separate events instead of the single event to prevent the CSS transition problem. | /**
* Created by Zack Boman on 1/31/14.
* http://www.zackboman.com or [email protected]
*/
'use strict';
(function(){
var mod = angular.module('routeStyles', ['ngRoute']);
mod.directive('head', ['$rootScope','$compile',
function($rootScope, $compile){
return {
restrict: 'E',
link: function(scope, elem){
var html = '<link rel="stylesheet" ng-repeat="(routeCtrl, cssUrl) in routeStyles" ng-href="{{cssUrl}}" >';
elem.append($compile(html)(scope));
scope.routeStyles = {};
$rootScope.$on('$routeChangeStart', function (e, next) {
if(next && next.$$route && next.$$route.css){
if(!Array.isArray(next.$$route.css)){
next.$$route.css = [next.$$route.css];
}
angular.forEach(next.$$route.css, function(sheet){
scope.routeStyles[sheet] = sheet;
});
}
});
$rootScope.$on('$routeChangeSuccess', function(e, current, previous) {
if (previous && previous.$$route && previous.$$route.css) {
if (!Array.isArray(previous.$$route.css)) {
previous.$$route.css = [previous.$$route.css];
}
angular.forEach(previous.$$route.css, function (sheet) {
scope.routeStyles[sheet] = undefined;
});
}
});
}
};
}
]);
})();
| /**
* Created by Zack Boman on 1/31/14.
* http://www.zackboman.com or [email protected]
*/
(function(){
var mod = angular.module('routeStyles', ['ngRoute']);
mod.directive('head', ['$rootScope','$compile',
function($rootScope, $compile){
return {
restrict: 'E',
link: function(scope, elem){
var html = '<link rel="stylesheet" ng-repeat="(routeCtrl, cssUrl) in routeStyles" ng-href="{{cssUrl}}" >';
elem.append($compile(html)(scope));
scope.routeStyles = {};
$rootScope.$on('$routeChangeStart', function (e, next, current) {
if(current && current.$$route && current.$$route.css){
if(!Array.isArray(current.$$route.css)){
current.$$route.css = [current.$$route.css];
}
angular.forEach(current.$$route.css, function(sheet){
scope.routeStyles[sheet] = undefined;
});
}
if(next && next.$$route && next.$$route.css){
if(!Array.isArray(next.$$route.css)){
next.$$route.css = [next.$$route.css];
}
angular.forEach(next.$$route.css, function(sheet){
if (angular.isFunction(sheet)){
sheet = sheet(next.params);
}
scope.routeStyles[sheet] = sheet;
});
}
});
}
};
}
]);
})();
|
Add exception if file does not exists | var fs = require('fs');
var jsss = require('./jsss');
var argv = process.argv;
var message = require('./message');
var pkg = fs.readFileSync(__dirname + '/../package.json');
if(argv[2] !== void 0) {
switch (argv[2]) {
case '-v':
if (argv.length === 3) {
jsss.version();
}
break;
case '--version':
if (argv.length === 3) {
jsss.version();
}
break;
case '-h':
if (argv.length === 3) {
jsss.help();
}
break;
case '--help':
if (argv.length === 3) {
jsss.help();
}
break;
default:
if (argv.length === 4 || argv.length === 3) {
var file = argv[2];
if (!fs.existsSync(file)) {
process.stdout.write('No such file or directory "' + file + '"\n');
return;
}
var opt = {
encoding: 'utf8'
};
var code = fs.readFileSync(file, opt);
var css = jsss.parse(code);
var out = argv[3] || false;
if (!out) {
process.stdout.write(css);
} else {
fs.writeFileSync(out, css);
}
} else {
var message = 'Unrecognized command line argument: ';
message += argv[2];
message += ' ( see: \'jsss -h\' )';
process.stdout.write(message);
break;
}
}
} else {
process.stdout.write(message());
return;
}
| var fs = require('fs');
var jsss = require('./jsss');
var argv = process.argv;
var message = require('./message');
var pkg = fs.readFileSync(__dirname + '/../package.json');
if(argv[2] !== void 0) {
switch (argv[2]) {
case '-v':
if (argv.length === 3) {
jsss.version();
}
break;
case '--version':
if (argv.length === 3) {
jsss.version();
}
break;
case '-h':
if (argv.length === 3) {
jsss.help();
}
break;
case '--help':
if (argv.length === 3) {
jsss.help();
}
break;
default:
if (argv.length === 4 || argv.length === 3) {
var opt = {
encoding: 'utf8'
};
var file = argv[2];
var code = fs.readFileSync(file, opt);
var css = jsss.parse(code);
var out = argv[3] || false;
if (!out) {
process.stdout.write(css);
} else {
fs.writeFileSync(out, css);
}
} else {
var message = 'Unrecognized command line argument: ';
message += argv[2];
message += ' ( see: \'jsss -h\' )';
process.stdout.write(message);
break;
}
}
} else {
process.stdout.write(message());
return;
}
|
Fix module not found error on moment | const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: {
app: path.resolve(__dirname, 'app/Resources/assets/js/app.js')
},
output: {
path: path.resolve(__dirname, 'web/builds'),
filename: 'bundle.js',
publicPath: '/builds/'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/,
use: 'babel-loader'
},
{
test: /\.scss$/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" },
{ loader: "sass-loader" }
]
},
{
test: /\.woff2?$|\.ttf$|\.eot$|\.svg$/,
use: "url-loader"
}
]
},
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery",
}),
],
resolve: {
alias: {
fonts: path.resolve(__dirname, 'web/fonts'),
jquery: path.resolve(__dirname, 'app/Resources/assets/js/jquery-2.1.4.min.js'),
moment: path.resolve(__dirname, 'app/Resources/assets/js/moment.min.js')
}
}
};
| const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: {
app: path.resolve(__dirname, 'app/Resources/assets/js/app.js')
},
output: {
path: path.resolve(__dirname, 'web/builds'),
filename: 'bundle.js',
publicPath: '/builds/'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/,
use: 'babel-loader'
},
{
test: /\.scss$/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" },
{ loader: "sass-loader" }
]
},
{
test: /\.woff2?$|\.ttf$|\.eot$|\.svg$/,
use: "url-loader"
}
]
},
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery",
}),
],
resolve: {
alias: {
fonts: path.resolve(__dirname, 'web/fonts'),
jquery: path.resolve(__dirname, 'app/Resources/assets/js/jquery-2.1.4.min.js')
}
}
};
|
Remove console statements from tests
Remove console statements from mock objects and functions. | import Text from './text'
import Browser from '../browser';
describe('Text', () => {
describe('clearSelection', () => {
describe('when document.body.createTextRange is defined', () => {
it('calls collapse and select on the text range', () => {
const mockTextRange = {
collapse() {},
select() {}
};
const mockDocument = {
body: {
createTextRange() {
return mockTextRange;
}
}
};
spyOn(mockTextRange, 'collapse');
spyOn(mockTextRange, 'select');
spyOn(Browser, 'getDocument').and.returnValue(mockDocument);
Text.clearSelection();
expect(mockTextRange.collapse).toHaveBeenCalled();
expect(mockTextRange.select).toHaveBeenCalled();
});
});
describe('when window.getSelection is defined', () => {
it('calls removeAllRanges on the selection', () => {
const mockSelection = {
removeAllRanges() {}
};
const mockWindow = {
getSelection() {
return mockSelection;
}
};
spyOn(mockSelection, 'removeAllRanges');
spyOn(Browser, 'getWindow').and.returnValue(mockWindow);
Text.clearSelection();
expect(mockSelection.removeAllRanges).toHaveBeenCalled();
});
});
});
});
| import Text from './text'
import Browser from '../browser';
describe('Text', () => {
describe('clearSelection', () => {
describe('when document.body.createTextRange is defined', () => {
it('calls collapse and select on the text range', () => {
const mockTextRange = {
collapse() {
console.log('range.collapse()');
},
select() {
console.log('range.select()');
}
};
const mockDocument = {
body: {
createTextRange() {
console.log('createTextRange called');
return mockTextRange;
}
}
};
spyOn(mockTextRange, 'collapse');
spyOn(mockTextRange, 'select');
spyOn(Browser, 'getDocument').and.returnValue(mockDocument);
Text.clearSelection();
expect(mockTextRange.collapse).toHaveBeenCalled();
expect(mockTextRange.select).toHaveBeenCalled();
});
});
describe('when window.getSelection is defined', () => {
it('calls removeAllRanges on the selection', () => {
const mockSelection = {
removeAllRanges() {
console.log('removeAllRanges');
}
};
const mockWindow = {
getSelection() {
return mockSelection;
}
};
spyOn(mockSelection, 'removeAllRanges');
spyOn(Browser, 'getWindow').and.returnValue(mockWindow);
Text.clearSelection();
expect(mockSelection.removeAllRanges).toHaveBeenCalled();
});
});
});
});
|
Fix item selection in enum property editor. | /*
* Copyright 2015 Matthew Aguirre
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.l2fprod.common.beans.editor;
import com.l2fprod.common.annotations.EditorRegistry;
import javax.swing.JComboBox;
/**
*
* @author matta
*/
@EditorRegistry(type = Enum.class)
public class EnumerationPropertyEditor extends ComboBoxPropertyEditor {
private Class<?> baseType;
public EnumerationPropertyEditor() {
super();
}
@Override
public Object getValue() {
JComboBox e = (JComboBox) editor;
return e.getSelectedItem();
}
@Override
public void setValue(Object value) {
if (this.baseType == null) {
this.baseType = value.getClass();
setAvailableValues(baseType.getEnumConstants());
}
JComboBox e = (JComboBox) editor;
e.getModel().setSelectedItem(value);
}
}
| /*
* Copyright 2015 Matthew Aguirre
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.l2fprod.common.beans.editor;
import com.l2fprod.common.annotations.EditorRegistry;
import javax.swing.JComboBox;
/**
*
* @author matta
*/
@EditorRegistry(type = Enum.class)
public class EnumerationPropertyEditor extends ComboBoxPropertyEditor {
private Class<?> baseType;
public EnumerationPropertyEditor() {
super();
}
@Override
public Object getValue() {
JComboBox e = (JComboBox) editor;
return e.getSelectedItem();
}
@Override
public void setValue(Object value) {
if (this.baseType == null) {
this.baseType = value.getClass();
setAvailableValues(baseType.getEnumConstants());
}
JComboBox e = (JComboBox) editor;
for (int ii = 0; ii < e.getItemCount(); ii++) {
if (value != null && e.getItemAt(ii).equals(value.getClass().getCanonicalName())) {
e.setSelectedIndex(ii);
break;
}
}
}
}
|
Update the Resume toJSON method.
remove need for 'activeAttributes'. | define([
'underscore',
'backbone',
'models/profile',
'models/address',
'collections/item'
], function (_, Backbone, Profile, Address, ItemCollection) {
'use strict';
var ResumeModel = Backbone.Model.extend({
defaults: {
name: ''
},
hasOne: ['profile', 'address'],
hasMany: ['item'],
parse: function(response) {
var r;
if (response.resume) {
r = response.resume;
} else {
r = response;
}
var options = { resumeId: this.id };
r.address = new Address(r.address, options);
r.profile = new Profile(r.profile, options);
r.items = new ItemCollection(r.items, options);
return r;
},
toJSON: function() {
var json = JSON.parse(JSON.stringify(this.attributes));
// has one associations
_.each(this.hasOne, function(assoc) {
json[assoc + '_id'] = this.get(assoc).id;
delete json[assoc];
}, this);
// has many associations
_.each(this.hasMany, function(assoc) {
json[assoc + '_ids'] = this.get(assoc + 's').map(function(item) {
return item.id;
});
delete json[assoc + 's'];
}, this);
return {
resume: json
};
}
});
return ResumeModel;
});
| define([
'underscore',
'backbone',
'models/profile',
'models/address',
'collections/item'
], function (_, Backbone, Profile, Address, ItemCollection) {
'use strict';
var ResumeModel = Backbone.Model.extend({
defaults: {
name: ''
},
activeAttributes: ['name'],
hasOne: ['profile', 'address'],
hasMany: ['item'],
parse: function(response) {
var r;
if (response.resume) {
r = response.resume;
} else {
r = response;
}
var options = { resumeId: this.id };
r.address = new Address(r.address, options);
r.profile = new Profile(r.profile, options);
return r;
},
toJSON: function() {
var json = {};
_.each(this.activeAttributes, function(attr) {
json[attr] = this.get(attr);
}, this);
_.each(this.hasOne, function(assoc) {
if (this.get(assoc)) {
json[assoc + '_id'] = this.get(assoc).id;
}
}, this);
_.each(this.hasMany, function(assoc) {
json[assoc + '_ids'] = this.get(assoc + '_ids');
}, this);
return { resume: json };
}
});
return ResumeModel;
});
|
Add support for sublime 2 | import sublime_plugin
import sublime
import os
from ..libs.global_vars import IS_ST2
class TypescriptBuildCommand(sublime_plugin.WindowCommand):
def run(self):
file_name = self.window.active_view().file_name()
directory = os.path.dirname(file_name)
if "tsconfig.json" in os.listdir(directory):
self.window.run_command("exec", {
"cmd": "tsc",
"file_regex": "^(.+?)\\((\\d+),(\\d+)\\): (.+)$",
"shell": True
})
else:
sublime.active_window().show_input_panel(
"Build parameters: ",
"", # initial text
self.compile_inferred_project,
None, # on change
None # on cancel
)
def compile_inferred_project(self, params=""):
file_name = self.window.active_view().file_name()
if not IS_ST2:
cmd = "tsc {0} {1}".format(file_name, params)
self.window.run_command("exec", {
"shell_cmd": cmd,
"file_regex": "^(.+?)\\((\\d+),(\\d+)\\): (.+)$"
})
else:
cmd = "tsc {0} {1}".format(file_name, params)
self.window.run_command("exec", {
"cmd": [cmd],
"file_regex": "^(.+?)\\((\\d+),(\\d+)\\): (.+)$",
"shell": True
})
| import sublime_plugin
import sublime
import os
class TypescriptBuildCommand(sublime_plugin.WindowCommand):
def run(self):
file_name = self.window.active_view().file_name()
directory = os.path.dirname(file_name)
if "tsconfig.json" in os.listdir(directory):
self.window.run_command("exec", {
"shell_cmd": "tsc",
"file_regex": "^(.+?)\\((\\d+),(\\d+)\\): (.+)$"
})
else:
sublime.active_window().show_input_panel(
"Build parameters: ",
"", # initial text
self.compile_inferred_project,
None, # on change
None # on cancel
)
def compile_inferred_project(self, params=""):
file_name = self.window.active_view().file_name()
self.window.run_command("exec", {
"shell_cmd": "tsc {0} {1}".format(file_name, params),
"file_regex": "^(.+?)\\((\\d+),(\\d+)\\): (.+)$"
})
|
Change https protocol for Chat component |
/**
* Chat Component
* $("#chat").chat({
* ruleGroupName: "",
* style: ["block"],
* template: [1],
* environment: "1"|"2"|"3"
* });
*/
ui.chat = function(conf) {
var that = ui.object(); // Inheritance
var getDomain = function(n) {
switch (n) {
case "1": return "mercadolidesa.com.ar"; break;
case "2": return "mercadolistage.com.ar"; break;
case "3": return "mercadolibre.com.ar"; break;
}
}
if (conf.msg) {
conf.ruleGroupName = conf.msg;
}
that.load = function() {
loadChatGZ(conf.ruleGroupName, conf.element.id, conf.style||"block", conf.template||"1",conf.environment||"3");
}
ui.get({
method: "component",
name: "chat",
script: "https://www."+getDomain(conf.environment)+"/org-img/jsapi/chat/chatRBIScript.js",
callback: function() {
that.load();
}
});
that.publish = {
uid: conf.uid,
element: conf.element,
type: conf.type
}
return that.publish;
}
|
/**
* Chat Component
* $("#chat").chat({
* ruleGroupName: "",
* style: ["block"],
* template: [1],
* environment: "1"|"2"|"3"
* });
*/
ui.chat = function(conf) {
var that = ui.object(); // Inheritance
var getDomain = function(n) {
switch (n) {
case "1": return "mercadolidesa.com.ar"; break;
case "2": return "mercadolistage.com.ar"; break;
case "3": return "mercadolibre.com.ar"; break;
}
}
if (conf.msg) {
conf.ruleGroupName = conf.msg;
}
that.load = function() {
loadChatGZ(conf.ruleGroupName, conf.element.id, conf.style||"block", conf.template||"1",conf.environment||"3");
}
ui.get({
method: "component",
name: "chat",
script: "http://www."+getDomain(conf.environment)+"/org-img/jsapi/chat/chatRBIScript.js",
callback: function() {
that.load();
}
});
that.publish = {
uid: conf.uid,
element: conf.element,
type: conf.type
}
return that.publish;
}
|
Remove last reference to OneOf Generator | <?php
use Eris\TestTrait;
use Eris\Generator;
class ElementsTest extends \PHPUnit_Framework_TestCase
{
use TestTrait;
public function testElementsOnlyProducesElementsFromTheGivenArguments()
{
$this->forAll([
Generator\elements(1, 2, 3),
])
->__invoke(function($number) {
$this->assertContains(
$number,
[1, 2, 3]
);
});
}
/**
* This means you cannot have a Elements Generator with a single element,
* which is perfectly fine as if you have a single element this generator
* is useless. Use Constant Generator instead
*/
public function testElementsOnlyProducesElementsFromTheGivenArrayDomain()
{
$this->forAll([
Generator\elements([1, 2, 3]),
])
->__invoke(function($number) {
$this->assertContains(
$number,
[1, 2, 3]
);
});
}
public function testVectorOfElementsGenerators()
{
$this->forAll([
Generator\vector(4,
Generator\elements([2, 4, 6, 8, 10, 12])
)
])
->__invoke(function($vector) {
$sum = array_sum($vector);
$isEven = function($number) { return $mumber % 2 == 0; };
$this->assertTrue(
$isEven($sum),
"$sum is not even, but it's the sum of the vector " . var_export($vector, true)
);
});
}
}
| <?php
use Eris\TestTrait;
use Eris\Generator;
class ElementsTest extends \PHPUnit_Framework_TestCase
{
use TestTrait;
public function testElementsOnlyProducesElementsFromTheGivenArguments()
{
$this->forAll([
Generator\elements(1, 2, 3),
])
->__invoke(function($number) {
$this->assertContains(
$number,
[1, 2, 3]
);
});
}
/**
* This means you cannot have a oneOf Generator with a single element,
* which is perfectly fine as if you have a single
* element this generator is useless.
*/
public function testElementsOnlyProducesElementsFromTheGivenArrayDomain()
{
$this->forAll([
Generator\elements([1, 2, 3]),
])
->__invoke(function($number) {
$this->assertContains(
$number,
[1, 2, 3]
);
});
}
public function testVectorOfElementsGenerators()
{
$this->forAll([
Generator\vector(4,
Generator\elements([2, 4, 6, 8, 10, 12])
)
])
->__invoke(function($vector) {
$sum = array_sum($vector);
$isEven = function($number) { return $mumber % 2 == 0; };
$this->assertTrue(
$isEven($sum),
"$sum is not even, but it's the sum of the vector " . var_export($vector, true)
);
});
}
}
|
Add ID of scheduled maintenance to list group item
This allows us to use a static URL to a scheduled maintenance. | <div class="timeline schedule">
<div class="panel panel-default">
<div class="panel-heading">
<strong>{{ trans('cachet.incidents.scheduled') }}</strong>
</div>
<div class="list-group">
@foreach($scheduled_maintenance as $schedule)
<div class="list-group-item" id="scheduled-{{ $schedule->id }}">
<strong>{{ $schedule->name }}</strong> <small class="date"><abbr class="timeago" data-toggle="tooltip" data-placement="right" title="{{ $schedule->scheduled_at_formatted }}" data-timeago="{{ $schedule->scheduled_at_iso }}"></abbr></small>
<div class="markdown-body">
{!! $schedule->formatted_message !!}
</div>
@if($schedule->components->count() > 0)
<hr>
@foreach($schedule->components as $affected_component)
<span class="label label-primary">{{ $affected_component->component->name }}</span>
@endforeach
@endif
</div>
@endforeach
</div>
</div>
</div>
| <div class="timeline schedule">
<div class="panel panel-default">
<div class="panel-heading">
<strong>{{ trans('cachet.incidents.scheduled') }}</strong>
</div>
<div class="list-group">
@foreach($scheduled_maintenance as $schedule)
<div class="list-group-item">
<strong>{{ $schedule->name }}</strong> <small class="date"><abbr class="timeago" data-toggle="tooltip" data-placement="right" title="{{ $schedule->scheduled_at_formatted }}" data-timeago="{{ $schedule->scheduled_at_iso }}"></abbr></small>
<div class="markdown-body">
{!! $schedule->formatted_message !!}
</div>
@if($schedule->components->count() > 0)
<hr>
@foreach($schedule->components as $affected_component)
<span class="label label-primary">{{ $affected_component->component->name }}</span>
@endforeach
@endif
</div>
@endforeach
</div>
</div>
</div>
|
Increase timeout for Wit.ai speech-to-text plugin | var Donna = require('../../src/');
var assert = require("assert");
describe('Wit.ai Plugin', function() {
describe('#intent extraction()', function() {
beforeEach(function(done) {
// Init Donna
var donna = new Donna({
logger: {
// level: 'error'
}
});
// Store Donna
this.donna = donna;
done();
})
it('should extract Intent from Input with Wit.ai',
function(done) {
var donna = this.donna;
this.timeout(5*1000); // Increase timeout for slow networks
// Create InputEntity instance
var input = donna.createInputEntity({
senseTypes: [],
dataTypes: ['text'],
data: {
'text': 'Hello!'
},
context: {}
});
assert(input instanceof Donna.InputEntity);
// Mock the .intent API
donna.intent = function(intent) {
donna.logger.debug("Intent received:", intent);
assert(intent instanceof Donna.IntentEntity);
done();
};
// Process the InputEntity
donna.input(input)
.then(function() {
assert(true);
})
.catch(function(error) {
done(error);
});
});
});
});
| var Donna = require('../../src/');
var assert = require("assert");
describe('Wit.ai Plugin', function() {
describe('#intent extraction()', function() {
beforeEach(function(done) {
// Init Donna
var donna = new Donna({
logger: {
// level: 'error'
}
});
// Store Donna
this.donna = donna;
done();
})
it('should extract Intent from Input with Wit.ai',
function(done) {
var donna = this.donna;
// Create InputEntity instance
var input = donna.createInputEntity({
senseTypes: [],
dataTypes: ['text'],
data: {
'text': 'Hello!'
},
context: {}
});
assert(input instanceof Donna.InputEntity);
// Mock the .intent API
donna.intent = function(intent) {
donna.logger.debug("Intent received:", intent);
assert(intent instanceof Donna.IntentEntity);
done();
};
// Process the InputEntity
donna.input(input)
.then(function() {
assert(true);
})
.catch(function(error) {
done(error);
});
});
});
});
|
Add cors header status code | <?php
namespace App\Middleware;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Slim\Container;
/**
* CORS preflight middleware.
*/
class CorsMiddleware
{
/**
* @var Container
*/
protected $container;
/**
* Constructor.
*
* @param Container $container
*/
public function __construct(Container $container)
{
$this->container = $container;
}
/**
* Invoke middleware.
*
* @param ServerRequestInterface $request PSR7 request
* @param ResponseInterface $response PSR7 response
* @param callable $next Next middleware
*
* @return ResponseInterface PSR7 response
*/
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next): ResponseInterface
{
if (PHP_SAPI === 'cli' || $request->getMethod() !== 'OPTIONS') {
return $next($request, $response);
}
$response = $next($request, $response);
/** @var ResponseInterface $response */
$response = $response->withHeader('Access-Control-Allow-Origin', '*');
$response = $response->withHeader('Access-Control-Allow-Methods', $request->getHeaderLine('Access-Control-Request-Method'));
$response = $response->withHeader('Access-Control-Allow-Headers', $request->getHeaderLine('Access-Control-Request-Headers'));
$response = $response->withStatus(200);
return $response;
}
}
| <?php
namespace App\Middleware;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Slim\Container;
/**
* CORS preflight middleware.
*/
class CorsMiddleware
{
/**
* @var Container
*/
protected $container;
/**
* Constructor.
*
* @param Container $container
*/
public function __construct(Container $container)
{
$this->container = $container;
}
/**
* Invoke middleware.
*
* @param ServerRequestInterface $request PSR7 request
* @param ResponseInterface $response PSR7 response
* @param callable $next Next middleware
*
* @return ResponseInterface PSR7 response
*/
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next): ResponseInterface
{
if (PHP_SAPI === 'cli' || $request->getMethod() !== 'OPTIONS') {
return $next($request, $response);
}
$response = $next($request, $response);
/** @var ResponseInterface $response */
$response = $response->withHeader('Access-Control-Allow-Origin', '*');
$response = $response->withHeader('Access-Control-Allow-Methods', $request->getHeaderLine('Access-Control-Request-Method'));
$response = $response->withHeader('Access-Control-Allow-Headers', $request->getHeaderLine('Access-Control-Request-Headers'));
return $response;
}
}
|
Change some logic to the filter instead. | var fs = require('fs');
var utils = require('amd-utils');
var task = {
id : 'init',
author : 'Indigo United',
name : 'Init',
options : {
name: {
description: 'The task name',
'default': 'autofile'
},
dst: {
description: 'Directory where the task will be created',
'default': process.cwd()
}
},
filter: function (opt, next) {
if (utils.string.endsWith(opt.name, '.js')) {
opt.name = opt.name.slice(0, -3);
}
opt.filename = opt.name + '.js';
fs.stat(opt.filename, function (err) {
if (!err || err.code !== 'ENOENT') {
return next(new Error('Filename ' + opt.filename + ' already exists.'));
}
next();
});
},
tasks :
[
{
task: 'cp',
options: {
src: __dirname + '/../base_autofile.js',
dst: '{{dst}}/{{filename}}'
}
},
{
task: 'scaffolding-replace',
options: {
file: '{{dst}}/{{filename}}',
data: {
name: '{{name}}'
}
}
}
]
};
module.exports = task; | var fs = require('fs');
var utils = require('amd-utils');
var task = {
id : 'init',
author : 'Indigo United',
name : 'Init',
options : {
name: {
description: 'The task name',
'default': 'autofile'
},
dst: {
description: 'Directory where the task will be created',
'default': process.cwd()
}
},
filter: function (opt, next) {
if (utils.string.endsWith(opt.name, '.js')) {
opt.name = opt.name.slice(0, -3);
}
opt.filename = opt.name + '.js';
next();
},
tasks :
[
{
task: function (opt, next) {
fs.stat(opt.filename, function (err) {
if (!err || err.code !== 'ENOENT') {
return next(new Error('Filename ' + opt.filename + ' already exists.'));
}
next();
});
}
},
{
task: 'cp',
options: {
src: __dirname + '/../base_autofile.js',
dst: '{{dst}}/{{filename}}'
}
},
{
task: 'scaffolding-replace',
options: {
file: '{{dst}}/{{filename}}',
data: {
name: '{{name}}'
}
}
}
]
};
module.exports = task; |
Fix self-queries ignoring (since self queries are ajax) | <?php
namespace tunect\Yii2JsErrorHandler;
use yii\base\BootstrapInterface;
class Bootstrap implements BootstrapInterface
{
/**
* @inheritdoc
*/
public function bootstrap($app)
{
$name = Module::$moduleName;
if (!$app->hasModule($name)) {
$app->setModule($name, new Module($name));
}
if ($app instanceof \yii\web\Application) {
$rules[] = [
'class' => 'yii\web\GroupUrlRule',
'prefix' => $name,
'rules' => [
'/' => 'default/index',
'<action:[\w-]+>' => 'default/<action>',
],
];
$app->getUrlManager()->addRules($rules, false);
$app->getModule($name)->registerErrorHandler();
} elseif ($app instanceof \yii\console\Application) {
$app->controllerMap = array_merge($app->controllerMap, [
'migrate' => [
'migrationNamespaces' => [
'tunect\Yii2JsErrorHandler\migrations',
],
],
]);
if (empty($app->controllerMap['migrate']['class'])) {
$app->controllerMap['migrate']['class'] = 'yii\console\controllers\MigrateController';
}
}
}
}
| <?php
namespace tunect\Yii2JsErrorHandler;
use yii\base\BootstrapInterface;
class Bootstrap implements BootstrapInterface
{
/**
* @inheritdoc
*/
public function bootstrap($app)
{
if (($app instanceof \yii\web\Application) && $app->request->isAjax) {
return;
}
$name = Module::$moduleName;
if (!$app->hasModule($name)) {
$app->setModule($name, new Module($name));
}
if ($app instanceof \yii\web\Application) {
$rules[] = [
'class' => 'yii\web\GroupUrlRule',
'prefix' => $name,
'rules' => [
'/' => 'default/index',
'<action:[\w-]+>' => 'default/<action>',
],
];
$app->getUrlManager()->addRules($rules, false);
$app->getModule($name)->registerErrorHandler();
} elseif ($app instanceof \yii\console\Application) {
$app->controllerMap = array_merge($app->controllerMap, [
'migrate' => [
'migrationNamespaces' => [
'tunect\Yii2JsErrorHandler\migrations',
],
],
]);
if (empty($app->controllerMap['migrate']['class'])) {
$app->controllerMap['migrate']['class'] = 'yii\console\controllers\MigrateController';
}
}
}
}
|
Handle when an OpenSSL error doesn't contain a reason
(Or any other field)
You can reproduce the error by running:
```
treq.get('https://nile.ghdonline.org')
```
from within a twisted program (and doing the approrpiate deferred stuff).
I'm unsure how to craft a unit test for this | from six import PY3, binary_type, text_type
from cryptography.hazmat.bindings.openssl.binding import Binding
binding = Binding()
ffi = binding.ffi
lib = binding.lib
def exception_from_error_queue(exceptionType):
def text(charp):
if not charp:
return ""
return native(ffi.string(charp))
errors = []
while True:
error = lib.ERR_get_error()
if error == 0:
break
errors.append((
text(lib.ERR_lib_error_string(error)),
text(lib.ERR_func_error_string(error)),
text(lib.ERR_reason_error_string(error))))
raise exceptionType(errors)
def native(s):
"""
Convert :py:class:`bytes` or :py:class:`unicode` to the native
:py:class:`str` type, using UTF-8 encoding if conversion is necessary.
:raise UnicodeError: The input string is not UTF-8 decodeable.
:raise TypeError: The input is neither :py:class:`bytes` nor
:py:class:`unicode`.
"""
if not isinstance(s, (binary_type, text_type)):
raise TypeError("%r is neither bytes nor unicode" % s)
if PY3:
if isinstance(s, binary_type):
return s.decode("utf-8")
else:
if isinstance(s, text_type):
return s.encode("utf-8")
return s
if PY3:
def byte_string(s):
return s.encode("charmap")
else:
def byte_string(s):
return s
| from six import PY3, binary_type, text_type
from cryptography.hazmat.bindings.openssl.binding import Binding
binding = Binding()
ffi = binding.ffi
lib = binding.lib
def exception_from_error_queue(exceptionType):
def text(charp):
return native(ffi.string(charp))
errors = []
while True:
error = lib.ERR_get_error()
if error == 0:
break
errors.append((
text(lib.ERR_lib_error_string(error)),
text(lib.ERR_func_error_string(error)),
text(lib.ERR_reason_error_string(error))))
raise exceptionType(errors)
def native(s):
"""
Convert :py:class:`bytes` or :py:class:`unicode` to the native
:py:class:`str` type, using UTF-8 encoding if conversion is necessary.
:raise UnicodeError: The input string is not UTF-8 decodeable.
:raise TypeError: The input is neither :py:class:`bytes` nor
:py:class:`unicode`.
"""
if not isinstance(s, (binary_type, text_type)):
raise TypeError("%r is neither bytes nor unicode" % s)
if PY3:
if isinstance(s, binary_type):
return s.decode("utf-8")
else:
if isinstance(s, text_type):
return s.encode("utf-8")
return s
if PY3:
def byte_string(s):
return s.encode("charmap")
else:
def byte_string(s):
return s
|
Fix load method response for csv time in columns reader | import CSVReader from 'readers/csv/csv';
import { isNumber } from 'base/utils';
const CSVTimeInColumnsReader = CSVReader.extend({
_name: 'csv-time_in_columns',
init(readerInfo) {
this._super(readerInfo);
},
load() {
return this._super()
.then(({ data, columns }) => {
const indicatorKey = columns[this.keySize];
let concepts = data.reduce((result, row) => {
Object.keys(row).forEach((concept) => {
concept = concept === indicatorKey ? row[indicatorKey] : concept;
if (Number(concept) != concept && !result.includes(concept)) {
result.push(concept);
}
});
return result;
}, []);
concepts.splice(1, 0, 'time');
const indicators = concepts.slice(2);
const [entityDomain] = concepts;
return {
columns: concepts,
data: data.reduce((result, row) => {
Object.keys(row).forEach((key) => {
if (![entityDomain, indicatorKey].includes(key)) {
result.push(
Object.assign({
[entityDomain]: row[entityDomain],
time: key,
}, indicators.reduce((result, indicator) => {
result[indicator] = row[indicatorKey] === indicator ? row[key] : null;
return result;
}, {})
)
);
}
});
return result;
}, [])
};
});
}
});
export default CSVTimeInColumnsReader;
| import CSVReader from 'readers/csv/csv';
import { isNumber } from 'base/utils';
const CSVTimeInColumnsReader = CSVReader.extend({
_name: 'csv-time_in_columns',
init(readerInfo) {
this._super(readerInfo);
},
load() {
return this._super()
.then(({ data, columns }) => {
const indicatorKey = columns[this.keySize];
const concepts = data.reduce((result, row) => {
Object.keys(row).forEach((concept) => {
concept = concept === indicatorKey ? row[indicatorKey] : concept;
if (Number(concept) != concept && !result.includes(concept)) {
result.push(concept);
}
});
return result;
}, []).concat('time');
const indicators = concepts.slice(1, -1);
const [entityDomain] = concepts;
return data.reduce((result, row) => {
Object.keys(row).forEach((key) => {
if (![entityDomain, indicatorKey].includes(key)) {
result.push(
Object.assign({
[entityDomain]: row[entityDomain],
time: key,
}, indicators.reduce((result, indicator) => {
result[indicator] = row[indicatorKey] === indicator ? row[key] : null;
return result;
}, {})
)
);
}
});
return result;
}, []);
});
}
});
export default CSVTimeInColumnsReader;
|
Add helper method phpdoc info | <?php
if (! function_exists('locale')) {
/**
* Get the active locale.
*
* @return string
*/
function locale()
{
return config('app.locale', config('app.fallback_locale'));
}
}
if (! function_exists('carbonize')) {
/**
* Create a Carbon object from a string.
*
* @param string $timeString
*
* @return \Carbon\Carbon
*/
function carbonize($timeString = null)
{
return new \Carbon\Carbon($timeString);
}
}
if (! function_exists('isActiveRoute')) {
/**
* Check if the given route is currently active.
*
* @param string $routeName
* @param string $output
*
* @return bool
*/
function isActiveRoute($routeName, $output = 'active')
{
/** @var \Laravelista\Ekko\Ekko $ekko */
$ekko = app('Laravelista\Ekko\Ekko');
return $ekko->isActiveRoute($routeName, $output);
}
}
if (! function_exists('take')) {
/**
* Create a new piped item from a given value.
*
* @param mixed $value
*
* @return \SebastiaanLuca\Helpers\Pipe\Item
*/
function take($value)
{
return new \SebastiaanLuca\Helpers\Pipe\Item($value);
}
}
| <?php
if (! function_exists('locale')) {
/**
* Get the active locale.
*
* @return string
*/
function locale()
{
return config('app.locale', config('app.fallback_locale'));
}
}
if (! function_exists('carbonize')) {
/**
* Create a Carbon object from a string.
*
* @param string $timeString
*
* @return \Carbon\Carbon
*/
function carbonize($timeString = null)
{
return new \Carbon\Carbon($timeString);
}
}
if (! function_exists('isActiveRoute')) {
/**
* @param string $routeName
* @param string $output
*
* @return bool
*/
function isActiveRoute($routeName, $output = 'active')
{
/** @var \Laravelista\Ekko\Ekko $ekko */
$ekko = app('Laravelista\Ekko\Ekko');
return $ekko->isActiveRoute($routeName, $output);
}
}
if (! function_exists('take')) {
/**
* Create a new piped item from a given value.
*
* @param mixed $value
*
* @return \SebastiaanLuca\Helpers\Pipe\Item
*/
function take($value)
{
return new \SebastiaanLuca\Helpers\Pipe\Item($value);
}
}
|
Use a router to navigate gui's | histomicstk.App = girder.App.extend({
initialize: function () {
girder.fetchCurrentUser()
.done(_.bind(function (user) {
girder.eventStream = new girder.EventStream({
timeout: girder.sseTimeout || null
});
this.headerView = new histomicstk.views.Header({
parentView: this
});
this.bodyView = new histomicstk.views.Body({
parentView: this
});
if (user) {
girder.currentUser = new girder.models.UserModel(user);
girder.eventStream.open();
}
this.render();
Backbone.history.start({pushState: false});
}, this));
girder.events.on('g:loginUi', this.loginDialog, this);
girder.events.on('g:registerUi', this.registerDialog, this);
girder.events.on('g:resetPasswordUi', this.resetPasswordDialog, this);
girder.events.on('g:alert', this.alert, this);
girder.events.on('g:login', this.login, this);
},
render: function () {
this.$el.html(histomicstk.templates.layout());
this.headerView.setElement(this.$('#g-app-header-container')).render();
this.bodyView.setElement(this.$('#g-app-body-container')).render();
return this;
}
});
| histomicstk.App = girder.App.extend({
initialize: function () {
girder.fetchCurrentUser()
.done(_.bind(function (user) {
girder.eventStream = new girder.EventStream({
timeout: girder.sseTimeout || null
});
this.headerView = new histomicstk.views.Header({
parentView: this
});
this.bodyView = new histomicstk.views.Body({
parentView: this
});
if (user) {
girder.currentUser = new girder.models.UserModel(user);
girder.eventStream.open();
}
this.render();
}, this));
girder.events.on('g:loginUi', this.loginDialog, this);
girder.events.on('g:registerUi', this.registerDialog, this);
girder.events.on('g:resetPasswordUi', this.resetPasswordDialog, this);
girder.events.on('g:alert', this.alert, this);
girder.events.on('g:login', this.login, this);
},
render: function () {
this.$el.html(histomicstk.templates.layout());
this.headerView.setElement(this.$('#g-app-header-container')).render();
this.bodyView.setElement(this.$('#g-app-body-container')).render();
return this;
}
});
|
Fix issues with callback function | (function (angular) {
'use strict';
function FlotDirective(eehFlot, $interval) {
return {
restrict: 'AE',
template: '<div class="eeh-flot"></div>',
scope: {
dataset: '=',
options: '@',
updateCallback: '=',
updateCallbackTime: '@'
},
link: function link(scope, element) {
scope.updateCallbackTime = scope.updateCallbackTime || 40;
var renderArea = element.find('.eeh-flot');
var chart = eehFlot(renderArea, scope.dataset, scope.options);
if (angular.isFunction(scope.updateCallback)) {
$interval(function() {
scope.updateCallback(chart, scope.dataset);
}, scope.updateCallbackTime);
}
}
};
}
angular.module('eehFlot').directive('eehFlot', FlotDirective);
})(angular);
| (function (angular) {
'use strict';
function FlotDirective(eehFlot, $interval) {
return {
restrict: 'AE',
template: '<div class="eeh-flot"></div>',
scope: {
dataset: '=',
options: '@',
updateCallback: '&',
updateCallbackTime: '@'
},
link: function link(scope, element) {
scope.updateCallbackTime = scope.updateCallbackTime || 1000;
var renderArea = element.find('.eeh-flot');
var chart = eehFlot(renderArea, scope.dataset, scope.options);
if (angular.isDefined(scope.updateCallback) &&
angular.isFunction(scope.updateCallback)) {
$interval(function() {
scope.updateCallback(chart, scope.dataset);
}, scope.updateCallbackTime);
}
}
};
}
angular.module('eehFlot').directive('eehFlot', FlotDirective);
})(angular);
|
Revert "Remove commonjs in top level"
This reverts commit a2690e601c457d27966adc6d074b9966f906e1b7. | import commonjs from '@rollup/plugin-commonjs';
import glslify from 'rollup-plugin-glslify';
import resolve from '@rollup/plugin-node-resolve';
import copy from "rollup-plugin-copy";
export default {
input: ['source/gltf-sample-viewer.js'],
output: [
{
file: 'dist/gltf-viewer.js',
format: 'cjs',
sourcemap: true
},
{
file: 'dist/gltf-viewer.module.js',
format: 'esm',
sourcemap: true,
}
],
plugins: [
glslify(),
copy({
targets: [
{
src: [
"assets/images/lut_charlie.png",
"assets/images/lut_ggx.png",
"assets/images/lut_sheen_E.png",
], dest: "dist/assets"
},
{ src: ["source/libs/*", "!source/libs/hdrpng.js"], dest: "dist/libs" }
]
}),
commonjs(),
]
};
| import commonjs from '@rollup/plugin-commonjs';
import glslify from 'rollup-plugin-glslify';
import resolve from '@rollup/plugin-node-resolve';
import copy from "rollup-plugin-copy";
export default {
input: ['source/gltf-sample-viewer.js'],
output: [
{
file: 'dist/gltf-viewer.js',
format: 'cjs',
sourcemap: true
},
{
file: 'dist/gltf-viewer.module.js',
format: 'esm',
sourcemap: true,
}
],
plugins: [
glslify(),
copy({
targets: [
{
src: [
"assets/images/lut_charlie.png",
"assets/images/lut_ggx.png",
"assets/images/lut_sheen_E.png",
], dest: "dist/assets"
},
{ src: ["source/libs/*", "!source/libs/hdrpng.js"], dest: "dist/libs" }
]
}),
]
};
|
Add stacktrace to java test failures | package brlyman;
import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunListener;
import java.util.*;
import org.junit.runner.Description;
import org.junit.runner.Result;
import brlyman.results.*;
import brlyman.results.processes.*;
public class TurboListener extends RunListener
{
public TurboListener(final Logger log)
{
this.log = log;
this.root = new Context("Test Suite");
}
public void
testRunStarted(final Description description) throws Exception
{
}
public void
testRunFinished(final Result result) throws Exception
{
root.apply(new PrintContexts(log));
root = new Context("Test Suite");
}
public void
testStarted(final Description description) throws Exception
{
}
public void
testFinished(final Description description) throws Exception
{
root.addTestResult(
Arrays.asList(
description.getClassName().split("\\$")),
new Pass(
description.getMethodName()));
}
public void
testFailure(final Failure failure) throws Exception
{
root.addTestResult(
Arrays.asList(
failure.getDescription().getClassName().split("\\$")),
new Fail(
failure.getDescription().getMethodName(),
failure.getMessage() + "\n" + failure.getTrace()));
}
public void
testAssumptionFailure(final Failure failure)
{
log.error(failure.getMessage());
}
public void
testIgnored(final Description description) throws Exception
{
log.warn(description.getMethodName() + " ignored");
}
private Context root;
private final Logger log;
}
| package brlyman;
import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunListener;
import java.util.*;
import org.junit.runner.Description;
import org.junit.runner.Result;
import brlyman.results.*;
import brlyman.results.processes.*;
public class TurboListener extends RunListener
{
public TurboListener(final Logger log)
{
this.log = log;
this.root = new Context("Test Suite");
}
public void
testRunStarted(final Description description) throws Exception
{
}
public void
testRunFinished(final Result result) throws Exception
{
root.apply(new PrintContexts(log));
root = new Context("Test Suite");
}
public void
testStarted(final Description description) throws Exception
{
}
public void
testFinished(final Description description) throws Exception
{
root.addTestResult(
Arrays.asList(
description.getClassName().split("\\$")),
new Pass(
description.getMethodName()));
}
public void
testFailure(final Failure failure) throws Exception
{
root.addTestResult(
Arrays.asList(
failure.getDescription().getClassName().split("\\$")),
new Fail(
failure.getDescription().getMethodName(),
failure.getMessage()));
}
public void
testAssumptionFailure(final Failure failure)
{
log.error(failure.getMessage());
}
public void
testIgnored(final Description description) throws Exception
{
log.warn(description.getMethodName() + " ignored");
}
private Context root;
private final Logger log;
}
|
:art: Refactor rule to work with gonzales 3.2.1 | 'use strict';
var helpers = require('../helpers');
module.exports = {
'name': 'space-after-comma',
'defaults': {
'include': true
},
'detect': function (ast, parser) {
var result = [];
ast.traverseByTypes(['operator', 'delimiter'], function (operator, i, parent) {
var next,
doubleNext;
if (operator.content === ',') {
next = parent.content[i + 1] || false;
doubleNext = parent.content[i + 2] || false;
if (next) {
if (operator.is('delimiter')) {
if (next.is('selector')) {
next = next.content[0];
}
}
if ((next.is('space') && !helpers.hasEOL(next.content)) && !parser.options.include) {
if (doubleNext && doubleNext.is('singlelineComment')) {
return false;
}
result = helpers.addUnique(result, {
'ruleId': parser.rule.name,
'line': next.start.line,
'column': next.start.column,
'message': 'Commas should not be followed by a space',
'severity': parser.severity
});
}
if (!next.is('space') && parser.options.include) {
result = helpers.addUnique(result, {
'ruleId': parser.rule.name,
'line': operator.start.line,
'column': operator.start.column,
'message': 'Commas should be followed by a space',
'severity': parser.severity
});
}
}
}
});
return result;
}
};
| 'use strict';
var helpers = require('../helpers');
module.exports = {
'name': 'space-after-comma',
'defaults': {
'include': true
},
'detect': function (ast, parser) {
var result = [];
ast.traverseByTypes(['operator', 'delimiter'], function (operator, i, parent) {
var next;
if (operator.content === ',') {
next = parent.content[i + 1];
if (next) {
if (operator.is('delimiter')) {
if (next.is('simpleSelector')) {
next = next.content[0];
}
}
if ((next.is('space') && !helpers.hasEOL(next.content)) && !parser.options.include) {
result = helpers.addUnique(result, {
'ruleId': parser.rule.name,
'line': next.start.line,
'column': next.start.column,
'message': 'Commas should not be followed by a space',
'severity': parser.severity
});
}
if (!next.is('space') && parser.options.include) {
result = helpers.addUnique(result, {
'ruleId': parser.rule.name,
'line': operator.start.line,
'column': operator.start.column,
'message': 'Commas should be followed by a space',
'severity': parser.severity
});
}
}
}
});
return result;
}
};
|
Change style for admin language panel | <?php
namespace Purethink\CMSBundle\Admin;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;
class Language extends Admin
{
protected $translationDomain = 'PurethinkCMSBundle';
protected $datagridValues = [
'_sort_by' => 'name'
];
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->with('General', ['class' => 'col-md-8'])
->add('name')
->add('alias')
->end()
->with('Options', ['class' => 'col-md-4'])
->add('enabled', null, ['required' => false])
->end();
}
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper
->add('id')
->add('name')
->add('alias')
->add('enabled');
}
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->addIdentifier('id')
->addIdentifier('name')
->add("alias")
->add('enabled', null, ['editable' => true]);
}
}
| <?php
namespace Purethink\CMSBundle\Admin;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;
class Language extends Admin
{
protected $translationDomain = 'PurethinkCMSBundle';
protected $datagridValues = [
'_sort_by' => 'name'
];
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->with('General')
->add('name')
->add('alias')
->add('enabled', null, ['required' => false])
->end();
}
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper
->add('id')
->add('name')
->add('alias')
->add('enabled');
}
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->addIdentifier('id')
->addIdentifier('name')
->add("alias")
->add('enabled', null, ['editable' => true]);
}
}
|
Change validate HTTP method to PUT | import flask
from flask import request, json
def Response(data, status = 200):
body = json.dumps(data)
return flask.Response(body, status = status, mimetype = 'application/json')
def SuccessResponse(dataset_id = None):
return Response({ 'success': True, 'id': dataset_id })
def ErrorResponse(status = 400):
return Response({ 'success': False }, status = status)
def API(name, backend):
app = flask.Flask(name)
app.config.from_object(name)
@app.route('/')
def api_root():
return SuccessResponse(backend.dataset_id)
@app.route('/load', methods=['POST'])
def api_load():
backend.load(request.json)
return SuccessResponse(backend.dataset_id)
@app.route('/fit', methods=['POST'])
def api_fit():
if not backend.loaded():
return ErrorResponse()
backend.fit()
return SuccessResponse(backend.dataset_id)
@app.route('/validate', methods=['PUT'])
def api_validate():
if not backend.loaded():
return ErrorResponse()
data = backend.validate()
return Response(data)
@app.route('/predict', methods=['PUT'])
def api_predict():
if not backend.trained():
return ErrorResponse()
data = backend.predict(request.json).tolist()
return Response(data)
return app
| import flask
from flask import request, json
def Response(data, status = 200):
body = json.dumps(data)
return flask.Response(body, status = status, mimetype = 'application/json')
def SuccessResponse(dataset_id = None):
return Response({ 'success': True, 'id': dataset_id })
def ErrorResponse(status = 400):
return Response({ 'success': False }, status = status)
def API(name, backend):
app = flask.Flask(name)
app.config.from_object(name)
@app.route('/')
def api_root():
return SuccessResponse(backend.dataset_id)
@app.route('/load', methods=['POST'])
def api_load():
backend.load(request.json)
return SuccessResponse(backend.dataset_id)
@app.route('/fit', methods=['POST'])
def api_fit():
if not backend.loaded():
return ErrorResponse()
backend.fit()
return SuccessResponse(backend.dataset_id)
@app.route('/validate', methods=['POST'])
def api_validate():
if not backend.loaded():
return ErrorResponse()
data = backend.validate()
return Response(data)
@app.route('/predict', methods=['PUT'])
def api_predict():
if not backend.trained():
return ErrorResponse()
data = backend.predict(request.json).tolist()
return Response(data)
return app
|
Fix wrong path for jscoverage report | module.exports = function(config) {
config.set({
basePath: '../../',
files: [
'web/js/vendor/angular.js',
'web/js/vendor/angular-*.js',
'test/lib/angular/angular-mocks.js',
'web/js/vendor/jquery*.js',
'web/js/**/*.js',
'test/unit/**/*.js'
],
autoWatch: false,
singleRun: true,
browsers: ['PhantomJS', 'Firefox'],
frameworks: ["jasmine"],
reporters: ['dots', 'junit', 'coverage'],
preprocessors: {
// source files, that you wanna generate coverage for
// do not include tests or libraries
// (these files will be instrumented by Istanbul)
'web/js/*.js': ['coverage']
},
junitReporter: {
outputFile: 'app/build/logs/js_unit.xml',
suite: 'unit'
},
coverageReporter: {
type : 'html',
dir : 'app/build/jscoverage/'
},
reportSlowerThan: 500,
});
};
| module.exports = function(config) {
config.set({
basePath: '../../',
files: [
'web/js/vendor/angular.js',
'web/js/vendor/angular-*.js',
'test/lib/angular/angular-mocks.js',
'web/js/vendor/jquery*.js',
'web/js/**/*.js',
'test/unit/**/*.js'
],
autoWatch: false,
singleRun: true,
browsers: ['PhantomJS', 'Firefox'],
frameworks: ["jasmine"],
reporters: ['dots', 'junit', 'coverage'],
preprocessors: {
// source files, that you wanna generate coverage for
// do not include tests or libraries
// (these files will be instrumented by Istanbul)
'web/js/*.js': ['coverage']
},
junitReporter: {
outputFile: 'app/build/logs/js_unit.xml',
suite: 'unit'
},
coverageReporter: {
type : 'html',
dir : 'app/build/logs/jscoverage/'
},
reportSlowerThan: 500,
});
};
|
Use getKey for both sensors and actuators | <?php
namespace actsmart\actsmart;
use actsmart\actsmart\Sensors\SensorInterface;
use actsmart\actsmart\Controllers\ControllerInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpFoundation\Response;
class Agent
{
/** @var SensorInterface */
protected $sensors;
/** @var EventDispatcher */
protected $dispatcher;
/** @var Response */
protected $http_response = null;
public function __construct(EventDispatcher $dispatcher)
{
$this->dispatcher = $dispatcher;
}
public function addSensor(SensorInterface $sensor)
{
$this->sensors[$sensor->getKey()] = $sensor;
}
/**
* Makes an infostore a listener to sensor events.
*
* @param $sensor
* @param $infostore
*/
public function bindSensorToStore($sensor, $store)
{
$this->dispatcher->addListener($sensor->getEventName(), array($store, 'store'));
}
public function bindSensorToController(SensorInterface $sensor, ControllerInterface $controller)
{
$this->dispatcher->addListener($sensor->getEventName(), array($controller, 'execute'));
}
public function sensorReceive($sensor_key, $message)
{
return $this->sensors[$sensor_key]->receive($message);
}
public function setHttpReaction(Response $response)
{
$this->http_response = $response;
}
public function httpReact()
{
if ($this->http_response == null) {
return new Response('', Response::HTTP_OK, ['content-type' => 'text/html']);
}
return $this->http_response;
}
} | <?php
namespace actsmart\actsmart;
use actsmart\actsmart\Sensors\SensorInterface;
use actsmart\actsmart\Controllers\ControllerInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpFoundation\Response;
class Agent
{
/** @var SensorInterface */
protected $sensors;
/** @var EventDispatcher */
protected $dispatcher;
/** @var Response */
protected $http_response = null;
public function __construct(EventDispatcher $dispatcher)
{
$this->dispatcher = $dispatcher;
}
public function addSensor(SensorInterface $sensor)
{
$this->sensors[$sensor->getName()] = $sensor;
}
/**
* Makes an infostore a listener to sensor events.
*
* @param $sensor
* @param $infostore
*/
public function bindSensorToStore($sensor, $store)
{
$this->dispatcher->addListener($sensor->getEventName(), array($store, 'store'));
}
public function bindSensorToController(SensorInterface $sensor, ControllerInterface $controller)
{
$this->dispatcher->addListener($sensor->getEventName(), array($controller, 'execute'));
}
public function sensorReceive($sensor_name, $message)
{
return $this->sensors[$sensor_name]->receive($message);
}
public function setHttpReaction(Response $response)
{
$this->http_response = $response;
}
public function httpReact()
{
if ($this->http_response == null) {
return new Response('', Response::HTTP_OK, ['content-type' => 'text/html']);
}
return $this->http_response;
}
} |
Move and take out the col-md-8 piece | <h3>Change Access</h3>
<form class="form-horizontal">
<!-- Select Basic -->
<div class="form-group">
<div class="col-md-8">
<label class="control-label" for="access-type">Select Access Type</label>
<?php
$types = $dal->getAccessTypes();
$selected_user = $_GET['for'];
$curr = $dal->getUserAccessLevel($selected_user);
$level_options = '';
?>
<select id="access-type" name="access-type" class="form-control">
<option disabled>Select Access Type</option>
<?php
foreach ($types as $row) {
$level_options .= '';
//$level_options .= "<option value=".$row['id'].">".$row['type']."</option>";
}
echo $level_options;
/*
if ($types) {
foreach ($types as $row) {
$option = "<option value='".$row['type']."' ";
if ($row['type'] == $curr) {
$option .= "selected>$row['type']</option>";
} else {
$option .= ">$row['type']</option>";
}
echo $option;
}
}
*/
?>
</select>
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-8 control-label" for="submit"></label>
<div class="col-md-8">
<button id="submit" name="submit" class="btn btn-primary">Update</button>
</div>
</div>
</form>
| <h3>Change Access</h3>
<form class="form-horizontal">
<!-- Select Basic -->
<div class="form-group">
<label class="col-md-8 control-label" for="access-type">Select Access Type</label>
<div class="col-md-8">
<?php
$types = $dal->getAccessTypes();
$selected_user = $_GET['for'];
$curr = $dal->getUserAccessLevel($selected_user);
$level_options = '';
?>
<select id="access-type" name="access-type" class="form-control">
<option disabled>Select Access Type</option>
<?php
foreach ($types as $row) {
$level_options .= '';
//$level_options .= "<option value=".$row['id'].">".$row['type']."</option>";
}
echo $level_options;
/*
if ($types) {
foreach ($types as $row) {
$option = "<option value='".$row['type']."' ";
if ($row['type'] == $curr) {
$option .= "selected>$row['type']</option>";
} else {
$option .= ">$row['type']</option>";
}
echo $option;
}
}
*/
?>
</select>
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-8 control-label" for="submit"></label>
<div class="col-md-8">
<button id="submit" name="submit" class="btn btn-primary">Update</button>
</div>
</div>
</form>
|
Update ID to match others | from ansiblelint import AnsibleLintRule
try:
from types import StringTypes
except ImportError:
# Python3 removed types.StringTypes
StringTypes = str,
class NoFormattingInWhenRule(AnsibleLintRule):
id = 'ANSIBLE0019'
shortdesc = 'No Jinja2 in when'
description = '"when" lines should not include Jinja2 variables'
tags = ['deprecated']
def _is_valid(self, when):
if not isinstance(when, StringTypes):
return True
return when.find('{{') == -1 and when.find('}}') == -1
def matchplay(self, file, play):
errors = []
if isinstance(play, dict):
if 'roles' not in play:
return errors
for role in play['roles']:
if self.matchtask(file, role):
errors.append(({'when': role},
'role "when" clause has Jinja2 templates'))
if isinstance(play, list):
for play_item in play:
sub_errors = self.matchplay(file, play_item)
if sub_errors:
errors = errors + sub_errors
return errors
def matchtask(self, file, task):
return 'when' in task and not self._is_valid(task['when'])
| from ansiblelint import AnsibleLintRule
try:
from types import StringTypes
except ImportError:
# Python3 removed types.StringTypes
StringTypes = str,
class NoFormattingInWhenRule(AnsibleLintRule):
id = 'CINCH0001'
shortdesc = 'No Jinja2 in when'
description = '"when" lines should not include Jinja2 variables'
tags = ['deprecated']
def _is_valid(self, when):
if not isinstance(when, StringTypes):
return True
return when.find('{{') == -1 and when.find('}}') == -1
def matchplay(self, file, play):
errors = []
if isinstance(play, dict):
if 'roles' not in play:
return errors
for role in play['roles']:
if self.matchtask(file, role):
errors.append(({'when': role},
'role "when" clause has Jinja2 templates'))
if isinstance(play, list):
for play_item in play:
sub_errors = self.matchplay(file, play_item)
if sub_errors:
errors = errors + sub_errors
return errors
def matchtask(self, file, task):
return 'when' in task and not self._is_valid(task['when'])
|
Add debugging statement to retrieve_passages function | # LING 573 Question Answering System
# Code last updated 4/17/14 by Clara Gordon
# This code implements an InfoRetriever for the question answering system.
from pymur import *
from general_classes import *
import sys
class InfoRetriever:
# builds a QueryEnvironment associated with the indexed document collection
def __init__(self, index_path):
# how to get this to link up to the doc collection?
self.path_to_idx = index_path
self.index = Index(self.path_to_idx)
self.query_env = QueryEnvironment()
self.query_env.addIndex(self.path_to_idx)
# creates a list of all the passages returned by all the queries generated by
# the query-processing module
def retrieve_passages(self, queries):
passages = []
for query in queries:
query = " ".join(query)
sys.stderr.write(query)
# second argument is the number of documents desired
docs = self.query_env.runQuery("#combine[passage50:25](" + query + ")", 20)
for doc in docs:
doc_num = doc.document
begin = doc.begin
end = doc.end
doc_id = self.query_env.documents([doc_num])[0].metadata['docno'] # need this for output
passage = Passage(self.index.document(doc_num, True)[begin:end], doc.score, doc_id)
passages.append(passage)
return passages
| # LING 573 Question Answering System
# Code last updated 4/17/14 by Clara Gordon
# This code implements an InfoRetriever for the question answering system.
from pymur import *
from general_classes import *
class InfoRetriever:
# builds a QueryEnvironment associated with the indexed document collection
def __init__(self, index_path):
# how to get this to link up to the doc collection?
self.path_to_idx = index_path
self.index = Index(self.path_to_idx)
self.query_env = QueryEnvironment()
self.query_env.addIndex(self.path_to_idx)
# creates a list of all the passages returned by all the queries generated by
# the query-processing module
def retrieve_passages(self, queries):
passages = []
for query in queries:
query = " ".join(query)
# second argument is the number of documents desired
docs = self.query_env.runQuery("#combine[passage50:25](" + query + ")", 20)
for doc in docs:
doc_num = doc.document
begin = doc.begin
end = doc.end
doc_id = self.query_env.documents([doc_num])[0].metadata['docno'] # need this for output
passage = Passage(self.index.document(doc_num, True)[begin:end], doc.score, doc_id)
passages.append(passage)
return passages
|
Add `miniplug:ws` debug namespace, logging all incoming events | import login from 'plug-login'
import socket from 'plug-socket'
import createDebug from 'debug'
const debug = createDebug('miniplug:connect')
const debugWs = createDebug('miniplug:ws')
export default function connectPlugin (options = {}) {
return (mp) => {
// log in
const loginOpts = { host: options.host, authToken: true }
function connect (opts) {
debug('connecting', opts.email)
const loginPromise = Promise.resolve(
opts.email
? login.user(opts.email, opts.password, loginOpts)
: login.guest(loginOpts)
)
const ws = socket()
ws.setMaxListeners(100)
ws.on('action', (type, payload) => {
debugWs(type, payload)
})
const connected = loginPromise
.then((res) => new Promise((resolve, reject) => {
ws.auth(res.token)
ws.once('error', reject)
mp.isConnected = true
mp.emit('login')
const me = mp.getMe()
ws.once('ack', () => {
resolve({ cookie: res.cookie })
ws.removeListener('error', reject)
me.then((user) => mp.emit('connected', user))
})
}))
.catch((err) => {
mp.emit('error', err)
throw err
})
mp.ws = ws
mp.connected = connected
return connected
}
mp.connect = connect
}
}
| import login from 'plug-login'
import socket from 'plug-socket'
import createDebug from 'debug'
const debug = createDebug('miniplug:connect')
export default function connectPlugin (options = {}) {
return (mp) => {
// log in
const loginOpts = { host: options.host, authToken: true }
function connect (opts) {
debug('connecting', opts.email)
const loginPromise = Promise.resolve(
opts.email
? login.user(opts.email, opts.password, loginOpts)
: login.guest(loginOpts)
)
const ws = socket()
ws.setMaxListeners(100)
const connected = loginPromise
.then((res) => new Promise((resolve, reject) => {
ws.auth(res.token)
ws.once('error', reject)
mp.isConnected = true
mp.emit('login')
const me = mp.getMe()
ws.once('ack', () => {
resolve({ cookie: res.cookie })
ws.removeListener('error', reject)
me.then((user) => mp.emit('connected', user))
})
}))
.catch((err) => {
mp.emit('error', err)
throw err
})
mp.ws = ws
mp.connected = connected
return connected
}
mp.connect = connect
}
}
|
Fix last commit: Must ensure GUID before saving so that PK is defined | from framework import StoredObject, fields
class Guid(StoredObject):
_id = fields.StringField()
referent = fields.AbstractForeignField()
_meta = {
'optimistic': True,
}
class GuidStoredObject(StoredObject):
# Redirect to content using URL redirect by default
redirect_mode = 'redirect'
def _ensure_guid(self):
"""Create GUID record if current record doesn't already have one, then
point GUID to self.
"""
# Create GUID with specified ID if ID provided
if self._primary_key:
# Done if GUID already exists
guid = Guid.load(self._primary_key)
if guid is not None:
return
# Create GUID
guid = Guid(
_id=self._primary_key,
referent=self
)
guid.save()
# Else create GUID optimistically
else:
# Create GUID
guid = Guid()
guid.save()
guid.referent = (guid._primary_key, self._name)
guid.save()
# Set primary key to GUID key
self._primary_key = guid._primary_key
def save(self, *args, **kwargs):
""" Ensure GUID on save initialization. """
self._ensure_guid()
return super(GuidStoredObject, self).save(*args, **kwargs)
@property
def annotations(self):
""" Get meta-data annotations associated with object. """
return self.metadata__annotated
| from framework import StoredObject, fields
class Guid(StoredObject):
_id = fields.StringField()
referent = fields.AbstractForeignField()
_meta = {
'optimistic': True,
}
class GuidStoredObject(StoredObject):
# Redirect to content using URL redirect by default
redirect_mode = 'redirect'
def _ensure_guid(self):
"""Create GUID record if current record doesn't already have one, then
point GUID to self.
"""
# Create GUID with specified ID if ID provided
if self._primary_key:
# Done if GUID already exists
guid = Guid.load(self._primary_key)
if guid is not None:
return
# Create GUID
guid = Guid(
_id=self._primary_key,
referent=self
)
guid.save()
# Else create GUID optimistically
else:
# Create GUID
guid = Guid()
guid.save()
guid.referent = (guid._primary_key, self._name)
guid.save()
# Set primary key to GUID key
self._primary_key = guid._primary_key
def save(self, *args, **kwargs):
""" Ensure GUID on save initialization. """
rv = super(GuidStoredObject, self).save(*args, **kwargs)
self._ensure_guid()
return rv
@property
def annotations(self):
""" Get meta-data annotations associated with object. """
return self.metadata__annotated
|
Use try/catch for loading mapfiles. |
/**
* Small wrapper around node-pool. Establishes a pool of 5 mapnik map objects
* per mapfile.
* @TODO: Make pool size configurable.
*/
module.exports = new function() {
return {
pools: {},
acquire: function(mapfile, options, callback) {
if (!this.pools[mapfile]) {
this.pools[mapfile] = require('generic-pool').Pool({
name: mapfile,
create: function(callback) {
var width = options.width || 256,
height = options.height || 256,
Map = require('mapnik').Map,
map = new Map(width, height);
try {
map.load(mapfile);
map.buffer_size(128);
callback(map);
} catch(err) {
callback(map);
}
},
destroy: function(map) {
map.clear();
delete map;
},
max: 5,
idleTimeoutMillis: 5000,
log: false
});
}
this.pools[mapfile].acquire(callback);
},
release: function(mapfile, map) {
this.pools[mapfile] && this.pools[mapfile].release(map);
}
};
}
|
/**
* Small wrapper around node-pool. Establishes a pool of 5 mapnik map objects
* per mapfile.
* @TODO: Make pool size configurable.
*/
module.exports = new function() {
return {
pools: {},
acquire: function(mapfile, options, callback) {
if (!this.pools[mapfile]) {
this.pools[mapfile] = require('generic-pool').Pool({
name: mapfile,
create: function(callback) {
var width = options.width || 256,
height = options.height || 256,
Map = require('mapnik').Map,
map = new Map(width, height);
map.load(mapfile);
map.buffer_size(128);
callback(map);
},
destroy: function(map) {
map.clear();
delete map;
},
max: 5,
idleTimeoutMillis: 5000,
log: false
});
}
this.pools[mapfile].acquire(callback);
},
release: function(mapfile, map) {
this.pools[mapfile] && this.pools[mapfile].release(map);
}
};
}
|
Fix: Support older devices with session cache | "use strict";
angular.module("angular-mobile-docs")
.factory("FetchService", function ($http, $q, LocalStorageCache, baseUrl) {
var getVersionList = function () {
/*
TODO: LocalStorage for already downloaded files.
But also should fetch if net is available
*/
return $http.get(
baseUrl
+ "versions/"
+ "index.json"
, {cache: true}//{cache: LocalStorageCache}
);
}
var getFileList = function (version) {
return $http.get(
baseUrl
+ "versions/"
+ version
+ ".api.json"
, {cache: (localStorage)?LocalStorageCache:true}
);
}
var getPartial = function (version, name) {
return $http.get(
baseUrl
+ "code/"
+ version
+ "/docs/partials/api/" + name
, {cache: (localStorage)?LocalStorageCache:true});
}
var getAllPartials = function (version) {
var promises = [];
getFileList(version)
.then(function (fileNameList) {
console.log(fileNameList);
angular.forEach(fileNameList.data, function (fileName) {
promises.push(getPartial(version, fileName));
})
});
return $q.all(promises);
}
return {
getVersionList: function () {
return getVersionList();
},
getFileList : function (version) {
return getFileList(version);
},
getPartial : function (version, name) {
return getPartial(version, name);
},
getAllPartials: function (version) {
return getAllPartials(version);
}
};
}); | "use strict";
angular.module("angular-mobile-docs")
.factory("FetchService", function ($http, $q, LocalStorageCache, baseUrl) {
var getVersionList = function () {
/*
TODO: LocalStorage for already downloaded files.
But also should fetch if net is available
*/
return $http.get(
baseUrl
+ "versions/"
+ "index.json"
, {cache: true}//{cache: LocalStorageCache}
);
}
var getFileList = function (version) {
return $http.get(
baseUrl
+ "versions/"
+ version
+ ".api.json"
, {cache: LocalStorageCache}
);
}
var getPartial = function (version, name) {
return $http.get(
baseUrl
+ "code/"
+ version
+ "/docs/partials/api/" + name
, {cache: LocalStorageCache});
}
var getAllPartials = function (version) {
var promises = [];
getFileList(version)
.then(function (fileNameList) {
console.log(fileNameList);
angular.forEach(fileNameList.data, function (fileName) {
promises.push(getPartial(version, fileName));
})
});
return $q.all(promises);
}
return {
getVersionList: function () {
return getVersionList();
},
getFileList : function (version) {
return getFileList(version);
},
getPartial : function (version, name) {
return getPartial(version, name);
},
getAllPartials: function (version) {
return getAllPartials(version);
}
};
}); |
Remove old logging statements. Set up structure to build HTML | $("#search-form").submit(function (event) {
var query = $("#search-box").val();
var path = window.location.pathname;
//Split path, removing empty entries
var splitPath = path.split('/');
splitPath = splitPath.filter(function (v) { return v !== '' });
if (splitPath.length <= 1) {
searchSite(query);
}
else if (splitPath.length >= 2)
{
var username = splitPath[1];
var repository = splitPath[2];
searchRepository(username, repository, query);
}
return false;
});
function searchRepository(username, repository, query) {
data = JSON.stringify({
"username": username,
"repository": repository,
"query": query
});
$.ajax({
type: "POST",
url: "/Search/Repository/",
//TODO: If anyone knows a better way to do this, please share it.
//My Javascript is not strong...
data: "username=" + username + "&repository=" + repository + "&query="+ query,
success: handleSearch
});
}
function handleSearch(results) {
$("#tree-view").hide();
$("#search-results").show();
if (results.length == 0) {
$("#no-results").show();
}
else {
$("#no-results").hide();
var htmlResults = buildResults(results);
}
}
function buildResults(results) {
for (var i = 0; i < results.length; i++) {
var searchResult = results[i];
console.log(searchResult);
}
}
function searchSite(query) {
}
| $("#search-form").submit(function (event) {
var query = $("#search-box").val();
var path = window.location.pathname;
//Split path, removing empty entries
var splitPath = path.split('/');
splitPath = splitPath.filter(function (v) { return v !== '' });
if (splitPath.length <= 1) {
searchSite(query);
}
else if (splitPath.length >= 2)
{
var username = splitPath[1];
console.log(username);
var repository = splitPath[2];
console.log(repository);
searchRepository(username, repository, query);
}
console.log(splitPath.length);
return false;
});
function searchRepository(username, repository, query) {
console.log("search repo");
data = JSON.stringify({
"username": username,
"repository": repository,
"query": query
});
$.ajax({
type: "POST",
url: "/Search/Repository/",
//TODO: If anyone knows a better way to do this, please share it.
//My Javascript is not strong...
data: "username=" + username + "&repository=" + repository + "&query="+ query,
success: results
});
}
function results(e) {
$("#tree-view").hide();
$("#search-results").show();
if(e.length == 0)
{
$("#no-results").show();
return;
}
$("#no-results").hide();
}
function searchSite(query) {
console.log("search site");
console.log(query);
}
|
Add html to watch list since its compiled inline via browserify | var browserifyTransforms = ['brfs'];
module.exports = function(grunt) {
grunt.registerTask( 'default', [ 'clean', 'browserify', 'sass', 'autoprefixer' ] );
grunt.initConfig({
browserify: {
options: {
transform: browserifyTransforms
},
dist: {
files: {
'dist/js/app.js': ['./app/app.js']
}
}
},
sass: {
dist: {
options: {
style: 'expanded'
},
files: {
'./dist/css/style.css': './app/sass/style.scss'
}
}
},
autoprefixer: {
dist: {
files: {
'./dist/css/style.css': './dist/css/style.css'
}
}
},
watch: {
dist: {
files: [ './app/**/*.js', './app/**/*.scss', './app/**/*.html' ],
tasks: [ 'default' ]
}
},
clean: ['./dist']
});
grunt.loadNpmTasks('grunt-browserify');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-autoprefixer');
}; | var browserifyTransforms = ['brfs'];
module.exports = function(grunt) {
grunt.registerTask( 'default', [ 'clean', 'browserify', 'sass', 'autoprefixer' ] );
grunt.initConfig({
browserify: {
options: {
transform: browserifyTransforms
},
dist: {
files: {
'dist/js/app.js': ['./app/app.js']
}
}
},
sass: {
dist: {
options: {
style: 'expanded'
},
files: {
'./dist/css/style.css': './app/sass/style.scss'
}
}
},
autoprefixer: {
dist: {
files: {
'./dist/css/style.css': './dist/css/style.css'
}
}
},
watch: {
dist: {
files: [ './app/**/*.js', './app/**/*.scss' ],
tasks: [ 'default' ]
}
},
clean: ['./dist']
});
grunt.loadNpmTasks('grunt-browserify');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-autoprefixer');
}; |
Set RedirectView.permanent to True to match old default settings | from django.conf.urls import patterns, url, include
from django.conf import settings
from django.contrib import admin
from django.core.urlresolvers import reverse_lazy
from django.views.generic.base import RedirectView
import competition
admin.autodiscover()
urlpatterns = patterns(
'',
url(r'^$', RedirectView.as_view(permanent=True,url=reverse_lazy('competition_list'))),
url(r'', include(competition.urls)),
url(r'^admin/', include(admin.site.urls)),
url(r'^admin_tools/', include('admin_tools.urls')),
url (r'^accounts/login/$',
'django.contrib.auth.views.login',
{'template_name': 'accounts/login.html'},
name='account_login'),
url (r'^accounts/logout/$',
'django.contrib.auth.views.logout_then_login',
name='account_logout'),
)
if settings.DEBUG:
urlpatterns += patterns(
'django.views.static',
url(r'^qr/(?P<path>.*\.png)$', 'serve',
{'document_root': settings.QR_DIR}),
url(r'^static/(?P<path>.*)$', 'serve',
{'document_root': settings.STATIC_ROOT}),
url(r'^media/(?P<path>.*)$', 'serve',
{'document_root': settings.MEDIA_ROOT}),
)
| from django.conf.urls import patterns, url, include
from django.conf import settings
from django.contrib import admin
from django.core.urlresolvers import reverse_lazy
from django.views.generic.base import RedirectView
import competition
admin.autodiscover()
urlpatterns = patterns(
'',
url(r'^$', RedirectView.as_view(url=reverse_lazy('competition_list'))),
url(r'', include(competition.urls)),
url(r'^admin/', include(admin.site.urls)),
url(r'^admin_tools/', include('admin_tools.urls')),
url (r'^accounts/login/$',
'django.contrib.auth.views.login',
{'template_name': 'accounts/login.html'},
name='account_login'),
url (r'^accounts/logout/$',
'django.contrib.auth.views.logout_then_login',
name='account_logout'),
)
if settings.DEBUG:
urlpatterns += patterns(
'django.views.static',
url(r'^qr/(?P<path>.*\.png)$', 'serve',
{'document_root': settings.QR_DIR}),
url(r'^static/(?P<path>.*)$', 'serve',
{'document_root': settings.STATIC_ROOT}),
url(r'^media/(?P<path>.*)$', 'serve',
{'document_root': settings.MEDIA_ROOT}),
)
|
Hide the option set from incompatible browsers | from __future__ import unicode_literals
from itertools import chain
from django import forms
from django.utils.encoding import force_text
from django.utils.html import format_html
from django.utils.safestring import mark_safe
class DataListInput(forms.TextInput):
"""
A form widget that displays a standard ``TextInput`` field, as well
as an HTML5 datalist element. This provides a set of options that
the user can select from, along with the ability to enter a custom
value. Suggested options are matched as the user begins typing.
"""
def __init__(self, attrs=None, choices=()):
super(DataListInput, self).__init__(attrs)
self.choices = list(chain.from_iterable(choices))
def render(self, name, value, attrs={}, choices=()):
attrs['list'] = 'id_%s_list' % name
output = [super(DataListInput, self).render(name, value, attrs)]
options = self.render_options(name, choices)
if options:
output.append(options)
return mark_safe('\n'.join(output))
def render_options(self, name, choices):
output = []
output.append('<datalist id="id_%s_list">' % name)
output.append('<select style="display:none">')
for option in chain(self.choices, choices):
output.append(format_html('<option value="{0}" />', force_text(option)))
output.append('</select>')
output.append('</datalist>')
return '\n'.join(output)
| from __future__ import unicode_literals
from itertools import chain
from django import forms
from django.utils.encoding import force_text
from django.utils.html import format_html
from django.utils.safestring import mark_safe
class DataListInput(forms.TextInput):
"""
A form widget that displays a standard ``TextInput`` field, as well
as an HTML5 datalist element. This provides a set of options that
the user can select from, along with the ability to enter a custom
value. Suggested options are matched as the user begins typing.
"""
def __init__(self, attrs=None, choices=()):
super(DataListInput, self).__init__(attrs)
self.choices = list(chain.from_iterable(choices))
def render(self, name, value, attrs={}, choices=()):
attrs['list'] = 'id_%s_list' % name
output = [super(DataListInput, self).render(name, value, attrs)]
options = self.render_options(name, choices)
if options:
output.append(options)
return mark_safe('\n'.join(output))
def render_options(self, name, choices):
output = []
output.append('<datalist id="id_%s_list">' % name)
output.append('<select>')
for option in chain(self.choices, choices):
output.append(format_html('<option value="{0}" />', force_text(option)))
output.append('</select>')
output.append('</datalist>')
return '\n'.join(output)
|
Remove constraint on dependency version | from spack import *
class Hdf(Package):
"""HDF4 (also known as HDF) is a library and multi-object
file format for storing and managing data between machines."""
homepage = "https://www.hdfgroup.org/products/hdf4/"
url = "https://www.hdfgroup.org/ftp/HDF/releases/HDF4.2.11/src/hdf-4.2.11.tar.gz"
list_url = "https://www.hdfgroup.org/ftp/HDF/releases/"
list_depth = 3
version('4.2.11', '063f9928f3a19cc21367b71c3b8bbf19')
depends_on("jpeg")
depends_on("szip")
depends_on("zlib")
def url_for_version(self, version):
return "https://www.hdfgroup.org/ftp/HDF/releases/HDF" + str(version) + "/src/hdf-" + str(version) + ".tar.gz"
def install(self, spec, prefix):
configure('--prefix=%s' % prefix,
'--with-jpeg=%s' % spec['jpeg'].prefix,
'--with-szlib=%s' % spec['szip'].prefix,
'--with-zlib=%s' % spec['zlib'].prefix,
'--disable-netcdf',
'--enable-fortran',
'--disable-shared',
'--enable-static',
'--enable-production')
make()
make("install")
| from spack import *
class Hdf(Package):
"""HDF4 (also known as HDF) is a library and multi-object
file format for storing and managing data between machines."""
homepage = "https://www.hdfgroup.org/products/hdf4/"
url = "https://www.hdfgroup.org/ftp/HDF/releases/HDF4.2.11/src/hdf-4.2.11.tar.gz"
list_url = "https://www.hdfgroup.org/ftp/HDF/releases/"
list_depth = 3
version('4.2.11', '063f9928f3a19cc21367b71c3b8bbf19')
depends_on("jpeg")
depends_on("[email protected]")
depends_on("zlib")
def url_for_version(self, version):
return "https://www.hdfgroup.org/ftp/HDF/releases/HDF" + str(version) + "/src/hdf-" + str(version) + ".tar.gz"
def install(self, spec, prefix):
configure('--prefix=%s' % prefix,
'--with-jpeg=%s' % spec['jpeg'].prefix,
'--with-szlib=%s' % spec['szip'].prefix,
'--with-zlib=%s' % spec['zlib'].prefix,
'--disable-netcdf',
'--enable-fortran',
'--disable-shared',
'--enable-static',
'--enable-production')
make()
make("install")
|
Fix version string so that we can install with pip/setuptools | """Schemas for structured data."""
from flatland.exc import AdaptationError
from flatland.schema import Array, Boolean, Compound, Constrained, Container,\
Date, DateTime, DateYYYYMMDD, Decimal, Dict, Element, Enum, Float, Form,\
Integer, JoinedString, List, Long, Mapping, MultiValue, Number,\
Properties, Ref, Scalar, Sequence, Skip, SkipAll, SkipAllFalse,\
SparseDict, String, Time, Unevaluated, Unset
'''
from flatland.util.deferred import deferred_module
deferred_module.shadow(
'flatland',
{'exc': ('AdaptationError',),
'schema': ('Array',
'Boolean',
'Compound',
'Constrained',
'Container',
'Date',
'DateTime',
'DateYYYYMMDD',
'Decimal',
'Dict',
'Element',
'Enum',
'Float',
'Form',
'Integer',
'JoinedString',
'List',
'Long',
'Mapping',
'MultiValue',
'Number',
'Properties',
'Ref',
'Scalar',
'Sequence',
'Skip',
'SkipAll',
'SkipAllFalse',
'SparseDict',
'String',
'Time',
'Unevaluated',
'Unset',
),
'signals': (),
'util': ('Unspecified', 'class_cloner',),
'validation': (),
},
__version__='dev')
'''
__version__='fix-imports'
| """Schemas for structured data."""
from flatland.exc import AdaptationError
from flatland.schema import Array, Boolean, Compound, Constrained, Container,\
Date, DateTime, DateYYYYMMDD, Decimal, Dict, Element, Enum, Float, Form,\
Integer, JoinedString, List, Long, Mapping, MultiValue, Number,\
Properties, Ref, Scalar, Sequence, Skip, SkipAll, SkipAllFalse,\
SparseDict, String, Time, Unevaluated, Unset
'''
from flatland.util.deferred import deferred_module
deferred_module.shadow(
'flatland',
{'exc': ('AdaptationError',),
'schema': ('Array',
'Boolean',
'Compound',
'Constrained',
'Container',
'Date',
'DateTime',
'DateYYYYMMDD',
'Decimal',
'Dict',
'Element',
'Enum',
'Float',
'Form',
'Integer',
'JoinedString',
'List',
'Long',
'Mapping',
'MultiValue',
'Number',
'Properties',
'Ref',
'Scalar',
'Sequence',
'Skip',
'SkipAll',
'SkipAllFalse',
'SparseDict',
'String',
'Time',
'Unevaluated',
'Unset',
),
'signals': (),
'util': ('Unspecified', 'class_cloner',),
'validation': (),
},
__version__='dev')
'''
|
Send message, even if it was a delete | /**
* Copyright 2014 Nicholas Humfrey
* Copyright 2013 IBM Corp.
*
* 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.
**/
module.exports = function(RED) {
"use strict";
function CollectorNode(n) {
RED.nodes.createNode(this,n);
this.name = n.name;
this.state = {};
var node = this;
node.on("input", function(msg) {
try {
if (msg.topic) {
if (msg.payload == undefined || msg.payload == null || msg.payload == '') {
delete node.state[msg.topic];
} else {
node.state[msg.topic] = msg.payload;
}
node.send(node.state);
} else {
node.warn("No topic set on message to collector");
}
} catch(err) {
node.error(err.message);
}
});
}
RED.nodes.registerType("collector",CollectorNode);
}
| /**
* Copyright 2014 Nicholas Humfrey
* Copyright 2013 IBM Corp.
*
* 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.
**/
module.exports = function(RED) {
"use strict";
function CollectorNode(n) {
RED.nodes.createNode(this,n);
this.name = n.name;
this.state = {};
var node = this;
node.on("input", function(msg) {
try {
if (msg.topic) {
if (msg.payload == undefined || msg.payload == null || msg.payload == '') {
delete node.state[msg.topic];
} else {
node.state[msg.topic] = msg.payload;
node.send(node.state);
}
} else {
node.warn("No topic set on message to collector");
}
} catch(err) {
node.error(err.message);
}
});
}
RED.nodes.registerType("collector",CollectorNode);
}
|
Allow Program Readers to view comments | # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: [email protected]
# Maintained By: [email protected]
scope = "AuditImplied"
description = """
A user with the ProgramReader role for a private program will also have this
role in the audit context for any audit created for that program.
"""
permissions = {
"read": [
"Request",
"Comment",
"ControlAssessment",
"Issue",
"DocumentationResponse",
"InterviewResponse",
"PopulationSampleResponse",
"Audit",
"AuditObject",
"Meeting",
"ObjectDocument",
"ObjectPerson",
"Relationship",
"Document",
"Meeting",
"UserRole",
"Context",
],
"create": [
"DocumentationResponse",
"InterviewResponse",
"Response",
"ObjectDocument",
"ObjectPerson",
"Relationship",
"Document"
],
"view_object_page": [
"__GGRC_ALL__"
],
"update": [],
"delete": [
"ObjectDocument",
"ObjectPerson",
"Relationship"
]
}
| # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: [email protected]
# Maintained By: [email protected]
scope = "AuditImplied"
description = """
A user with the ProgramReader role for a private program will also have this
role in the audit context for any audit created for that program.
"""
permissions = {
"read": [
"Request",
"ControlAssessment",
"Issue",
"DocumentationResponse",
"InterviewResponse",
"PopulationSampleResponse",
"Audit",
"AuditObject",
"Meeting",
"ObjectDocument",
"ObjectPerson",
"Relationship",
"Document",
"Meeting",
"UserRole",
"Context",
],
"create": [
"DocumentationResponse",
"InterviewResponse",
"Response",
"ObjectDocument",
"ObjectPerson",
"Relationship",
"Document"
],
"view_object_page": [
"__GGRC_ALL__"
],
"update": [],
"delete": [
"ObjectDocument",
"ObjectPerson",
"Relationship"
]
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.