text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Fix account sidenav hash click | $(document).ready(function() {
var sideNav = $('#sidenav');
var sideNavActiveScope = sideNav.attr('data-active-scope');
if ($('.active', sideNavActiveScope).length === 0) {
$('li:first', sideNavActiveScope).addClass('active');
}
$('.sidenav a').click(function () {
var href = $(this).attr('href');
if (href.substr(0, 1) === '#') {
var target = $(href);
if (target.length) {
$.scrollTo(target, {
'offset':-80
});
window.location.hash = target.attr('id');
return false;
}
}
});
if ($(window.location.hash).length) {
var target = $(window.location.hash);
if (target.length) {
$.scrollTo(target, {
'offset':-80
});
}
}
}); | $(document).ready(function() {
var sideNav = $('#sidenav');
var sideNavActiveScope = sideNav.attr('data-active-scope');
if ($('.active', sideNavActiveScope).length === 0) {
$('li:first', sideNavActiveScope).addClass('active');
}
$('.sidenav a').click(function () {
var target = $($(this).attr('href'));
$.scrollTo(target, {
'offset':-80
});
window.location.hash = target.attr('id');
return false;
});
if ($(window.location.hash).length) {
var target = $(window.location.hash);
$.scrollTo(target, {
'offset':-80
});
}
}); |
Raise `ConfigurationError` instead of `Exception` if environment variable `BYCEPS_CONFIG` is not set | """
byceps.util.system
~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import os
import sys
from ..config import ConfigurationError
CONFIG_VAR_NAME = 'BYCEPS_CONFIG'
def get_config_filename_from_env() -> str:
"""Return the configuration filename set via environment variable.
Raise an exception if it isn't set.
"""
env = os.environ.get(CONFIG_VAR_NAME)
if not env:
raise ConfigurationError(
"No configuration file was specified via the '{}' "
"environment variable.".format(CONFIG_VAR_NAME))
return env
def get_config_filename_from_env_or_exit() -> str:
"""Return the configuration filename set via environment variable.
Exit if it isn't set.
"""
try:
return get_config_filename_from_env()
except ConfigurationError as e:
sys.stderr.write("{}\n".format(e))
sys.exit(1)
| """
byceps.util.system
~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import os
import sys
CONFIG_VAR_NAME = 'BYCEPS_CONFIG'
def get_config_filename_from_env() -> str:
"""Return the configuration filename set via environment variable.
Raise an exception if it isn't set.
"""
env = os.environ.get(CONFIG_VAR_NAME)
if not env:
raise Exception(
"No configuration file was specified via the '{}' "
"environment variable.".format(CONFIG_VAR_NAME))
return env
def get_config_filename_from_env_or_exit() -> str:
"""Return the configuration filename set via environment variable.
Exit if it isn't set.
"""
try:
return get_config_filename_from_env()
except Exception as e:
sys.stderr.write("{}\n".format(e))
sys.exit(1)
|
Change less main-source name to something more recognizable | /*!
* customize-engine-less <https://github.com/nknapp/customize-engine-less>
*
* Copyright (c) 2015 Nils Knappmeier.
* Released under the MIT license.
*/
'use strict'
var _ = require('lodash')
var less = require('less')
var Q = require('q')
module.exports = {
defaultConfig: {
main: [],
paths: []
},
preprocessConfig: function (config) {
return {
main: coerceToArray(config.main),
paths: coerceToArray(config.paths)
}
},
run: function (config) {
var lessSource = config.main.map(function (file) {
return '@import "' + file + '";'
}).join('\n')
return less.render(lessSource, {
paths: config.paths,
sourceMap: {},
filename: 'customize-bundle.less',
compress: true
})
}
}
/**
* If `objOrArray` exists and is a non-array, it is replaced by
* an array with the property as single object.
* @param {object} objOrArray the object or an array
* @return objOrArray, if it is an array or an array containing `objOrArray` (if it is no array)
*/
function coerceToArray (objOrArray) {
if (!_.isUndefined(objOrArray) && !_.isArray(objOrArray)) {
return [ objOrArray ];
}
return objOrArray;
}
| /*!
* customize-engine-less <https://github.com/nknapp/customize-engine-less>
*
* Copyright (c) 2015 Nils Knappmeier.
* Released under the MIT license.
*/
'use strict'
var _ = require('lodash')
var less = require('less')
var Q = require('q')
module.exports = {
defaultConfig: {
main: [],
paths: []
},
preprocessConfig: function (config) {
return {
main: coerceToArray(config.main),
paths: coerceToArray(config.paths)
}
},
run: function (config) {
var lessSource = config.main.map(function (file) {
return '@import "' + file + '";'
}).join('\n')
return less.render(lessSource, {
paths: config.paths,
sourceMap: {},
filename: 'main.less',
compress: true
})
}
}
/**
* If `objOrArray` exists and is a non-array, it is replaced by
* an array with the property as single object.
* @param {object} objOrArray the object or an array
* @return objOrArray, if it is an array or an array containing `objOrArray` (if it is no array)
*/
function coerceToArray (objOrArray) {
if (!_.isUndefined(objOrArray) && !_.isArray(objOrArray)) {
return [ objOrArray ];
}
return objOrArray;
}
|
Add docstring into load function
Describe which file parse at least. | # Copyright 2015-2016 Masayuki Yamamoto
#
# 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.
"""Handle yanico configuration."""
import configparser
import os.path
CONFIG_FILENAME = '.yanico.conf'
def user_path():
"""Return user configuration filepath.
The filepath depends home directory and CONFIG_FILENAME constants.
"""
return os.path.join(os.path.expanduser('~'), CONFIG_FILENAME)
def load(*filepaths):
"""Return configration object.
Object parses home directory config file.
Args:
filepaths (Tuple[str]): configuration file paths
Returns:
ConfigParser: object expects some configurations are loaded.
"""
parser = configparser.ConfigParser()
parser.read((user_path(),) + filepaths)
return parser
| # Copyright 2015-2016 Masayuki Yamamoto
#
# 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.
"""Handle yanico configuration."""
import configparser
import os.path
CONFIG_FILENAME = '.yanico.conf'
def user_path():
"""Return user configuration filepath.
The filepath depends home directory and CONFIG_FILENAME constants.
"""
return os.path.join(os.path.expanduser('~'), CONFIG_FILENAME)
def load(*filepaths):
parser = configparser.ConfigParser()
parser.read((user_path(),) + filepaths)
return parser
|
KULRICE-9047: Disable term lookup smoke test to avoid any server impact till fixed.
git-svn-id: 2a5d2b5a02908a0c4ba7967b726d8c4198d1b9ed@37464 7a7aa7f6-c479-11dc-97e2-85a2497f191d | /**
* Copyright 2005-2011 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
*
* 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 edu.samplu.mainmenu.test;
import org.junit.Test;
import edu.samplu.common.MainMenuLookupLegacyITBase;
/**
* tests that user 'admin' can display the Term lookup screen, search,
* initiate an Term maintenance document via an edit action on the search results and
* finally cancel the maintenance document
*
* @author Kuali Rice Team (rice.collab@kuali.org)
*/
public class TermLookUpLegacyIT extends MainMenuLookupLegacyITBase {
@Override
public void testLookUp() {} // no-op to avoid https://jira.kuali.org/browse/KULRICE-9047 messing up the server state
@Override
public String getLinkLocator() {
return "Term Lookup";
}
@Test
public void lookupAssertions() throws Exception{
gotoMenuLinkLocator();
super.testTermLookUp();
}
} | /**
* Copyright 2005-2011 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
*
* 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 edu.samplu.mainmenu.test;
import org.junit.Test;
import edu.samplu.common.MainMenuLookupLegacyITBase;
/**
* tests that user 'admin' can display the Term lookup screen, search,
* initiate an Term maintenance document via an edit action on the search results and
* finally cancel the maintenance document
*
* @author Kuali Rice Team (rice.collab@kuali.org)
*/
public class TermLookUpLegacyIT extends MainMenuLookupLegacyITBase {
@Override
public String getLinkLocator() {
return "Term Lookup";
}
@Test
public void lookupAssertions() throws Exception{
gotoMenuLinkLocator();
super.testTermLookUp();
}
} |
Add sample config to the package data | from setuptools import setup, find_packages
with open('README.rst') as f:
long_description = f.read()
setup(
name='jiradoc',
version='0.1',
description='A small Python module to parse JIRAdoc markup files and insert them into JIRA',
long_description=long_description,
url='https://github.com/lucianovdveekens/jiradoc',
author='Luciano van der Veekens',
author_email='lucianovdveekens@gmail.com',
packages=find_packages(),
install_requires=['ply', 'jira', 'pyyaml', 'appdirs'],
package_data={
'jiradoc': ['data/test.jiradoc', 'data/sample_config.yml']
},
entry_points={
'console_scripts': [
'jiradoc=jiradoc.__main__:main',
],
},
)
| from setuptools import setup, find_packages
with open('README.rst') as f:
long_description = f.read()
setup(
name='jiradoc',
version='0.1',
description='A small Python module to parse JIRAdoc markup files and insert them into JIRA',
long_description=long_description,
url='https://github.com/lucianovdveekens/jiradoc',
author='Luciano van der Veekens',
author_email='lucianovdveekens@gmail.com',
packages=find_packages(),
install_requires=['ply', 'jira', 'pyyaml', 'appdirs'],
package_data={
'jiradoc': ['data/test.jiradoc']
},
entry_points={
'console_scripts': [
'jiradoc=jiradoc.__main__:main',
],
},
)
|
Add onEnter redirect for 'signin' and 'signup' if current user | angular
.module('fitnessTracker', ['ui.router', 'templates', 'Devise'])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('signup', {
url: '/signup',
templateUrl: 'auth/_signup.html',
controller: 'AuthenticationController as AuthCtrl',
onEnter: function($state, Auth) {
Auth.currentUser().then(function (){
$state.go('home');
})
}
})
.state('signin', {
url: '/signin',
templateUrl: 'auth/_signin.html',
controller: 'AuthenticationController as AuthCtrl',
onEnter: function($state, Auth) {
Auth.currentUser().then(function (){
$state.go('home');
})
}
})
.state('user', {
url: '/user',
templateUrl: 'user/_user.html',
controller: 'UserController as UserCtrl'
});
$urlRouterProvider.otherwise('/signin');
});
| angular
.module('fitnessTracker', ['ui.router', 'templates', 'Devise'])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('signup', {
url: '/signup',
templateUrl: 'auth/_signup.html',
controller: 'AuthenticationController as AuthCtrl'
})
.state('signin', {
url: '/signin',
templateUrl: 'auth/_signin.html',
controller: 'AuthenticationController as AuthCtrl'
})
.state('user', {
url: '/user',
templateUrl: 'user/_user.html',
controller: 'UserController as UserCtrl'
});
$urlRouterProvider.otherwise('/signin');
});
|
Add null check as per request from Joel | /*
*
* Copyright (c) 2004 by VASSAL team
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License (LGPL) as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, copies are available
* at http://www.opensource.org.
*/
package VASSAL.configure;
import java.util.Objects;
import VASSAL.build.AbstractConfigurable;
import VASSAL.build.Buildable;
import VASSAL.i18n.Resources;
/**
* Requires that the object does not have null configurable name
*/
public class NotNullConfigureName implements ValidityChecker {
private final AbstractConfigurable target;
public NotNullConfigureName(AbstractConfigurable target) {
this.target = Objects.requireNonNull(target);
}
@Override
public void validate(Buildable b, ValidationReport report) {
if (b == target && ((target.getConfigureName() == null) || (target.getConfigureName().equals("")))) {
report.addWarning(Resources.getString("Editor.ValidationReportDialog.blank_name") + " " + target.getClass().getName());
}
}
}
| /*
*
* Copyright (c) 2004 by VASSAL team
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License (LGPL) as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, copies are available
* at http://www.opensource.org.
*/
package VASSAL.configure;
import java.util.Objects;
import VASSAL.build.AbstractConfigurable;
import VASSAL.build.Buildable;
import VASSAL.i18n.Resources;
/**
* Requires that the object does not have null configurable name
*/
public class NotNullConfigureName implements ValidityChecker {
private final AbstractConfigurable target;
public NotNullConfigureName(AbstractConfigurable target) {
this.target = Objects.requireNonNull(target);
}
@Override
public void validate(Buildable b, ValidationReport report) {
if (b == target && target.getConfigureName().equals("")) {
report.addWarning(Resources.getString("Editor.ValidationReportDialog.blank_name") + " " + target.getClass().getName());
}
}
}
|
Add socket event : `key`
Send the pressed key to the TV | var express = require('express');
var http = require('http');
var socket = require('socket.io');
var SamsungRemote = require('samsung-remote');
var app = express();
var port = process.env.PORT || 8080;
app.disable('etag');
var server = http.createServer(app).listen(port, function() {
console.log('Express server listening on port ' + port);
});
var io = socket.listen(server);
io.sockets.on('connection', function(socket){
console.log('New client connected');
socket.emit('welcome', 'hello! You are now connected');
var remote = new SamsungRemote({
ip: '192.168.1.1'
});
socket.on('ip', function(ip){
remote.config.ip = ip;
console.log('New IP defined : ' + ip);
socket.emit('ip', 'New IP defined : ' + ip);
});
socket.on('name', function(name){
remote.config.host.name = name;
socket.emit('name', 'New Name defined : ' + name)
console.log('New Name defined : ' + name);
});
socket.on('key', function(key){
remote.send(key, function callback(err){
if (err) {
console.log('Erreur ' + key + ' : ' + err);
socket.emit('key', 'Erreur ' + key + ' : ' + err);
} else {
console.log('Key : ' + key);
socket.emit('key', 'Key : ' + key);
}
});
});
});
| var express = require('express');
var http = require('http');
var socket = require('socket.io');
var SamsungRemote = require('samsung-remote');
var app = express();
var port = process.env.PORT || 8080;
app.disable('etag');
var server = http.createServer(app).listen(port, function() {
console.log('Express server listening on port ' + port);
});
var io = socket.listen(server);
io.sockets.on('connection', function(socket){
console.log('New client connected');
socket.emit('welcome', 'hello! You are now connected');
var remote = new SamsungRemote({
ip: '192.168.1.1'
});
socket.on('ip', function(ip){
remote.config.ip = ip;
console.log('New IP defined : ' + ip);
socket.emit('ip', 'New IP defined : ' + ip);
});
socket.on('name', function(name){
remote.config.host.name = name;
socket.emit('name', 'New Name defined : ' + name)
console.log('New Name defined : ' + name);
});
});
|
Remove the reload constants button | jQuery.fn.rotate = function(degrees) {
$(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
'-moz-transform' : 'rotate('+ degrees +'deg)',
'-ms-transform' : 'rotate('+ degrees +'deg)',
'transform' : 'rotate('+ degrees +'deg)'});
};
jQuery.fn.resetRotate = function(degrees) {
$(this).css({'-webkit-transform' : 'rotate(0deg)',
'-moz-transform' : 'rotate(0deg)',
'-ms-transform' : 'rotate(0deg)',
'transform' : 'rotate(0deg)'});
};
$(function() {
Constants.get("game_size", function(value) {
var game = new Game(value);
game.setupCanvas();
game.setupGame();
});
});
| jQuery.fn.rotate = function(degrees) {
$(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
'-moz-transform' : 'rotate('+ degrees +'deg)',
'-ms-transform' : 'rotate('+ degrees +'deg)',
'transform' : 'rotate('+ degrees +'deg)'});
};
jQuery.fn.resetRotate = function(degrees) {
$(this).css({'-webkit-transform' : 'rotate(0deg)',
'-moz-transform' : 'rotate(0deg)',
'-ms-transform' : 'rotate(0deg)',
'transform' : 'rotate(0deg)'});
};
$(function() {
Constants.get("game_size", function(value) {
var game = new Game(value);
game.setupCanvas();
game.setupGame();
Input.press("reloadConstants", Constants.reload);
});
});
|
Use $window service instead of global window object (best practice) | 'use strict';
/**
* Desktop notifications
* see http://caniuse.com/#search=notifications
*
* If the browser does not support notifications, the message will
* be logged to the browser console
*/
app.factory('AvvisoService', ['$window',
function($window) {
var hasNotifications = $window.Notification != undefined;
if (hasNotifications) {
Notification.requestPermission();
}
var Service = {
notify: function(title, body) {
if (hasNotifications) {
var notif = new Notification(title, {
body: body,
// icon: // TODO: add purkinje icon (only displayed in Firefox; not Chrome)
});
} else {
console.debug(title + ': ' + body);
}
}
};
return Service;
}
]);
| 'use strict';
/**
* Desktop notifications
* see http://caniuse.com/#search=notifications
*
* If the browser does not support notifications, the message will
* be logged to the browser console
*/
app.factory('AvvisoService', [
function() {
var hasNotifications = window.Notification != undefined;
if (hasNotifications) {
Notification.requestPermission();
}
var Service = {
notify: function(title, body) {
if (hasNotifications) {
var notif = new Notification(title, {
body: body,
// icon: // TODO: add purkinje icon (only displayed in Firefox; not Chrome)
});
} else {
console.debug(title + ': ' + body);
}
}
};
return Service;
}
]);
|
Make click2dial work in real life | # -*- coding: utf-8 -*-
##############################################################################
#
# Base Phone module for Odoo
# Copyright (C) 2014-2015 Alexis de Lattre (alexis@via.ecp.fr)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from odoo import http
class BasePhoneController(http.Controller):
@http.route('/base_phone/click2dial', type='json', auth='user')
def click2dial(self, phone_number, click2dial_model, click2dial_id):
res = http.request.env['phone.common'].with_context(
click2dial_model=click2dial_model,
click2dial_id=click2dial_id).click2dial(phone_number)
return res
| # -*- coding: utf-8 -*-
##############################################################################
#
# Base Phone module for Odoo
# Copyright (C) 2014-2015 Alexis de Lattre (alexis@via.ecp.fr)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from odoo import http
class BasePhoneController(http.Controller):
@http.route('/base_phone/click2dial', type='json', auth='none')
def click2dial(self, phone_number, click2dial_model, click2dial_id):
res = http.request.env['phone.common'].click2dial(
phone_number, {
'click2dial_model': click2dial_model,
'click2dial_id': click2dial_id,
})
return res
|
Fix for Partner's email not being accessible to administrator | # -*- coding: utf-8 -*-
from openerp import models, fields, api
class User(models.Model):
_inherit = 'res.users'
def __init__(self, pool, cr):
super(User, self).__init__(pool, cr)
self._add_permitted_fields(level='privileged', fields={'email'})
self._add_permitted_fields(level='owner', fields={'email'})
@api.one
def _compute_user_access_level(self):
"""
Access level that the current (logged in) user has for the object.
Either "owner", "admin", "privileged" or None.
"""
super(User, self)._compute_user_access_level()
if not self.user_access_level and self.user_has_groups('bestja_api_user.api_access'):
self.user_access_level = 'privileged'
class Partner(models.Model):
_inherit = 'res.partner'
email = fields.Char(groups='base.group_system,bestja_api_user.api_access') # give access to the email field
| # -*- coding: utf-8 -*-
from openerp import models, fields, api
class User(models.Model):
_inherit = 'res.users'
def __init__(self, pool, cr):
super(User, self).__init__(pool, cr)
self._add_permitted_fields(level='privileged', fields={'email'})
self._add_permitted_fields(level='owner', fields={'email'})
@api.one
def _compute_user_access_level(self):
"""
Access level that the current (logged in) user has for the object.
Either "owner", "admin", "privileged" or None.
"""
super(User, self)._compute_user_access_level()
if not self.user_access_level and self.user_has_groups('bestja_api_user.api_access'):
self.user_access_level = 'privileged'
class Partner(models.Model):
_inherit = 'res.partner'
email = fields.Char(groups='bestja_api_user.api_access') # give access to the email field
|
Add test to check that Action Item column is not displayed on render | import React from "react"
import { shallow } from "enzyme"
import { expect } from "chai"
import sinon from "sinon"
import Room from "../../web/static/js/components/room"
import CategoryColumn from "../../web/static/js/components/category_column"
describe("Room component", () => {
const mockRetroChannel = { push: sinon.spy(), on: () => {} }
describe(".handleIdeaSubmission", () => {
it("pushes the idea to the room channel", () => {
const roomComponent = shallow(<Room retroChannel={mockRetroChannel} users={[]} />)
roomComponent
.instance()
.handleIdeaSubmission({ category: "sad", body: "we don't use our linter" })
expect(
mockRetroChannel.push.calledWith("new_idea", { category: "sad", body: "we don't use our linter" }),
).to.equal(true)
})
})
describe("Action item column", () => {
it("is not visible on render", () => {
const roomComponent = shallow(<Room retroChannel={mockRetroChannel} users={[]} />)
expect(roomComponent.containsMatchingElement(
<CategoryColumn category="action-item" ideas={[]}/>
)).to.equal(false)
})
})
})
| import React from "react"
import { shallow } from "enzyme"
import { expect } from "chai"
import sinon from "sinon"
import Room from "../../web/static/js/components/room"
describe("Room component", () => {
const mockRetroChannel = { push: sinon.spy(), on: () => {} }
describe(".handleIdeaSubmission", () => {
it("pushes the idea to the room channel", () => {
const roomComponent = shallow(<Room retroChannel={mockRetroChannel} users={[]} />)
roomComponent
.instance()
.handleIdeaSubmission({ category: "sad", body: "we don't use our linter" })
expect(
mockRetroChannel.push.calledWith("new_idea", { category: "sad", body: "we don't use our linter" }),
).to.equal(true)
})
})
})
|
Remove routeChangeSuccess function, automatically call getUserInfo on load | angular.module('bolt.profile', ['bolt.auth'])
.controller('ProfileController', function ($scope, $rootScope, Auth, Profile) {
$rootScope.user = {};
$scope.newInfo = {};
var getUserInfo = function () {
Profile.getUser()
.then(function (user) {
$rootScope.user = user.data;
});
};
$scope.signout = function () {
Auth.signout();
};
$scope.update = function () {
var newProperties = {};
for (var property in $scope.newInfo) {
newProperties[property] = $scope.newInfo[property];
$scope.newInfo[property] = '';
}
Profile.updateUser(newProperties, $rootScope.user.username)
.then( function(user) {
$rootScope.user = user.data;
//get the current user on rootScope
getUserInfo();
});
};
getUserInfo();
});
| angular.module('bolt.profile', ['bolt.auth'])
.controller('ProfileController', function ($scope, $rootScope, Auth, Profile) {
$rootScope.user = {};
$scope.newInfo = {};
var getUserInfo = function () {
Profile.getUser()
.then(function (user) {
$rootScope.user = user;
});
};
$scope.signout = function () {
Auth.signout();
};
$scope.update = function () {
var newProperties = {};
for (var property in $scope.newInfo) {
newProperties[property] = $scope.newInfo[property];
$scope.newInfo[property] = '';
}
Profile.updateUser(newProperties, $rootScope.user.username)
.then( function(user) {
$rootScope.user = user.data;
//get the current user on rootScope
getUserInfo();
});
};
$scope.$on('$routeChangeSuccess', function () {
getUserInfo();
console.log('loading!');
// do something
});
});
|
Edit error message for better debugging | <?php
require "twilio-php-master/Services/Twilio.php";
require_once "config.php";
$mysqli = new mysqli($HOST, $USER, $PASSWORD, $DATABASE);
$client = new Services_Twilio($ACCOUNT_SID, $AUTH_TOKEN);
$target = "ryan"; // temp set static target
if($_REQUEST['To'] == $US_NUMBER) {
$outboundNumber = $FRENCH_NUMBER;
$targetPhone = "french_phone";
} else if($_REQUEST['To'] == $FRENCH_NUMBER) {
$outboundNumber = $US_NUMBER;
$targetPhone = "us_phone";
} else {
error_log("MSG received on unknown phone number. Number: ".$_REQUEST['To']. " Expected: ".$FRENCH_NUMBER );
$mysqli->close();
exit(1); //Kill the program if source can't be reliably confirmed
}
if($result = $mysqli->query("SELECT ".$targetPhone." FROM users WHERE handle=".$target)) {
$obj = $result->fetch_object();
$targetPhoneNumber = $obj[$targetPhone];
} else {
echo $mysqli->error;
error_log($mysqli->error);
}
$mysqli->close();
try {
$message = $client->account->messages->create(array(
"From" => $outboundNumber,
"To" => "+16785173393",
"Body" => $_REQUEST['Body'],
));
} catch (Services_Twilio_RestException $e) {
echo $e->getMessage();
error_log($e->getMessage());
} | <?php
require "twilio-php-master/Services/Twilio.php";
require_once "config.php";
$mysqli = new mysqli($HOST, $USER, $PASSWORD, $DATABASE);
$client = new Services_Twilio($ACCOUNT_SID, $AUTH_TOKEN);
$target = "ryan"; // temp set static target
if($_REQUEST['To'] == $US_NUMBER) {
$outboundNumber = $FRENCH_NUMBER;
$targetPhone = "french_phone";
} else if($_REQUEST['To'] == $FRENCH_NUMBER) {
$outboundNumber = $US_NUMBER;
$targetPhone = "us_phone";
} else {
error_log("MSG received on unknown phone number. Number: ".$_REQUEST['To']);
exit(1); //Kill the program if source can't be reliably confirmed
}
if($result = $mysqli->query("SELECT ".$targetPhone." FROM users WHERE handle=".$target)) {
$obj = $result->fetch_object();
$targetPhoneNumber = $obj[$targetPhone];
} else {
echo $mysqli->error;
error_log($mysqli->error);
}
try {
$message = $client->account->messages->create(array(
"From" => $outboundNumber,
"To" => "+16785173393",
"Body" => $_REQUEST['Body'],
));
} catch (Services_Twilio_RestException $e) {
echo $e->getMessage();
error_log($e->getMessage());
} |
Test to see if caddy works now | package com.frederikam.fred.moe;
import com.frederikam.fred.moe.util.SLF4JInputStreamLogger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
public class Caddy extends Thread {
private static final Logger log = LoggerFactory.getLogger(Caddy.class);
public Caddy() {
setName("Caddy");
}
@Override
public void run() {
try {
log.info("Starting Caddy");
ProcessBuilder pb = new ProcessBuilder()
.command("caddy", "-conf Caddyfile", "-agree", "-email $CADDY_EMAIL");
Process proc = pb.start();doc
new SLF4JInputStreamLogger(log, proc.getInputStream()).start();
try {
int code = proc.waitFor();
log.warn("Exited with code " + code);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
} catch (IOException e) {
log.warn(e.getMessage());
}
}
}
| package com.frederikam.fred.moe;
import com.frederikam.fred.moe.util.SLF4JInputStreamLogger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
public class Caddy extends Thread {
private static final Logger log = LoggerFactory.getLogger(Caddy.class);
public Caddy() {
setName("Caddy");
}
@Override
public void run() {
try {
log.info("Starting Caddy");
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("caddy -conf Caddyfile -agree -email $CADDY_EMAIL");
new SLF4JInputStreamLogger(log, proc.getInputStream()).start();
try {
int code = proc.waitFor();
log.warn("Exited with code " + code);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
} catch (IOException e) {
log.warn(e.getMessage());
}
}
}
|
Revert commit that accidentally checked in master | module.exports = [
'https://broad-shibboleth-prod.appspot.com',
'https://all-of-us-workbench-test.appspot.com',
'https://all-of-us-rw-staging.appspot.com',
'https://all-of-us-rw-stable.appspot.com',
'https://all-of-us-rw-perf.appspot.com',
'https://all-of-us-rw-preprod.appspot.com',
'https://workbench.researchallofus.org',
'https://app.terra.bio',
'https://firecloud.terra.bio',
'https://datastage.terra.bio',
'https://anvil.terra.bio',
'https://ukbiobank.terra.bio',
'https://baseline.terra.bio',
'https://terra.biodatacatalyst.nhlbi.nih.gov',
'https://duos.broadinstitute.org',
'https://duos.dsp-duos-staging.broadinstitute.org',
'https://duos.dsp-duos-dev.broadinstitute.org'
]
| module.exports = [
'https://broad-shibboleth-prod.appspot.com',
'https://all-of-us-workbench-test.appspot.com',
'https://all-of-us-rw-staging.appspot.com',
'https://all-of-us-rw-stable.appspot.com',
'https://all-of-us-rw-perf.appspot.com',
'https://preprod-workbench.researchallofus.org',
'https://workbench.researchallofus.org',
'https://app.terra.bio',
'https://firecloud.terra.bio',
'https://datastage.terra.bio',
'https://anvil.terra.bio',
'https://ukbiobank.terra.bio',
'https://baseline.terra.bio',
'https://terra.biodatacatalyst.nhlbi.nih.gov',
'https://duos.broadinstitute.org',
'https://duos.dsp-duos-staging.broadinstitute.org',
'https://duos.dsp-duos-dev.broadinstitute.org'
]
|
Remove solvent(water) from minimal example.
Minimal should be just that - minimal.
This hides issue #165 | # Data sources
database(
thermoLibraries = ['primaryThermoLibrary'],
reactionLibraries = [],
seedMechanisms = [],
kineticsDepositories = ['training'],
kineticsFamilies = ['!Intra_Disproportionation','!Substitution_O'],
kineticsEstimator = 'rate rules',
)
# List of species
species(
label='ethane',
reactive=True,
structure=SMILES("CC"),
)
# Reaction systems
simpleReactor(
temperature=(1350,'K'),
pressure=(1.0,'bar'),
initialMoleFractions={
"ethane": 1.0,
},
terminationConversion={
'ethane': 0.9,
},
terminationTime=(1e6,'s'),
)
simulator(
atol=1e-16,
rtol=1e-8,
)
model(
toleranceKeepInEdge=0.0,
toleranceMoveToCore=0.1,
toleranceInterruptSimulation=0.1,
maximumEdgeSpecies=100000
)
options(
units='si',
saveRestartPeriod=None,
drawMolecules=False,
generatePlots=False,
)
| # Data sources
database(
thermoLibraries = ['primaryThermoLibrary'],
reactionLibraries = [],
seedMechanisms = [],
kineticsDepositories = ['training'],
kineticsFamilies = ['!Intra_Disproportionation','!Substitution_O'],
kineticsEstimator = 'rate rules',
)
# List of species
species(
label='ethane',
reactive=True,
structure=SMILES("CC"),
)
# Reaction systems
simpleReactor(
temperature=(1350,'K'),
pressure=(1.0,'bar'),
initialMoleFractions={
"ethane": 1.0,
},
terminationConversion={
'ethane': 0.9,
},
terminationTime=(1e6,'s'),
)
solvation(
solvent='water'
)
simulator(
atol=1e-16,
rtol=1e-8,
)
model(
toleranceKeepInEdge=0.0,
toleranceMoveToCore=0.1,
toleranceInterruptSimulation=0.1,
maximumEdgeSpecies=100000
)
options(
units='si',
saveRestartPeriod=None,
drawMolecules=False,
generatePlots=False,
)
|
Change umask value for dev env | <?php
use Symfony\Component\HttpFoundation\Request;
// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
umask(0000);
// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
|| isset($_SERVER['HTTP_X_FORWARDED_FOR'])
|| !in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', 'fe80::1', '::1'))
) {
header('HTTP/1.0 403 Forbidden');
exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}
$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
require_once __DIR__.'/../app/AppKernel.php';
$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
Request::enableHttpMethodParameterOverride();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
| <?php
use Symfony\Component\HttpFoundation\Request;
// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);
// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
|| isset($_SERVER['HTTP_X_FORWARDED_FOR'])
|| !in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', 'fe80::1', '::1'))
) {
header('HTTP/1.0 403 Forbidden');
exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}
$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
require_once __DIR__.'/../app/AppKernel.php';
$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
Request::enableHttpMethodParameterOverride();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
|
Fix symbolication outside of chrome debugging
Summary:
When debugging in VScode or nucleide using a nodejs environment rather than chrome, the JS sources are made to appear as if they exist on disk, rather than coming from a `http://` url. Prior to this change the packager would see these file paths and not know how to handle them.
Since all the application JS will be part of a bundle file, we can switch out the path to the bundle on the filesystem with paths to the bundle served by the packager, and things will work just as though it was debugging in chrome. We stop the replacement once we reach an internal module (`vm.js` in the case of both nucleide and VSCode) since that is the point when the execution switches from inside the app to the surrounding debugging environment.
I've verified that this fixes redbox stack trace symbolication in VSCode, and from my understanding of nucleide's debugging environment it should also work there without requiring any changes.
Closes https://github.com/facebook/react-native/pull/9906
Differential Revision: D3887166
Pulled By: davidaurelio
fbshipit-source-id: e3a6704f30e0fd045ad836bba51f6e20d9854c30 | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule symbolicateStackTrace
* @flow
*/
'use strict';
const {fetch} = require('fetch');
const getDevServer = require('getDevServer');
const {SourceCode} = require('NativeModules');
import type {StackFrame} from 'parseErrorStack';
async function symbolicateStackTrace(stack: Array<StackFrame>): Promise<Array<StackFrame>> {
const devServer = getDevServer();
if (!devServer.bundleLoadedFromServer) {
throw new Error('Bundle was not loaded from the packager');
}
if (SourceCode.scriptURL) {
for (let i = 0; i < stack.length; ++i) {
// If the sources exist on disk rather than appearing to come from the packager,
// replace the location with the packager URL until we reach an internal source
// which does not have a path (no slashes), indicating a switch from within
// the application to a surrounding debugging environment.
if (/^http/.test(stack[i].file) || !/[\\/]/.test(stack[i].file)) {
break;
}
stack[i].file = SourceCode.scriptURL;
}
}
const response = await fetch(devServer.url + 'symbolicate', {
method: 'POST',
body: JSON.stringify({stack}),
});
const json = await response.json();
return json.stack;
}
module.exports = symbolicateStackTrace;
| /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule symbolicateStackTrace
* @flow
*/
'use strict';
const {fetch} = require('fetch');
const getDevServer = require('getDevServer');
import type {StackFrame} from 'parseErrorStack';
async function symbolicateStackTrace(stack: Array<StackFrame>): Promise<Array<StackFrame>> {
const devServer = getDevServer();
if (!devServer.bundleLoadedFromServer) {
throw new Error('Bundle was not loaded from the packager');
}
const response = await fetch(devServer.url + 'symbolicate', {
method: 'POST',
body: JSON.stringify({stack}),
});
const json = await response.json();
return json.stack;
}
module.exports = symbolicateStackTrace;
|
Update exception handling for levels argument | """
scrapple.utils.exceptions
~~~~~~~~~~~~~~~~~~~~~~~~~
Functions related to handling exceptions in the input arguments
"""
import re
def handle_exceptions(args):
"""
Validates the arguments passed through the CLI commands.
:param args: The arguments passed in the CLI, parsed by the docopt module
:return: None
"""
projectname_re = re.compile(r'[^a-zA-Z0-9_]')
if args['genconfig']:
if args['--type'] not in ['scraper', 'crawler']:
raise Exception("--type has to be 'scraper' or 'crawler'")
if args['--selector'] not in ['xpath', 'css']:
raise Exception("--selector has to be 'xpath' or 'css'")
if args['generate'] or args['run']:
if args['--output_type'] not in ['json', 'csv']:
raise Exception("--output_type has to be 'json' or 'csv'")
if args['genconfig'] or args['generate'] or args['run']:
if projectname_re.search(args['<projectname>']) is not None:
raise Exception("<projectname> should consist of letters, digits or _")
if int(args['--levels']) < 1:
raise Exception("--levels should be greater than, or equal to 1")
return
| """
scrapple.utils.exceptions
~~~~~~~~~~~~~~~~~~~~~~~~~
Functions related to handling exceptions in the input arguments
"""
import re
def handle_exceptions(args):
"""
Validates the arguments passed through the CLI commands.
:param args: The arguments passed in the CLI, parsed by the docopt module
:return: None
"""
projectname_re = re.compile(r'[^a-zA-Z0-9_]')
if args['genconfig']:
if args['--type'] not in ['scraper', 'crawler']:
raise Exception("--type has to be 'scraper' or 'crawler'")
if args['--selector'] not in ['xpath', 'css']:
raise Exception("--selector has to be 'xpath' or 'css'")
if args['generate'] or args['run']:
if args['--output_type'] not in ['json', 'csv']:
raise Exception("--output_type has to be 'json' or 'csv'")
if args['genconfig'] or args['generate'] or args['run']:
if projectname_re.search(args['<projectname>']) is not None:
raise Exception("<projectname> should consist of letters, digits or _")
return
|
tests: Add further tests for class defining __hash__. | # test builtin hash function
print(hash(False))
print(hash(True))
print({():1}) # hash tuple
print({1 << 66:1}) # hash big int
print(hash in {hash:1}) # hash function
try:
hash([])
except TypeError:
print("TypeError")
class A:
def __hash__(self):
return 123
def __repr__(self):
return "a instance"
print(hash(A()))
print({A():1})
# all user-classes have default __hash__
class B:
pass
hash(B())
# if __eq__ is defined then default __hash__ is not used
class C:
def __eq__(self, another):
return True
try:
hash(C())
except TypeError:
print("TypeError")
# __hash__ must return an int
class D:
def __hash__(self):
return None
try:
hash(D())
except TypeError:
print("TypeError")
# __hash__ returning a bool should be converted to an int
class E:
def __hash__(self):
return True
print(hash(E()))
# __hash__ returning a large number should be truncated
class F:
def __hash__(self):
return 1 << 70 | 1
print(hash(F()) != 0)
| # test builtin hash function
print(hash(False))
print(hash(True))
print({():1}) # hash tuple
print({1 << 66:1}) # hash big int
print(hash in {hash:1}) # hash function
try:
hash([])
except TypeError:
print("TypeError")
class A:
def __hash__(self):
return 123
def __repr__(self):
return "a instance"
print(hash(A()))
print({A():1})
# all user-classes have default __hash__
class B:
pass
hash(B())
# if __eq__ is defined then default __hash__ is not used
class C:
def __eq__(self, another):
return True
try:
hash(C())
except TypeError:
print("TypeError")
# __hash__ must return an int
class D:
def __hash__(self):
return None
try:
hash(D())
except TypeError:
print("TypeError")
|
Clarify values used in tests. | # coding: utf-8
from unittest import TestCase
from chipy8 import Memory
class TestMemory(TestCase):
def setUp(self):
self.memory = Memory()
def test_write(self):
'Write a byte to memory then read it.'
address = 0x200
self.memory.write_byte(address, 0x01)
self.assertEqual(0x01, self.memory.read_byte(address))
def test_load(self):
'Load a stream of bytes to memory starting on an address.'
address = 0x200
self.memory.load(address, [0x01, 0x02, 0x03])
self.assertEqual(0x01, self.memory.read_byte(address))
self.assertEqual(0x02, self.memory.read_byte(address + 1))
self.assertEqual(0x03, self.memory.read_byte(address + 2))
| # coding: utf-8
from unittest import TestCase
from chipy8 import Memory
class TestMemory(TestCase):
def setUp(self):
self.memory = Memory()
def test_write(self):
'Write a byte to memory then read it.'
address = 0x200
self.memory.write_byte(0x200, 0x01)
self.assertEqual(0x01, self.memory.read_byte(0x200))
def test_load(self):
'Load a stream of bytes to memory starting on an address.'
address = 0x200
self.memory.load(0x200, [0x01, 0x02, 0x03])
self.assertEqual(0x01, self.memory.read_byte(address))
self.assertEqual(0x02, self.memory.read_byte(address + 1))
self.assertEqual(0x03, self.memory.read_byte(address + 2))
|
Change style of setting records_class default | from __future__ import unicode_literals
__version__ = '1.5.1'
def register(
model, app=None, manager_name='history', records_class=None,
**records_config):
"""
Create historical model for `model` and attach history manager to `model`.
Keyword arguments:
app -- App to install historical model into (defaults to model.__module__)
manager_name -- class attribute name to use for historical manager
records_class -- class to use for history relation (defaults to
HistoricalRecords)
This method should be used as an alternative to attaching an
`HistoricalManager` instance directly to `model`.
"""
from . import models
if model._meta.db_table not in models.registered_models:
if records_class is None:
records_class = models.HistoricalRecords
records = records_class(**records_config)
records.manager_name = manager_name
records.module = app and ("%s.models" % app) or model.__module__
records.add_extra_methods(model)
records.finalize(model)
models.registered_models[model._meta.db_table] = model
| from __future__ import unicode_literals
__version__ = '1.5.1'
def register(
model, app=None, manager_name='history', records_class=None,
**records_config):
"""
Create historical model for `model` and attach history manager to `model`.
Keyword arguments:
app -- App to install historical model into (defaults to model.__module__)
manager_name -- class attribute name to use for historical manager
records_class -- class to use for history relation (defaults to
HistoricalRecords)
This method should be used as an alternative to attaching an
`HistoricalManager` instance directly to `model`.
"""
from . import models
if model._meta.db_table not in models.registered_models:
records_class = records_class or models.HistoricalRecords
records = records_class(**records_config)
records.manager_name = manager_name
records.module = app and ("%s.models" % app) or model.__module__
records.add_extra_methods(model)
records.finalize(model)
models.registered_models[model._meta.db_table] = model
|
Make tags accessible in sidebar
The tags as provided by the query are a Set element.
The sidebar js does not understand Set elements, so
we convert the set to an array.
This is prework for issue #4 | 'use strict';
var buttons = require('sdk/ui/button/action');
buttons.ActionButton({
id: 'elasticmarks-sidebar-button',
label: 'Open Elastic Bookmarks Sidebar',
icon: {
'16': './bookmark-16.png',
'32': './bookmark-32.png',
'64': './bookmark-64.png'
},
onClick: handleClick
});
function handleClick() {
sidebar.show();
}
var sidebar = require('sdk/ui/sidebar').Sidebar({
id: 'elasticmarks-sidebar',
title: 'Elastic Bookmarks Sidebar',
url: './sidebar.html',
onAttach: function (worker) {
worker.port.on('bmquery', function(query, queryId) {
let { search } = require('sdk/places/bookmarks');
search(
{ query: query }
).on('end', function (bookmarks) {
const fixedBookmarks = bookmarks.map(bookmark => {bookmark.tags = [...bookmark.tags]; return bookmark;});
worker.port.emit('queryResults', fixedBookmarks, queryId);
});
});
}
});
| 'use strict';
var buttons = require('sdk/ui/button/action');
buttons.ActionButton({
id: 'elasticmarks-sidebar-button',
label: 'Open Elastic Bookmarks Sidebar',
icon: {
'16': './bookmark-16.png',
'32': './bookmark-32.png',
'64': './bookmark-64.png'
},
onClick: handleClick
});
function handleClick() {
sidebar.show();
}
var sidebar = require('sdk/ui/sidebar').Sidebar({
id: 'elasticmarks-sidebar',
title: 'Elastic Bookmarks Sidebar',
url: './sidebar.html',
onAttach: function (worker) {
worker.port.on('bmquery', function(query, queryId) {
let { search } = require('sdk/places/bookmarks');
search(
{ query: query }
).on('end', function (results) {
worker.port.emit('queryResults', results, queryId);
});
});
}
});
|
Fix matplotlib / pandas 0.21 bug in examples
Here we manually register the pandas matplotlib converters so people
doing manual plotting with pandas works under pandas 0.21 | """
SunPy's TimeSeries module provides a datatype for 1D time series data, replacing the SunPy LightCurve module.
Currently the objects can be instansiated from files (such as CSV and FITS) and urls to these files, but don't include data downloaders for their specific instruments as this will become part of the universal downloader.
"""
from __future__ import absolute_import
from sunpy.timeseries.metadata import TimeSeriesMetaData
from sunpy.timeseries.timeseries_factory import TimeSeries
from sunpy.timeseries.timeseriesbase import GenericTimeSeries
from sunpy.timeseries.sources.eve import EVESpWxTimeSeries
from sunpy.timeseries.sources.goes import XRSTimeSeries
from sunpy.timeseries.sources.noaa import NOAAIndicesTimeSeries, NOAAPredictIndicesTimeSeries
from sunpy.timeseries.sources.lyra import LYRATimeSeries
from sunpy.timeseries.sources.norh import NoRHTimeSeries
from sunpy.timeseries.sources.rhessi import RHESSISummaryTimeSeries
from sunpy.timeseries.sources.fermi_gbm import GBMSummaryTimeSeries
# register pandas datetime converter with matplotlib
# This is to work around the change in pandas-dev/pandas#17710
import pandas.plotting._converter
pandas.plotting._converter.register()
| """
SunPy's TimeSeries module provides a datatype for 1D time series data, replacing the SunPy LightCurve module.
Currently the objects can be instansiated from files (such as CSV and FITS) and urls to these files, but don't include data downloaders for their specific instruments as this will become part of the universal downloader.
"""
from __future__ import absolute_import
from sunpy.timeseries.metadata import TimeSeriesMetaData
from sunpy.timeseries.timeseries_factory import TimeSeries
from sunpy.timeseries.timeseriesbase import GenericTimeSeries
from sunpy.timeseries.sources.eve import EVESpWxTimeSeries
from sunpy.timeseries.sources.goes import XRSTimeSeries
from sunpy.timeseries.sources.noaa import NOAAIndicesTimeSeries, NOAAPredictIndicesTimeSeries
from sunpy.timeseries.sources.lyra import LYRATimeSeries
from sunpy.timeseries.sources.norh import NoRHTimeSeries
from sunpy.timeseries.sources.rhessi import RHESSISummaryTimeSeries
from sunpy.timeseries.sources.fermi_gbm import GBMSummaryTimeSeries
|
Fix typo foce_unicode -> force_unicode | from django import template
from django.conf import settings
from django.utils.encoding import smart_str, force_unicode
from django.utils.safestring import mark_safe
register = template.Library()
def saferst(value):
try:
from docutils.core import publish_parts
except ImportError:
return force_unicode(value)
docutils_setttings = getattr(settings, "RESTRUCTUREDTEXT_FILTER_SETTINGS",
dict())
try:
parts = publish_parts(source=smart_str(value),
writer_name="html4css1",
settings_overrides=docutils_settings)
except:
return force_unicode(value)
else:
return mark_safe(force_unicode(parts["fragment"]))
saferst.is_safe = True
register.filter(saferst)
| from django import template
from django.conf import settings
from django.utils.encoding import smart_str, force_unicode
from django.utils.safestring import mark_safe
register = template.Library()
def saferst(value):
try:
from docutils.core import publish_parts
except ImportError:
return force_unicode(value)
docutils_setttings = getattr(settings, "RESTRUCTUREDTEXT_FILTER_SETTINGS",
dict())
try:
parts = publish_parts(source=smart_str(value),
writer_name="html4css1",
settings_overrides=docutils_settings)
except:
return foce_unicode(value)
else:
return mark_safe(force_unicode(parts["fragment"]))
saferst.is_safe = True
register.filter(saferst)
|
Add more service lookups for Deploys |
if alert['resource'].startswith('R1'):
alert['service'] = [ 'R1' ]
elif alert['resource'].startswith('R2'):
alert['service'] = [ 'R2' ]
elif 'content-api' in alert['resource'].lower():
alert['service'] = [ 'ContentAPI' ]
elif alert['resource'].startswith('frontend'):
alert['service'] = [ 'Frontend' ]
elif 'flexible' in alert['resource'].lower():
alert['service'] = [ 'FlexibleContent' ]
elif alert['resource'].startswith('Identity'):
alert['service'] = [ 'Identity' ]
elif alert['resource'].startswith('Mobile'):
alert['service'] = [ 'Mobile' ]
elif alert['resource'].startswith('Android'):
alert['service'] = [ 'Mobile' ]
elif alert['resource'].startswith('iOS'):
alert['service'] = [ 'Mobile' ]
elif alert['resource'].startswith('Soulmates'):
alert['service'] = [ 'Soulmates' ]
elif alert['resource'].startswith('Microapps'):
alert['service'] = [ 'MicroApp' ]
elif alert['resource'].startswith('Mutualisation'):
alert['service'] = [ 'Mutualisation' ]
elif alert['resource'].startswith('Ophan'):
alert['service'] = [ 'Ophan' ]
else:
alert['service'] = [ 'Unknown' ]
|
if 'r2' in alert['resource'].lower():
alert['service'] = [ 'R2' ]
elif 'content-api' in alert['resource'].lower():
alert['service'] = [ 'ContentAPI' ]
elif 'flexible' in alert['resource'].lower():
alert['service'] = [ 'FlexibleContent' ]
elif 'frontend' in alert['resource'].lower():
alert['service'] = [ 'Frontend' ]
elif 'mobile' in alert['resource'].lower():
alert['service'] = [ 'Mobile' ]
elif 'android' in alert['resource'].lower():
alert['service'] = [ 'Mobile' ]
elif 'ios' in alert['resource'].lower():
alert['service'] = [ 'Mobile' ]
elif 'identity' in alert['resource'].lower():
alert['service'] = [ 'Identity' ]
elif 'microapps' in alert['resource'].lower():
alert['service'] = [ 'MicroApp' ]
else:
alert['service'] = [ 'Unknown' ]
|
Refactor factorial sample to use compileProgramFile |
var cobs = require('../..'),
fs = require('fs');
var runtime = {
display: function() {
var result = '';
if (arguments && arguments.length)
for (var k = 0; k < arguments.length; k++)
if (arguments[k])
result += arguments[k].toString();
console.log(result);
}
}
function runFile(filename) {
cobs.compileProgramFile(filename).run(runtime);
};
process.argv.forEach(function(val) {
if (val.slice(-4) == ".cob")
runFile(val);
});
|
var cobs = require('../..'),
fs = require('fs');
var runtime = {
display: function() {
var result = '';
if (arguments && arguments.length)
for (var k = 0; k < arguments.length; k++)
if (arguments[k])
result += arguments[k].toString();
console.log(result);
}
}
function runFile(filename) {
var text = fs.readFileSync(filename).toString();
var parser = new cobs.Parser(text);
var program = parser.parseProgram();
cobs.run(program.command.compile(program), runtime, program);
};
process.argv.forEach(function(val) {
if (val.slice(-5) == ".cobs" || val.slice(-4) == ".cob")
runFile(val);
});
|
Fix for non-existent rst README | import os
from setuptools import setup
install_requires = [
'Flask',
'Flask-Babel',
]
if os.path.exists('README'):
with open('README') as f:
readme = f.read()
else:
readme = None
setup(
name='Flask-Table',
packages=['flask_table'],
version='0.3.1',
author='Andrew Plummer',
author_email='plummer574@gmail.com',
url='https://github.com/plumdog/flask_table',
description='HTML tables for use with the Flask micro-framework',
install_requires=install_requires,
test_suite='tests',
tests_require=['flask-testing'],
long_description=readme,
classifiers=[
'Development Status :: 3 - Alpha',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Operating System :: OS Independent',
'Framework :: Flask',
])
| from setuptools import setup
install_requires = [
'Flask',
'Flask-Babel',
]
with open('README') as f:
readme = f.read()
setup(
name='Flask-Table',
packages=['flask_table'],
version='0.3.1',
author='Andrew Plummer',
author_email='plummer574@gmail.com',
url='https://github.com/plumdog/flask_table',
description='HTML tables for use with the Flask micro-framework',
install_requires=install_requires,
test_suite='tests',
tests_require=['flask-testing'],
long_description=readme,
classifiers=[
'Development Status :: 3 - Alpha',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Operating System :: OS Independent',
'Framework :: Flask',
])
|
Check position count in Block and Page assertions | /*
* 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.facebook.presto.operator;
import com.facebook.presto.spi.Page;
import com.facebook.presto.spi.type.Type;
import java.util.List;
import static com.facebook.presto.block.BlockAssertions.assertBlockEquals;
import static org.testng.Assert.assertEquals;
public final class PageAssertions
{
private PageAssertions()
{
}
public static void assertPageEquals(List<? extends Type> types, Page actualPage, Page expectedPage)
{
assertEquals(types.size(), actualPage.getChannelCount());
assertEquals(actualPage.getChannelCount(), expectedPage.getChannelCount());
assertEquals(actualPage.getPositionCount(), expectedPage.getPositionCount());
for (int i = 0; i < actualPage.getChannelCount(); i++) {
assertBlockEquals(types.get(i), actualPage.getBlock(i), expectedPage.getBlock(i));
}
}
}
| /*
* 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.facebook.presto.operator;
import com.facebook.presto.spi.Page;
import com.facebook.presto.spi.type.Type;
import java.util.List;
import static com.facebook.presto.block.BlockAssertions.assertBlockEquals;
import static org.testng.Assert.assertEquals;
public final class PageAssertions
{
private PageAssertions()
{
}
public static void assertPageEquals(List<? extends Type> types, Page actualPage, Page expectedPage)
{
assertEquals(types.size(), actualPage.getChannelCount());
assertEquals(actualPage.getChannelCount(), expectedPage.getChannelCount());
for (int i = 0; i < actualPage.getChannelCount(); i++) {
assertBlockEquals(types.get(i), actualPage.getBlock(i), expectedPage.getBlock(i));
}
}
}
|
Remove false assertion from test | from tests import PMGLiveServerTestCase
from tests.fixtures import dbfixture, CallForCommentData
import urllib.request, urllib.error, urllib.parse
class TestCallsForCommentsPage(PMGLiveServerTestCase):
def setUp(self):
super(TestCallsForCommentsPage, self).setUp()
self.fx = dbfixture.data(CallForCommentData)
self.fx.setup()
def tearDown(self):
self.fx.teardown()
super(TestCallsForCommentsPage, self).tearDown()
def test_calls_for_comments(self):
"""
Test calls for comments page (/calls-for-comments/)
"""
call_for_comment = self.fx.CallForCommentData.arts_call_for_comment_one
self.make_request("/calls-for-comments/")
self.assertIn(call_for_comment.title, self.html)
| from tests import PMGLiveServerTestCase
from tests.fixtures import dbfixture, CallForCommentData
import urllib.request, urllib.error, urllib.parse
class TestCallsForCommentsPage(PMGLiveServerTestCase):
def setUp(self):
super(TestCallsForCommentsPage, self).setUp()
self.fx = dbfixture.data(CallForCommentData)
self.fx.setup()
def tearDown(self):
self.fx.teardown()
super(TestCallsForCommentsPage, self).tearDown()
def test_calls_for_comments(self):
"""
Test calls for comments page (/calls-for-comments/)
"""
call_for_comment = self.fx.CallForCommentData.arts_call_for_comment_one
self.make_request("/calls-for-comments/")
self.assertIn(call_for_comment.title, self.html)
self.assertTrue(False)
|
Replace mock for Pslackr with real object | <?php
namespace FullyBaked\Pslackr;
use PHPUnit_Framework_TestCase;
class PslackrTest extends PHPUnit_Framework_TestCase
{
public function testConstructorSetsConfigProperty()
{
$config = ['domain' => 'tester', 'token' => '123456'];
$relection = new \ReflectionClass('FullyBaked\Pslackr\Pslackr');
$tokenAttr = $relection->getProperty('token');
$tokenAttr->setAccessible(true);
$domainAttr = $relection->getProperty('domain');
$domainAttr->setAccessible(true);
$slack = new Pslackr($config);
$this->assertEquals($config['token'], $tokenAttr->getValue($slack));
$this->assertEquals($config['domain'], $domainAttr->getValue($slack));
}
}
| <?php
namespace FullyBaked\Pslackr;
use PHPUnit_Framework_TestCase;
class PslackrTest extends PHPUnit_Framework_TestCase
{
public function testConstructorSetsConfigProperty()
{
$config = ['domain' => 'tester', 'token' => '123456'];
$relection = new \ReflectionClass('FullyBaked\Pslackr\Pslackr');
$tokenAttr = $relection->getProperty('token');
$tokenAttr->setAccessible(true);
$domainAttr = $relection->getProperty('domain');
$domainAttr->setAccessible(true);
$slack = $this->getMockBuilder('FullyBaked\Pslackr\Pslackr')
->setConstructorArgs([$config])
->getMock();
$this->assertEquals($config['token'], $tokenAttr->getValue($slack));
$this->assertEquals($config['domain'], $domainAttr->getValue($slack));
}
}
|
feat: Add created file to sublime | """createTodoFile.py: Creates an todo file with title name as current date"""
import os.path
import time
def createfile():
# My-File--2009-12-31--23-59-59.txt
date = time.strftime("%d-%m-%Y")
filename = "GOALS--" + date + ".todo"
if not os.path.exists(filename):
with open(filename, "a") as myfile:
myfile.write("[RESULTS - {}]".format(date))
print("INFO: " + filename + " created!")
addfileToSublime(filename)
else:
print("ERROR: " + filename + " already exist! Exiting..")
def addfileToSublime(file):
os.system("subl --add " + file)
def main():
createfile()
if __name__ == '__main__':
main()
| """createTodoFile.py: Creates an todo file with title name as current date"""
import time
import os.path
def createfile():
# My-File--2009-12-31--23-59-59.txt
date = time.strftime("%d-%m-%Y")
filename = "GOALS--" + date + ".todo"
if not os.path.exists(filename):
with open(filename, "a") as myfile:
myfile.write("[RESULTS - {}]".format(date))
print("INFO: " + filename + " created!")
else:
print("ERROR: " + filename + " already exist! Exiting..")
# TODO: To move files into archive if more than a week
def archiveFiles():
pass
def main():
createfile()
if __name__ == '__main__':
main()
|
Apply default preference values in xml to preference store | /*******************************************************************************
* Copyright (c) Incoming Pty. Ltd. 2015
******************************************************************************/
package com.incoming.example.incomingpvntemplate;
import android.app.Activity;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
/**
* Basic settings Activity that includes the default Push Video settings and some content targeting settings for the user.
*/
public class PVNTemplateSettings extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Display the settings fragment as the main content.
getFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsFragment()).commit();
// Apply the default values from the preferences file. This is important if application preferences are used to control audience
// segmentation targets.
PreferenceManager.setDefaultValues(PVNTemplateSettings.this, R.xml.pvn_preferences, false);
PreferenceManager.setDefaultValues(PVNTemplateSettings.this, R.xml.preferences, false);
}
public static class SettingsFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Include the content targeting settings
addPreferencesFromResource(R.xml.preferences);
// Include the PVN SDK settings
addPreferencesFromResource(R.xml.pvn_preferences);
}
}
}
| /*******************************************************************************
* Copyright (c) Incoming Pty. Ltd. 2015
******************************************************************************/
package com.incoming.example.incomingpvntemplate;
import android.app.Activity;
import android.os.Bundle;
import android.preference.PreferenceFragment;
/**
* Basic settings Activity that includes the default Push Video settings and some content targeting settings for the user.
*/
public class PVNTemplateSettings extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Display the Push Video settings fragment as the main content.
getFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsFragment()).commit();
}
public static class SettingsFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Include the content targeting settings
addPreferencesFromResource(R.xml.preferences);
// Include the PVN SDK settings
addPreferencesFromResource(R.xml.pvn_preferences);
}
}
}
|
Add exception handler for attachment related operations | class BugsyException(Exception):
"""
If while interacting with Bugzilla and we try do something that is not
supported this error will be raised.
"""
def __init__(self, msg, error_code=None):
self.msg = msg
self.code = error_code
def __str__(self):
return "Message: {message} Code: {code}".format(message=self.msg,
code=self.code)
class LoginException(BugsyException):
"""
If a username and password are passed in but we don't receive a token
then this error will be raised.
"""
pass
class AttachmentException(BugsyException):
"""
If we try do something that is not allowed to an attachment then
this error is raised
"""
pass
class BugException(BugsyException):
"""
If we try do something that is not allowed to a bug then
this error is raised
"""
pass
class SearchException(BugsyException):
"""
If while interacting with Bugzilla and we try do something that is not
supported this error will be raised.
"""
pass
| class BugsyException(Exception):
"""
If while interacting with Bugzilla and we try do something that is not
supported this error will be raised.
"""
def __init__(self, msg, error_code=None):
self.msg = msg
self.code = error_code
def __str__(self):
return "Message: {message} Code: {code}".format(message=self.msg,
code=self.code)
class LoginException(BugsyException):
"""
If a username and password are passed in but we don't receive a token
then this error will be raised.
"""
pass
class BugException(BugsyException):
"""
If we try do something that is not allowed to a bug then
this error is raised
"""
pass
class SearchException(BugsyException):
"""
If while interacting with Bugzilla and we try do something that is not
supported this error will be raised.
"""
pass
|
Fix indentation and remove trailing whitespaces | package <%=packageName%>.web.rest;
import java.io.IOException;
import java.nio.charset.Charset;
import org.springframework.http.MediaType;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Utility class for testing REST controllers.
*/
public class TestUtil {
/** MediaType for JSON UTF8 */
public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(
MediaType.APPLICATION_JSON.getType(),
MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
/**
* Convert an object to JSON byte array.
*
* @param object
* the object to convert
* @return the JSON byte array
* @throws IOException
*/
public static byte[] convertObjectToJsonBytes(Object object)
throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return mapper.writeValueAsBytes(object);
}
}
| package <%=packageName%>.web.rest;
import java.io.IOException;
import java.nio.charset.Charset;
import org.springframework.http.MediaType;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Utility class for testing REST controllers.
*/
public class TestUtil {
/** MediaType for JSON UTF8 */
public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(
MediaType.APPLICATION_JSON.getType(),
MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
/**
* Convert an object to JSON byte array.
*
* @param object
* the object to convert
* @return the JSON byte array
* @throws IOException
*/
public static byte[] convertObjectToJsonBytes(Object object)
throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return mapper.writeValueAsBytes(object);
}
}
|
Add a guard clause to ResponseNewWindow | function ResponsesNewWindow(surveyID) {
try {
var ResponsesIndexView = require('ui/common/responses/ResponsesIndexView');
var ResponsesNewView = require('ui/common/responses/ResponsesNewView');
var ConfirmDialog = require('ui/common/components/ConfirmDialog');
var self = Ti.UI.createWindow({
navBarHidden : true,
backgroundColor : "#fff"
});
var view = new ResponsesNewView(surveyID);
self.add(view);
view.addEventListener('ResponsesNewView:savedResponse', function() {
Ti.App.fireEvent('ResponseNewWindow:closed');
view.cleanup();
view = null;
self.close();
});
var confirmDialog = new ConfirmDialog(L("confirm"), L("confirm_clear_answers"), onConfirm = function(e) {
if(view) {
view.cleanup();
}
view = null;
self.close();
});
self.addEventListener('android:back', function() {
confirmDialog.show();
});
return self;
}
catch(e) {
var auditor = require('helpers/Auditor');
auditor.writeIntoAuditFile(arguments.callee.name + " - " + e.toString());
}
}
module.exports = ResponsesNewWindow;
| function ResponsesNewWindow(surveyID) {
try {
var ResponsesIndexView = require('ui/common/responses/ResponsesIndexView');
var ResponsesNewView = require('ui/common/responses/ResponsesNewView');
var ConfirmDialog = require('ui/common/components/ConfirmDialog');
var self = Ti.UI.createWindow({
navBarHidden : true,
backgroundColor : "#fff"
});
var view = new ResponsesNewView(surveyID);
self.add(view);
view.addEventListener('ResponsesNewView:savedResponse', function() {
Ti.App.fireEvent('ResponseNewWindow:closed');
view.cleanup();
view = null;
self.close();
});
var confirmDialog = new ConfirmDialog(L("confirm"), L("confirm_clear_answers"), onConfirm = function(e) {
view.cleanup();
view = null;
self.close();
});
self.addEventListener('android:back', function() {
confirmDialog.show();
});
return self;
}
catch(e) {
var auditor = require('helpers/Auditor');
auditor.writeIntoAuditFile(arguments.callee.name + " - " + e.toString());
}
}
module.exports = ResponsesNewWindow;
|
Make buildUrl return a non-encoded url by default | // We faced a bug in babel so that transform-runtime with export * from 'x' generates import statements in transpiled code
// Tracked here : https://github.com/babel/babel/issues/2877
// We tested the workaround given here https://github.com/babel/babel/issues/2877#issuecomment-270700000 with success so far
import _ from 'lodash'
import * as errors from './errors'
import * as permissions from './permissions'
export { errors }
export { permissions }
// Append a parameter value to a given URL
export function addQueryParameter(baseUrl, parameter, value) {
// Check if this is the first parameter to be added or not
const prefix = (baseUrl.includes('?') ? '&' : '?')
return `${baseUrl}${prefix}${parameter}=${Array.isArray(value) ? JSON.stringify(value) : value}`
}
// Build an URL from a given set of parameters
export function buildUrl(baseUrl, parameters) {
let url = baseUrl
_.forOwn(parameters, function(value, key) {
url = addQueryParameter(url, key, value)
})
return url
}
// Build an encoded URL from a given set of parameters
export function buildEncodedUrl(baseUrl, parameters) {
return encodeURI(buildEncodedUrl(baseUrl, parameters))
}
| // We faced a bug in babel so that transform-runtime with export * from 'x' generates import statements in transpiled code
// Tracked here : https://github.com/babel/babel/issues/2877
// We tested the workaround given here https://github.com/babel/babel/issues/2877#issuecomment-270700000 with success so far
import _ from 'lodash'
import * as errors from './errors'
import * as permissions from './permissions'
export { errors }
export { permissions }
// Append a parameter value to a given URL
export function addQueryParameter(baseUrl, parameter, value) {
// Check if this is the first parameter to be added or not
const prefix = (baseUrl.includes('?') ? '&' : '?')
return `${baseUrl}${prefix}${parameter}=${Array.isArray(value) ? JSON.stringify(value) : value}`
}
// Build an encoded URL from a given set of parameters
export function buildUrl(baseUrl, parameters) {
let url = baseUrl
_.forOwn(parameters, function(value, key) {
url = addQueryParameter(url, key, value)
})
return encodeURI(url)
}
|
Add catch of license error from JxBrowser | package com.github.hronom.scrape.dat.rooms.core.webpage.html.grabbers;
import com.teamdev.jxbrowser.chromium.Browser;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class JxBrowserGrabber implements Grabber {
private static final Logger logger = LogManager.getLogger();
private Browser browser;
public JxBrowserGrabber() {
try {
browser = new Browser();
} catch (ExceptionInInitializerError exceptionInInitializerError) {
logger.error(exceptionInInitializerError);
}
}
@Override
public String grabHtml(String webpageUrl) {
browser.loadURL(webpageUrl);
// Wait for loading.
while (browser.isLoading()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
String html = browser.getHTML();
html = StringEscapeUtils.unescapeHtml4(html);
browser.stop();
return html;
}
}
| package com.github.hronom.scrape.dat.rooms.core.webpage.html.grabbers;
import com.teamdev.jxbrowser.chromium.Browser;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class JxBrowserGrabber implements Grabber {
private static final Logger logger = LogManager.getLogger();
private final Browser browser;
public JxBrowserGrabber() {
browser = new Browser();
}
@Override
public String grabHtml(String webpageUrl) {
browser.loadURL(webpageUrl);
// Wait for loading.
while (browser.isLoading()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
String html = browser.getHTML();
html = StringEscapeUtils.unescapeHtml4(html);
browser.stop();
return html;
}
}
|
Use sendall instead of send for socket messages
I kept getting Errno 111 connection refused errors; I hope this fixes
it. | """Message broker that sends to Unix domain sockets."""
import os
import socket
import time
class MessageProducer(object):
"""Message broker that sends to Unix domain sockets."""
def __init__(self, message_type):
self._message_type = message_type
socket_address = os.sep.join(
('.', 'messaging', 'sockets', message_type)
)
if not os.path.exists(socket_address):
raise ValueError('Socket does not exist: {}'.format(socket_address))
self._socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
self._socket.connect(socket_address)
def publish(self, message):
"""Publishes a message."""
self._socket.sendall(message.encode('utf-8'))
def kill(self):
"""Kills all listening consumers."""
try:
self._socket.sendall(b'QUIT')
except ConnectionRefusedError: # pylint: disable=undefined-variable
pass
| """Message broker that sends to Unix domain sockets."""
import os
import socket
import time
class MessageProducer(object):
"""Message broker that sends to Unix domain sockets."""
def __init__(self, message_type):
self._message_type = message_type
socket_address = os.sep.join(
('.', 'messaging', 'sockets', message_type)
)
if not os.path.exists(socket_address):
raise ValueError('Socket does not exist: {}'.format(socket_address))
self._socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
self._socket.connect(socket_address)
def publish(self, message):
"""Publishes a message."""
self._socket.send(message.encode('utf-8'))
def kill(self):
"""Kills all listening consumers."""
try:
self._socket.send(b'QUIT')
except ConnectionRefusedError: # pylint: disable=undefined-variable
pass
|
Attach admin policy to actions which create or destroy groups, rooms, or users.
Signed-off-by: Max Fierke <0706025b2bbcec1ed8d64822f4eccd96314938d0@maxfierke.com> | /**
* Policies are simply Express middleware functions which run before your controllers.
* You can apply one or more policies for a given controller or action.
*
* Any policy file (e.g. `authenticated.js`) can be dropped into the `/policies` folder,
* at which point it can be accessed below by its filename, minus the extension, (e.g. `authenticated`)
*
* For more information on policies, check out:
* http://sailsjs.org/#documentation
*/
module.exports.policies = {
// Default policy for all controllers and actions
// (`true` allows public access)
'*': true,
GroupController: {
'*': 'authenticated',
'create': ['authenticated', 'admin'],
'manage': ['authenticated', 'admin'],
'user_add': ['authenticated', 'admin'],
'user_delete': ['authenticated', 'admin'],
'destroy': ['authenticated', 'admin']
},
MainController: {
'dashboard': 'authenticated'
},
MessageController: {
'*': 'authenticated'
},
RoomController: {
'*': 'authenticated',
'create': ['authenticated', 'admin'],
'manage': ['authenticated', 'admin'],
'destroy': ['authenticated', 'admin']
},
UserController: {
'*': 'authenticated',
'manage': ['authenticated', 'admin'],
'create': true
}
};
| /**
* Policies are simply Express middleware functions which run before your controllers.
* You can apply one or more policies for a given controller or action.
*
* Any policy file (e.g. `authenticated.js`) can be dropped into the `/policies` folder,
* at which point it can be accessed below by its filename, minus the extension, (e.g. `authenticated`)
*
* For more information on policies, check out:
* http://sailsjs.org/#documentation
*/
module.exports.policies = {
// Default policy for all controllers and actions
// (`true` allows public access)
'*': true,
GroupController: {
'*': 'authenticated'
},
MainController: {
'dashboard': 'authenticated'
},
RoomController: {
'*': 'authenticated'
},
UserController: {
'*': 'authenticated',
'create': true
}
};
|
Set correct type to member variable and return value | <?php
/**
* This file is part of the PHP Generics package.
*
* @package Generics
*/
namespace Generics\Logger;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
trait LoggerTrait
{
/**
* Logger instance
*
* @var \Psr\Log\LoggerInterface
*/
private $logger = null;
/*
* (non-PHPdoc)
* @see \Psr\Log\LoggerAwareInterface::setLogger()
*/
public function setLogger(LoggerInterface $logger)
{
$this->logger = $logger;
}
/**
* Initialize the logger instance
*/
private function initLogger()
{
if (null === $this->logger) {
$this->logger = new NullLogger();
}
}
/**
* Retrieve the logger instance
*
* @return \Psr\Log\LoggerInterface
*/
private function getLog()
{
$this->initLogger();
return $this->logger;
}
}
| <?php
/**
* This file is part of the PHP Generics package.
*
* @package Generics
*/
namespace Generics\Logger;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
trait LoggerTrait
{
/**
* Logger instance
*
* @var AbstractLogger
*/
private $logger = null;
/*
* (non-PHPdoc)
* @see \Psr\Log\LoggerAwareInterface::setLogger()
*/
public function setLogger(LoggerInterface $logger)
{
$this->logger = $logger;
}
/**
* Initialize the logger instance
*/
private function initLogger()
{
if (null === $this->logger) {
$this->logger = new NullLogger();
}
}
/**
* Retrieve the logger instance
*
* @return \Generics\Logger\AbstractLogger
*/
private function getLog()
{
$this->initLogger();
return $this->logger;
}
}
|
Add comment about strange inverted err check. | package players
import "errors"
import "github.com/m4rw3r/uuid"
import "golang.org/x/crypto/bcrypt"
//import "fmt"
// The user associated with a player
type User struct {
Username string `json:"username"`
password string
Apikey string `json:"apikey"`
Admin bool `json:"admin"`
Locked bool `json:"locked"`
Settings UserSettings `json:"settings"`
}
// Create a user
func NewUser(player uuid.UUID, userdata *User) (*User, error) {
p, err := storage.Load(player)
if err != nil {
return nil, err
}
p.User = *userdata
err = storage.Store(p)
if err != nil {
return nil,
errors.New(err.Error() + " - Could not write user to storage")
}
return &p.User, nil
}
// The user preferences/settings of the user
type UserSettings struct {
Notifications map[string]bool `json:"notifications"`
}
func UserByName(username string) (*User, error) {
return storage.LoadUser(username)
}
func AuthUser(username string, password string) bool {
user, err := storage.LoadUser(username)
if err != nil {
return false
}
// No error from comparison means the hashes match
if err := bcrypt.CompareHashAndPassword([]byte(user.password), []byte(password)); err == nil {
return true
}
return false
}
| package players
import "errors"
import "github.com/m4rw3r/uuid"
import "golang.org/x/crypto/bcrypt"
//import "fmt"
// The user associated with a player
type User struct {
Username string `json:"username"`
password string
Apikey string `json:"apikey"`
Admin bool `json:"admin"`
Locked bool `json:"locked"`
Settings UserSettings `json:"settings"`
}
// Create a user
func NewUser(player uuid.UUID, userdata *User) (*User, error) {
p, err := storage.Load(player)
if err != nil {
return nil, err
}
p.User = *userdata
err = storage.Store(p)
if err != nil {
return nil,
errors.New(err.Error() + " - Could not write user to storage")
}
return &p.User, nil
}
// The user preferences/settings of the user
type UserSettings struct {
Notifications map[string]bool `json:"notifications"`
}
func UserByName(username string) (*User, error) {
return storage.LoadUser(username)
}
func AuthUser(username string, password string) bool {
user, err := storage.LoadUser(username)
if err != nil {
return false
}
if err := bcrypt.CompareHashAndPassword([]byte(user.password), []byte(password)); err == nil {
return true
}
return false
}
|
Add parameters to /signin (POST) request header | function proceedSignin() {
'use strict';
event.preventDefault();
var emailField = document.getElementById('email'),
passwordField = document.getElementById('password');
var user = {
username: emailField.value,
password: passwordField.value
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (this.status === 200) {
window.location = '/rooms';
}
if (this.status === 401) {
document.getElementById('signin-message').innerHTML = 'Le mot de passe ou le pseudonyme est incorrect. <br /> Avez-vous confirmé votre inscription ?';
}
}
};
xhr.open('POST', '/signin', true);
xhr.setRequestHeader('content-type', 'application/json; charset=utf-8');
xhr.setRequestHeader('x-requested-with', 'XMLHttpRequest');
xhr.send(JSON.stringify(user));
}
document.addEventListener('DOMContentLoaded', function () {
'use strict';
var signinSubmit = document.getElementById('signin-submit');
signinSubmit.addEventListener('click', proceedSignin, false);
}, false); | function proceedSignin() {
'use strict';
event.preventDefault();
var emailField = document.getElementById('email'),
passwordField = document.getElementById('password');
var user = {
username: emailField.value,
password: passwordField.value
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (this.status === 200) {
window.location = '/rooms';
}
if (this.status === 401) {
document.getElementById('signin-message').innerHTML = 'Le mot de passe ou le pseudonyme est incorrect. <br /> Avez-vous confirmé votre inscription ?';
}
}
};
xhr.open('POST', '/signin', true);
xhr.setRequestHeader('content-type', 'application/json; charset=utf-8');
xhr.send(JSON.stringify(user));
}
document.addEventListener('DOMContentLoaded', function () {
'use strict';
var signinSubmit = document.getElementById('signin-submit');
signinSubmit.addEventListener('click', proceedSignin, false);
}, false); |
Adjust REPL component target element | import Repl from './Repl.html';
import examples from './examples.js';
function tryParseData ( encoded ) {
try {
return JSON.parse( decodeURIComponent( atob( encoded ) ) );
} catch ( err ) {
return {};
}
}
if ( typeof svelte !== 'undefined' ) {
const dataMatch = /data=(.+)$/.exec( window.location.search );
const { source, data } = dataMatch ? tryParseData( dataMatch[1] ) : {};
const gistMatch = /gist=(.+)$/.exec( window.location.search );
const gist = gistMatch ? gistMatch[1] : ( source ? null : examples[0].gist );
const repl = new Repl({
target: document.querySelector( '.repl' ),
data: {
gist,
source,
data
}
});
window.repl = repl;
} else {
document.querySelector( '.repl' ).innerHTML = `<p style='text-align: center; margin: 0; padding: 4em 3em 8em 3em; line-height: 1.5;'>Svelte generates components that work in all modern JavaScript environments, but the Svelte compiler only runs in Node 6+ and browsers that support ES2015 features. Please reopen this page in a different browser such as Chrome.</p>`;
}
| import Repl from './Repl.html';
import examples from './examples.js';
function tryParseData ( encoded ) {
try {
return JSON.parse( decodeURIComponent( atob( encoded ) ) );
} catch ( err ) {
return {};
}
}
if ( typeof svelte !== 'undefined' ) {
const dataMatch = /data=(.+)$/.exec( window.location.search );
const { source, data } = dataMatch ? tryParseData( dataMatch[1] ) : {};
const gistMatch = /gist=(.+)$/.exec( window.location.search );
const gist = gistMatch ? gistMatch[1] : ( source ? null : examples[0].gist );
const repl = new Repl({
target: document.querySelector( 'main' ),
data: {
gist,
source,
data
}
});
window.repl = repl;
} else {
document.querySelector( 'main' ).innerHTML = `<p style='text-align: center; margin: 0; padding: 4em 3em 8em 3em; line-height: 1.5;'>Svelte generates components that work in all modern JavaScript environments, but the Svelte compiler only runs in Node 6+ and browsers that support ES2015 features. Please reopen this page in a different browser such as Chrome.</p>`;
}
|
Add files writer to solution app | from IPython.config.loader import Config
from IPython.config.application import catch_config_error
from IPython.utils.traitlets import Unicode
from nbgrader.apps.customnbconvertapp import CustomNbConvertApp
class SolutionApp(CustomNbConvertApp):
name = Unicode(u'nbgrader-solution')
description = Unicode(u'Prepare a solution version of an assignment')
def _export_format_default(self):
return 'notebook'
def build_extra_config(self):
self.extra_config = Config()
self.extra_config.Exporter.preprocessors = [
'nbgrader.preprocessors.IncludeHeaderFooter',
'nbgrader.preprocessors.TableOfContents',
'nbgrader.preprocessors.RenderSolutions',
'nbgrader.preprocessors.ExtractTests',
'IPython.nbconvert.preprocessors.ExecutePreprocessor'
]
self.extra_config.RenderSolutions.solution = True
self.extra_config.NbGraderApp.writer_class = 'IPython.nbconvert.writers.FilesWriter'
self.config.merge(self.extra_config)
| from IPython.config.loader import Config
from IPython.config.application import catch_config_error
from IPython.utils.traitlets import Unicode
from nbgrader.apps.customnbconvertapp import CustomNbConvertApp
class SolutionApp(CustomNbConvertApp):
name = Unicode(u'nbgrader-solution')
description = Unicode(u'Prepare a solution version of an assignment')
def _export_format_default(self):
return 'notebook'
def build_extra_config(self):
self.extra_config = Config()
self.extra_config.Exporter.preprocessors = [
'nbgrader.preprocessors.IncludeHeaderFooter',
'nbgrader.preprocessors.TableOfContents',
'nbgrader.preprocessors.RenderSolutions',
'nbgrader.preprocessors.ExtractTests',
'IPython.nbconvert.preprocessors.ExecutePreprocessor'
]
self.extra_config.RenderSolutions.solution = True
self.config.merge(self.extra_config)
|
Add registry settings to testing | # include settimgs from daiquiri
from daiquiri.core.settings.django import *
from daiquiri.core.settings.celery import *
from daiquiri.core.settings.daiquiri import *
from daiquiri.core.settings.logging import *
from daiquiri.core.settings.vendor import *
from daiquiri.archive.settings import *
from daiquiri.auth.settings import *
from daiquiri.conesearch.settings import *
from daiquiri.cutout.settings import *
from daiquiri.files.settings import *
from daiquiri.meetings.settings import *
from daiquiri.metadata.settings import *
from daiquiri.oai.settings import *
from daiquiri.query.settings import *
from daiquiri.registry.settings import *
from daiquiri.serve.settings import *
from daiquiri.stats.settings import *
from daiquiri.tap.settings import *
from daiquiri.wordpress.settings import *
# override settings from base.py (which is checked in to git)
try:
from .base import *
except ImportError:
pass
# override settings from local.py (which is not checked in to git)
try:
from .local import *
except ImportError:
pass
| # include settimgs from daiquiri
from daiquiri.core.settings.django import *
from daiquiri.core.settings.celery import *
from daiquiri.core.settings.daiquiri import *
from daiquiri.core.settings.logging import *
from daiquiri.core.settings.vendor import *
from daiquiri.archive.settings import *
from daiquiri.auth.settings import *
from daiquiri.conesearch.settings import *
from daiquiri.cutout.settings import *
from daiquiri.files.settings import *
from daiquiri.meetings.settings import *
from daiquiri.metadata.settings import *
from daiquiri.oai.settings import *
from daiquiri.query.settings import *
from daiquiri.serve.settings import *
from daiquiri.stats.settings import *
from daiquiri.tap.settings import *
from daiquiri.wordpress.settings import *
# override settings from base.py (which is checked in to git)
try:
from .base import *
except ImportError:
pass
# override settings from local.py (which is not checked in to git)
try:
from .local import *
except ImportError:
pass
|
Fix division for bits (not bytes) | #!/usr/bin/env python3
import os
import subprocess
import re
import datetime
import pygsheets
import speedtest
# Set constants
DATE = datetime.datetime.now().strftime("%d-%m-%y %H:%M:%S")
def get_credentials():
"""Function to check for valid OAuth access tokens."""
gc = pygsheets.authorize(outh_file="credentials.json")
return gc
def submit_into_spreadsheet(download, upload, ping):
"""Function to submit speedtest result."""
gc = get_credentials()
speedtest = gc.open(os.getenv('SPREADSHEET', 'Speedtest'))
sheet = speedtest.sheet1
data = [DATE, download, upload, ping]
sheet.append_table(values=data)
def main():
# Check for proper credentials
print("Checking OAuth validity...")
credentials = get_credentials()
# Run speedtest and store output
print("Starting speed test...")
spdtest = speedtest.Speedtest()
spdtest.get_best_server()
download = round(spdtest.download() / 1000 / 1000, 2)
upload = round(spdtest.upload() / 1000 / 1000, 2)
ping = round(spdtest.results.ping)
print("Starting speed finished (Download: ", download, ", Upload: ", upload, ", Ping: ", ping, ")")
# Write to spreadsheet
print("Writing to spreadsheet...")
submit_into_spreadsheet(download, upload, ping)
print("Successfuly written to spreadsheet!")
if __name__ == "__main__":
main()
| #!/usr/bin/env python3
import os
import subprocess
import re
import datetime
import pygsheets
import speedtest
# Set constants
DATE = datetime.datetime.now().strftime("%d-%m-%y %H:%M:%S")
def get_credentials():
"""Function to check for valid OAuth access tokens."""
gc = pygsheets.authorize(outh_file="credentials.json")
return gc
def submit_into_spreadsheet(download, upload, ping):
"""Function to submit speedtest result."""
gc = get_credentials()
speedtest = gc.open(os.getenv('SPREADSHEET', 'Speedtest'))
sheet = speedtest.sheet1
data = [DATE, download, upload, ping]
sheet.append_table(values=data)
def main():
# Check for proper credentials
print("Checking OAuth validity...")
credentials = get_credentials()
# Run speedtest and store output
print("Starting speed test...")
spdtest = speedtest.Speedtest()
spdtest.get_best_server()
download = round(spdtest.download() / 1024 / 1024, 2)
upload = round(spdtest.upload() / 1024 / 1024, 2)
ping = round(spdtest.results.ping)
print("Starting speed finished (Download: ", download, ", Upload: ", upload, ", Ping: ", ping, ")")
# Write to spreadsheet
print("Writing to spreadsheet...")
submit_into_spreadsheet(download, upload, ping)
print("Successfuly written to spreadsheet!")
if __name__ == "__main__":
main()
|
Fix typo in file_util import | #!/usr/bin/env python
from distutils.core import setup
from distutils.file_util import copy_file
import platform
version = "0.1.0"
setup(name="riemann-sumd",
version=version,
description="Python agent for scheduling event generating processes and sending the results to Riemann",
author="Brian Hatfield",
author_email="bmhatfield@gmail.com",
url="https://github.com/bmhatfield/riemann-sumd",
package_dir={'': 'lib'},
py_modules=['event', 'loader', 'scheduler', 'sender', 'task'],
data_files=[('/etc/init/', ["init/ubuntu/sumd.conf"]),
('/etc/sumd', ['examples/etc/sumd/sumd.conf']),
('/etc/sumd/tasks.d', ['examples/etc/sumd/tasks.d/simple.task.example']),
('/etc/sumd/tags.d', ['examples/etc/sumd/tags.d/simple.tag.example'])],
scripts=["bin/sumd"]
)
copy_file('/lib/init/upstart-job', '/etc/init.d/sumd', link='sym') | #!/usr/bin/env python
from distutils.core import setup
from distutils.file_utl import copy_file
import platform
version = "0.1.0"
setup(name="riemann-sumd",
version=version,
description="Python agent for scheduling event generating processes and sending the results to Riemann",
author="Brian Hatfield",
author_email="bmhatfield@gmail.com",
url="https://github.com/bmhatfield/riemann-sumd",
package_dir={'': 'lib'},
py_modules=['event', 'loader', 'scheduler', 'sender', 'task'],
data_files=[('/etc/init/', ["init/ubuntu/sumd.conf"]),
('/etc/sumd', ['examples/etc/sumd/sumd.conf']),
('/etc/sumd/tasks.d', ['examples/etc/sumd/tasks.d/simple.task.example']),
('/etc/sumd/tags.d', ['examples/etc/sumd/tags.d/simple.tag.example'])],
scripts=["bin/sumd"]
)
copy_file('/lib/init/upstart-job', '/etc/init.d/sumd', link='sym') |
Make "new room" page an authenticated route | (function (angular) {
'use strict';
angular.module('birdyard.rooms')
.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/rooms/c/everything', {
controller: 'roomsController',
templateUrl: 'modules/rooms/views/rooms.html'
});
$routeProvider.when('/rooms/c/:category', {
controller: 'roomsController',
templateUrl: 'modules/rooms/views/rooms.html'
});
$routeProvider.whenAuthenticated('/rooms/new', {
controller: 'newroomController',
templateUrl: 'modules/rooms/views/newroom.html',
resolve: {
user: ['$Auth', function ($Auth) {
var $auth = $Auth;
return $auth.$waitForAuth();
}]
}
})
$routeProvider.when('/', {
redirectTo: '/rooms/c/everything'
});
}]);
})(angular); | (function (angular) {
'use strict';
angular.module('birdyard.rooms')
.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/rooms/c/everything', {
controller: 'roomsController',
templateUrl: 'modules/rooms/views/rooms.html'
});
$routeProvider.when('/rooms/c/:category', {
controller: 'roomsController',
templateUrl: 'modules/rooms/views/rooms.html'
});
$routeProvider.when('/rooms/new', {
controller: 'newroomController',
templateUrl: 'modules/rooms/views/newroom.html'
})
$routeProvider.when('/', {
redirectTo: '/rooms/c/everything'
});
}]);
})(angular); |
Improve error handling while parsing XML data
Fixes koraktor/steam-condenser#224 | <?php
/**
* This code is free software; you can redistribute it and/or modify it under
* the terms of the new BSD License.
*
* Copyright (c) 2009-2013, Sebastian Staudt
*
* @license http://www.opensource.org/licenses/bsd-license.php New BSD License
*/
require_once STEAM_CONDENSER_PATH . 'exceptions/SteamCondenserException.php';
/**
* This class is used to streamline access to XML-based data resources
*
* @author Sebastian Staudt
* @package steam-condenser
* @subpackage community
*/
abstract class XMLData {
/**
* Loads XML data from the given URL and returns it parsed into a
* <var>SimpleXMLElement</var>
*
* @param string $url The URL to load the data from
* @return SimpleXMLElement The parsed XML data
* @throws SteamCondenserException if the data cannot be parsed
*/
protected function getData($url) {
try {
return @new SimpleXMLElement($url, 0, true);
} catch (Exception $e) {
$errorMessage = "XML could not be parsed: " . $e->getMessage();
if ((float) phpversion() < 5.3) {
throw new SteamCondenserException($errorMessage, 0);
} else {
throw new SteamCondenserException($errorMessage, 0, $e);
}
}
}
}
| <?php
/**
* This code is free software; you can redistribute it and/or modify it under
* the terms of the new BSD License.
*
* Copyright (c) 2009-2011, Sebastian Staudt
*
* @license http://www.opensource.org/licenses/bsd-license.php New BSD License
*/
require_once STEAM_CONDENSER_PATH . 'exceptions/SteamCondenserException.php';
/**
* This class is used to streamline access to XML-based data resources
*
* @author Sebastian Staudt
* @package steam-condenser
* @subpackage community
*/
abstract class XMLData {
/**
* Loads XML data from the given URL and returns it parsed into a
* <var>SimpleXMLElement</var>
*
* @param string $url The URL to load the data from
* @return SimpleXMLElement The parsed XML data
* @throws SteamCondenserException if the data cannot be parsed
*/
protected function getData($url) {
try {
return @new SimpleXMLElement($url, 0, true);
} catch (Exception $e) {
throw new SteamCondenserException("XML could not be parsed", 0, $e);
}
}
}
|
: Create documentation of DataSource Settings
Task-Url: | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
dbs = ['FNOSDS', 'FNGCDDS', 'IBM_FORMS_DATA_SOURCE', 'activities', 'blogs', 'communities', 'dogear', 'files', 'forum', 'homepage', 'metrics', 'mobile', 'news', 'oauth provider', 'profiles', 'search', 'wikis'] # List of all databases to check
for db in dbs.splitlines():
t1 = ibmcnx.functions.getDSId( db )
AdminConfig.list( t1 ) | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
print AdminControl.getCell()
cell = "/Cell:" + AdminControl.getCell() + "/"
cellid = AdminConfig.getid( cell )
dbs = AdminConfig.list( 'DataSource', str(cellid) )
dbs = dbs.split('(')
print dbs
for db in dbs.splitlines():
t1 = ibmcnx.functions.getDSId( db )
AdminConfig.list( t1 ) |
Fix the decimal places limitation (at a758918). | var num;
var result;
var getIntegerDecimalPart = function(num) {
var re = /(\d+)(\.\d+)?/;
var found = num.match(re);
var decimal = found[2] ? found[2] : '';
return {integer: found[1], decimal: decimal};
};
var getCommaDelimitedIntegerPart = function(str_integer) {
var out = '';
while (str_integer.length > 0) {
var three_digits = str_integer.slice(-3); // get 3 digits
out = three_digits + out;
str_integer = str_integer.slice(0, -3); // remove 3 digits
if (str_integer.length >= 1) {
out = ',' + out;
}
}
return out;
}
// check args
if (process.argv.length < 3) { // sample value
num = Math.floor(Math.random() * 1000000000) + 1;
num = num.toString();
} else {
num = process.argv[2];
}
console.log('input: ' + num);
var obj_num = getIntegerDecimalPart(num);
result = obj_num.decimal;
result = getCommaDelimitedIntegerPart(obj_num.integer) + result;
console.log(result);
| var num;
var result;
var getIntegerDecimalPart = function(num) {
var integer = Math.floor(num);
var decimal = (num - integer).toFixed(5); // temporarily, 5 digits to appear after the decimal point
var str_decimal = ('0.00000' != decimal) ? decimal.slice(1) : '';
return {integer: integer.toString(), decimal: str_decimal};
};
var getCommaDelimitedIntegerPart = function(str_integer) {
var out = '';
while (str_integer.length > 0) {
var three_digits = str_integer.slice(-3); // get 3 digits
out = three_digits + out;
str_integer = str_integer.slice(0, -3); // remove 3 digits
if (str_integer.length >= 1) {
out = ',' + out;
}
}
return out;
}
// check args
if (process.argv.length < 3) { // sample value
num = Math.floor(Math.random() * 1000000000) + 1;
} else {
num = process.argv[2];
}
console.log('input: ' + num);
var obj_num = getIntegerDecimalPart(Number(num));
result = obj_num.decimal;
result = getCommaDelimitedIntegerPart(obj_num.integer) + result;
console.log(result);
|
Switch to .catch since there is no success handler | import Templates from "../Templates.js";
import AuthController from "../controllers/Auth.js";
import translations from "../nls/views/login.js";
var LoginView = {
"template": Templates.getView( "login" ),
data(){
return {
"username": "",
"password": "",
translations
};
},
"on": {
login(){
var data = this.get();
AuthController
.login( data.username, data.password )
.catch( () => {
/* eslint "no-console": "off", "no-debugger": "off", "vars-on-top": "off", "no-unused-vars": "off", "complexity": "off" */
console.log( "handle errors in form" );
} );
return false;
}
}
};
export default LoginView;
| import Templates from "../Templates.js";
import AuthController from "../controllers/Auth.js";
import translations from "../nls/views/login.js";
var LoginView = {
"template": Templates.getView( "login" ),
data(){
return {
"username": "",
"password": "",
translations
};
},
"on": {
login(){
var data = this.get();
AuthController
.login( data.username, data.password )
.then(
() => {},
() => {
/* eslint "no-console": "off", "no-debugger": "off", "vars-on-top": "off", "no-unused-vars": "off", "complexity": "off" */
console.log( "handle errors in form" );
}
);
return false;
}
}
};
export default LoginView;
|
Use 'config' instead of 'Config' when pulling application configuration | <?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ZfrCors\Factory;
use Interop\Container\ContainerInterface;
use ZfrCors\Options\CorsOptions;
/**
* CorsOptionsFactory
*
* @license MIT
* @author Florent Blaison <florent.blaison@gmail.com>
*/
class CorsOptionsFactory
{
/**
* {@inheritDoc}
*
* @return CorsOptions
*/
public function __invoke(ContainerInterface $container, $requestedName, $options = null)
{
/* @var $config array */
$config = $container->get('config');
return new CorsOptions($config['zfr_cors']);
}
}
| <?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ZfrCors\Factory;
use Interop\Container\ContainerInterface;
use ZfrCors\Options\CorsOptions;
/**
* CorsOptionsFactory
*
* @license MIT
* @author Florent Blaison <florent.blaison@gmail.com>
*/
class CorsOptionsFactory
{
/**
* {@inheritDoc}
*
* @return CorsOptions
*/
public function __invoke(ContainerInterface $container, $requestedName, $options = null)
{
/* @var $config array */
$config = $container->get('Config');
return new CorsOptions($config['zfr_cors']);
}
}
|
Remove unused fields during anonymization instead of storing null | 'use strict'
const Record = require('../schemas/Record')
const runUpdate = require('../utils/runUpdate')
const add = async (data) => {
return Record.create(data)
}
const update = async (id) => {
return runUpdate(Record, id)
}
const anonymize = async (clientId, ignoreId) => {
return Record.updateMany({
$and: [
{ clientId },
{
id: {
$ne: ignoreId
}
}
]
}, {
clientId: undefined,
siteLanguage: undefined,
screenWidth: undefined,
screenHeight: undefined,
screenColorDepth: undefined,
deviceName: undefined,
deviceManufacturer: undefined,
osName: undefined,
osVersion: undefined,
browserName: undefined,
browserVersion: undefined,
browserWidth: undefined,
browserHeight: undefined
})
}
const del = async (domainId) => {
return Record.deleteMany({
domainId
})
}
module.exports = {
add,
update,
anonymize,
del
} | 'use strict'
const Record = require('../schemas/Record')
const runUpdate = require('../utils/runUpdate')
const add = async (data) => {
return Record.create(data)
}
const update = async (id) => {
return runUpdate(Record, id)
}
const anonymize = async (clientId, ignoreId) => {
return Record.updateMany({
$and: [
{ clientId },
{
id: {
$ne: ignoreId
}
}
]
}, {
clientId: null,
siteLanguage: null,
screenWidth: null,
screenHeight: null,
screenColorDepth: null,
deviceName: null,
deviceManufacturer: null,
osName: null,
osVersion: null,
browserName: null,
browserVersion: null,
browserWidth: null,
browserHeight: null
})
}
const del = async (domainId) => {
return Record.deleteMany({
domainId
})
}
module.exports = {
add,
update,
anonymize,
del
} |
SDC-15068: Update label for kubernetes selection in Spark configuration
Change-Id: I4bf80c324fbad953519f459bd033b997153410af
Reviewed-on: https://review.streamsets.net/c/datacollector/+/33167
Reviewed-by: Madhukar Devaraju <d22477479bbf55ba62bd822f4112c80f292c7805@streamsets.com>
Reviewed-by: Santhosh Kumar <dcc54d3f6dcdfa9d2e6b02f6c7f69cc77b8d8c9a@streamsets.com> | /*
* Copyright 2019 StreamSets Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.streamsets.datacollector.config;
import com.streamsets.pipeline.api.GenerateResourceBundle;
import com.streamsets.pipeline.api.Label;
/**
* Enum for representing possible Cluster Type
*/
@GenerateResourceBundle
public enum SparkClusterType implements Label {
AZURE_HD_INSIGHT("Apache Spark for HDInsight"),
DATABRICKS("Databricks"),
EMR("EMR"),
DATAPROC("Dataproc"),
YARN("Hadoop YARN"),
KUBERNETES("Kubernetes Cluster"),
LOCAL("None (local)"),
STANDALONE_SPARK_CLUSTER("Spark Standalone Cluster"),
SQL_SERVER_BIG_DATA_CLUSTER("SQL Server 2019 Big Data Cluster"),
;
private final String label;
SparkClusterType(String label) {
this.label = label;
}
@Override
public String getLabel() {
return label;
}
}
| /*
* Copyright 2019 StreamSets Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.streamsets.datacollector.config;
import com.streamsets.pipeline.api.GenerateResourceBundle;
import com.streamsets.pipeline.api.Label;
/**
* Enum for representing possible Cluster Type
*/
@GenerateResourceBundle
public enum SparkClusterType implements Label {
AZURE_HD_INSIGHT("Apache Spark for HDInsight"),
DATABRICKS("Databricks"),
EMR("EMR"),
DATAPROC("Dataproc"),
YARN("Hadoop YARN"),
KUBERNETES("Kubernetes Cluster (advanced users only)"),
LOCAL("None (local)"),
STANDALONE_SPARK_CLUSTER("Spark Standalone Cluster"),
SQL_SERVER_BIG_DATA_CLUSTER("SQL Server 2019 Big Data Cluster"),
;
private final String label;
SparkClusterType(String label) {
this.label = label;
}
@Override
public String getLabel() {
return label;
}
}
|
Refactor listToArray to work with list parameters of dynamic sizes | // Write a function arrayToList that builds up a data structure like the previous one when given [1, 2, 3] as argument, and write a listToArray function that produces an array from a list. Also write the helper functions prepend, which takes an element and a list and creates a new list that adds the element to the front of the input list, and nth, which takes a list and a number and returns the element at the given position in the list, or undefined when there is no such element.
function arrayToList(array) {
const arrayLength = array.length;
let list = null;
for (let i = array.length - 1; i >= 0; i-- ) {
list = {
value: array[i],
rest: list
};
}
return list;
}
const theArray = [1, 2, 3, 4, 5, 6, 7, 8];
console.log(arrayToList(theArray));
function listToArray(list) {
let array = [];
for (let currentNode = list; currentNode; currentNode = currentNode.rest) {
array.push(currentNode.value);
}
return array;
}
const theList = arrayToList([1, 2, 3, 4, 5, 6, 7, 8]);
console.log(listToArray(theList));
// write helper function 'prepend', which takes an element and a list and creates a new list that adds the element to the front of the input list
function prepend(element, list) {
let newList;
// do some stuff here
return newList;
} | // Write a function arrayToList that builds up a data structure like the previous one when given [1, 2, 3] as argument, and write a listToArray function that produces an array from a list. Also write the helper functions prepend, which takes an element and a list and creates a new list that adds the element to the front of the input list, and nth, which takes a list and a number and returns the element at the given position in the list, or undefined when there is no such element.
function arrayToList(array) {
const arrayLength = array.length;
let list = null;
for (let i = array.length - 1; i >= 0; i-- ) {
list = {
value: array[i],
rest: list
};
}
return list;
}
const theArray = [1, 2, 3, 4, 5, 6, 7, 8];
console.log(arrayToList(theArray));
function listToArray(list) {
console.log(list);
const array = [
list.value,
list.rest.value,
list.rest.rest.value
];
return array;
}
// const theList = arrayToList([1, 2, 3]);
// console.log(listToArray(theList));
// write helper function 'prepend', which takes an element and a list and creates a new list that adds the element to the front of the input list
function prepend(element, list) {
let newList;
// do some stuff here
return newList;
} |
Change default base url to be next | var baseUrl = process.env.OS_BASE_URL || 'https://next.openspending.org';
var osExplorerSearchHost = process.env.OS_EXPLORER_SEARCH_HOST || baseUrl;
var searchUrl = process.env.OS_SEARCH_URL || osExplorerSearchHost + '/search/package';
var authUrl = process.env.OS_EXPLORER_AUTH_HOST || baseUrl;
var url = require('url');
var assert = require('assert');
function validateUrl(_url) {
var parsedUrl = url.parse(_url);
assert(parsedUrl.protocol, 'You need to define the URL protocol (' + _url + ')');
assert(!_url.endsWith('/'), 'The URL should not end with a slash (' + _url + ')');
return _url;
}
module.exports = {
baseUrl: validateUrl(baseUrl),
searchUrl: validateUrl(searchUrl),
authUrl: validateUrl(authUrl),
snippets: {
ga: process.env.OS_SNIPPETS_GA
}
};
| var baseUrl = process.env.OS_BASE_URL || 'https://staging.openspending.org';
var osExplorerSearchHost = process.env.OS_EXPLORER_SEARCH_HOST || baseUrl;
var searchUrl = process.env.OS_SEARCH_URL || osExplorerSearchHost + '/search/package';
var authUrl = process.env.OS_EXPLORER_AUTH_HOST || baseUrl;
var url = require('url');
var assert = require('assert');
function validateUrl(_url) {
var parsedUrl = url.parse(_url);
assert(parsedUrl.protocol, 'You need to define the URL protocol (' + _url + ')');
assert(!_url.endsWith('/'), 'The URL should not end with a slash (' + _url + ')');
return _url;
}
module.exports = {
baseUrl: validateUrl(baseUrl),
searchUrl: validateUrl(searchUrl),
authUrl: validateUrl(authUrl),
snippets: {
ga: process.env.OS_SNIPPETS_GA
}
};
|
Fix on Loader (missing "/") | package main
import (
"fmt"
"io/ioutil"
)
// Reader defines an interface that implements the
// methods to read files from some resource and translate
// it to File instances
type Reader interface {
Read(path string) ([]File, error)
}
// DiskReader defines a implementation of the
// Reader interface to read files from Disk
type DiskReader struct{}
// Read reads the files from disk and translate it
// to the internal File structure
func (dr DiskReader) Read(path string) ([]File, error) {
var files []File
memFiles, err := ioutil.ReadDir(path)
if err != nil {
return nil, err
}
for _, memFile := range memFiles {
if memFile.IsDir() {
continue
}
content, err := ioutil.ReadFile(fmt.Sprintf("%s/%s", path, memFile.Name()))
if err != nil {
return nil, err
}
files = append(files, File{
FileInfo: memFile,
Path: path,
Content: string(content),
})
}
return files, nil
}
| package main
import (
"io/ioutil"
)
// Reader defines an interface that implements the
// methods to read files from some resource and translate
// it to File instances
type Reader interface {
Read(path string) ([]File, error)
}
// DiskReader defines a implementation of the
// Reader interface to read files from Disk
type DiskReader struct{}
// Read reads the files from disk and translate it
// to the internal File structure
func (dr DiskReader) Read(path string) ([]File, error) {
var files []File
memFiles, err := ioutil.ReadDir(path)
if err != nil {
return nil, err
}
for _, memFile := range memFiles {
if memFile.IsDir() {
continue
}
content, err := ioutil.ReadFile(path + memFile.Name())
if err != nil {
return nil, err
}
files = append(files, File{
FileInfo: memFile,
Path: path,
Content: string(content),
})
}
return files, nil
}
|
Fix extraneous self parameter in staticmethod | import subprocess
import os
from .settings import Settings
class Command():
def __init__(self, command):
self.__command = command
self.__startup_info = None
self.__shell = False
if os.name == 'nt':
self.__startup_info = subprocess.STARTUPINFO()
self.__startup_info.dwFlags |= subprocess.STARTF_USESHOWWINDOW
self.__startup_info.wShowWindow = subprocess.SW_HIDE
self.__shell = True
@staticmethod
def env():
path = os.pathsep.join(Settings.paths())
env = os.environ.copy()
env['PATH'] = path + os.pathsep + env['PATH']
return env
def run(self, input):
return subprocess.Popen(
self.__command,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
startupinfo=self.__startup_info,
shell=self.__shell,
env=self.env(),
universal_newlines=True).communicate(input=input)
| import subprocess
import os
from .settings import Settings
class Command():
def __init__(self, command):
self.__command = command
self.__startup_info = None
self.__shell = False
if os.name == 'nt':
self.__startup_info = subprocess.STARTUPINFO()
self.__startup_info.dwFlags |= subprocess.STARTF_USESHOWWINDOW
self.__startup_info.wShowWindow = subprocess.SW_HIDE
self.__shell = True
@staticmethod
def env(self):
path = os.pathsep.join(Settings.paths())
env = os.environ.copy()
env['PATH'] = path + os.pathsep + env['PATH']
return env
def run(self, input):
return subprocess.Popen(
self.__command,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
startupinfo=self.__startup_info,
shell=self.__shell,
env=self.env(),
universal_newlines=True).communicate(input=input)
|
change: Rename release directory name to Out | /**
* Copyright (c) Ajay Sreedhar. All rights reserved.
*
* Licensed under the MIT License.
* Please see LICENSE file located in the project root for more information.
*/
'use strict';
const releaseConfig = {
appId: 'com.kongdash',
productName: 'KongDash',
copyright: 'Copyright (c) 2022 Ajay Sreedhar',
asar: true,
compression: 'normal',
removePackageScripts: true,
nodeGypRebuild: false,
buildDependenciesFromSource: false,
files: [
{
from: 'out/platform',
to: 'platform'
},
{
from: 'out/workbench',
to: 'workbench'
},
'package.json'
],
directories: {
output: 'dist'
},
extraResources: [
{
from: 'resources/themes',
to: 'themes'
}
],
extraMetadata: {
main: 'platform/main.js'
}
};
module.exports = {releaseConfig};
| /**
* Copyright (c) Ajay Sreedhar. All rights reserved.
*
* Licensed under the MIT License.
* Please see LICENSE file located in the project root for more information.
*/
'use strict';
const releaseConfig = {
appId: 'com.kongdash',
productName: 'KongDash',
copyright: 'Copyright (c) 2022 Ajay Sreedhar',
asar: true,
compression: 'normal',
removePackageScripts: true,
nodeGypRebuild: false,
buildDependenciesFromSource: false,
files: [
{
from: 'dist/platform',
to: 'platform'
},
{
from: 'dist/workbench',
to: 'workbench'
},
'package.json'
],
directories: {
output: 'release'
},
extraResources: [
{
from: 'resources/themes',
to: 'themes'
}
],
extraMetadata: {
main: 'platform/main.js'
}
};
module.exports = {releaseConfig};
|
Add the possibility to force the used transport using an env var | <?php
/*
* This file is part of the SensioLabs Security Checker.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SensioLabs\Security\Crawler;
/**
* @internal
*/
class DefaultCrawler implements CrawlerInterface
{
private $crawler;
public function __construct()
{
$this->crawler = ('stream' === getenv('SENSIOLABS_SECURITY_CHECKER_TRANSPORT') || !function_exists('curl_init')) ? new FileGetContentsCrawler() : new CurlCrawler();
}
/**
* {@inheritdoc}
*/
public function check($lock)
{
return $this->crawler->check($lock);
}
/**
* {@inheritdoc}
*/
public function setTimeout($timeout)
{
$this->crawler->setTimeout($timeout);
}
/**
* {@inheritdoc}
*/
public function setEndPoint($endPoint)
{
$this->crawler->setEndPoint($endPoint);
}
}
| <?php
/*
* This file is part of the SensioLabs Security Checker.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SensioLabs\Security\Crawler;
/**
* @internal
*/
class DefaultCrawler implements CrawlerInterface
{
private $crawler;
public function __construct()
{
$this->crawler = function_exists('curl_init') ? new CurlCrawler() : new FileGetContentsCrawler();
}
/**
* {@inheritdoc}
*/
public function check($lock)
{
return $this->crawler->check($lock);
}
/**
* {@inheritdoc}
*/
public function setTimeout($timeout)
{
$this->crawler->setTimeout($timeout);
}
/**
* {@inheritdoc}
*/
public function setEndPoint($endPoint)
{
$this->crawler->setEndPoint($endPoint);
}
}
|
Change data param to json | # -*- coding: utf-8 -*-
import requests
from dbaas_services.analyzing.exceptions import ServiceNotAvailable
class AnalyzeService(object):
def __init__(self, endpoint, healh_check_route, healh_check_string):
self.endpoint = endpoint
self.healh_check_route = healh_check_route
self.healh_check_string = healh_check_string
if self.__service_is_not__available():
raise ServiceNotAvailable("Service not Working")
def __service_is_not__available(self,):
healh_check_endpoint = self.endpoint + self.healh_check_route
response = requests.get(healh_check_endpoint)
return not response.content == self.healh_check_string
def run(self, **kwargs):
response = requests.post(self.endpoint, json=kwargs)
return response.json()
| # -*- coding: utf-8 -*-
import requests
from dbaas_services.analyzing.exceptions import ServiceNotAvailable
class AnalyzeService(object):
def __init__(self, endpoint, healh_check_route, healh_check_string):
self.endpoint = endpoint
self.healh_check_route = healh_check_route
self.healh_check_string = healh_check_string
if self.__service_is_not__available():
raise ServiceNotAvailable("Service not Working")
def __service_is_not__available(self,):
healh_check_endpoint = self.endpoint + self.healh_check_route
response = requests.get(healh_check_endpoint)
return not response.content == self.healh_check_string
def run(self, **kwargs):
response = requests.post(self.endpoint, data=kwargs)
return response.json()
|
Set content type for API response | <?PHP
namespace Firelit;
class ApiResponse extends Response {
protected $response = array();
protected $responseSent = false;
protected $responseFormat = 'JSON';
public function __construct($responseFormat = 'JSON', $ob = true, $charset = "UTF-8") {
parent::__construct($ob, $charset);
if ($responseFormat == 'JSON')
$this->contentType('application/json');
$this->responseFormat = strtoupper($responseFormat);
}
public function setTemplate($template) {
$this->response = array_merge($this->response, $template);
}
public function set($response) {
$this->response = array_merge($this->response, $response);
}
public function respond($response = array(), $end = true) {
$this->set($response);
if ($this->outputBuffering) {
$this->cleanBuffer();
}
if ($this->responseFormat == 'JSON') {
echo json_encode($this->response);
} else {
throw new Exception('Invalid response format: '. $this->responseFormat);
}
if ($this->outputBuffering) {
$this->flushBuffer();
}
$this->responseSent = true;
if ($end) exit;
}
public function hasResponded() {
return $this->responseSent;
}
public function __destruct() {
if (!$this->hasResponded()) {
$this->respond(array(), false);
}
}
} | <?PHP
namespace Firelit;
class ApiResponse extends Response {
protected $response = array();
protected $responseSent = false;
protected $responseFormat = 'JSON';
public function __construct($responseFormat = 'JSON', $ob = true, $charset = "UTF-8") {
parent::__construct($ob, $charset);
$this->responseFormat = strtoupper($responseFormat);
}
public function setTemplate($template) {
$this->response = array_merge($this->response, $template);
}
public function set($response) {
$this->response = array_merge($this->response, $response);
}
public function respond($response = array(), $end = true) {
$this->set($response);
if ($this->outputBuffering) {
$this->cleanBuffer();
}
if ($this->responseFormat == 'JSON') {
echo json_encode($this->response);
} else {
throw new Exception('Invalid response format: '. $this->responseFormat);
}
if ($this->outputBuffering) {
$this->flushBuffer();
}
$this->responseSent = true;
if ($end) exit;
}
public function hasResponded() {
return $this->responseSent;
}
public function __destruct() {
if (!$this->hasResponded()) {
$this->respond(array(), false);
}
}
} |
Python: Add test we don't handle for `py/request-without-cert-validation` | import requests
#Simple cases
requests.get('https://semmle.com', verify=True) # GOOD
requests.get('https://semmle.com', verify=False) # BAD
requests.post('https://semmle.com', verify=True) # GOOD
requests.post('https://semmle.com', verify=False) # BAD
# Simple flow
put = requests.put
put('https://semmle.com', verify="/path/to/cert/") # GOOD
put('https://semmle.com', verify=False) # BAD
#Other flow
delete = requests.delete
def req1(verify=False):
delete('https://semmle.com', verify) # BAD
if verify:
delete('https://semmle.com', verify) # GOOD
if not verify:
return
delete('https://semmle.com', verify) # GOOD
patch = requests.patch
def req2(verify):
patch('https://semmle.com', verify=verify) # BAD (from line 30)
req2(False) # BAD (at line 28)
req2("/path/to/cert/") # GOOD
#Falsey value
requests.post('https://semmle.com', verify=0) # BAD
# requests treat `None` as default value, which means it is turned on
requests.get('https://semmle.com') # OK
requests.get('https://semmle.com', verify=None) # OK
s = requests.Session()
s.get("url", verify=False) # BAD
| import requests
#Simple cases
requests.get('https://semmle.com', verify=True) # GOOD
requests.get('https://semmle.com', verify=False) # BAD
requests.post('https://semmle.com', verify=True) # GOOD
requests.post('https://semmle.com', verify=False) # BAD
# Simple flow
put = requests.put
put('https://semmle.com', verify="/path/to/cert/") # GOOD
put('https://semmle.com', verify=False) # BAD
#Other flow
delete = requests.delete
def req1(verify=False):
delete('https://semmle.com', verify) # BAD
if verify:
delete('https://semmle.com', verify) # GOOD
if not verify:
return
delete('https://semmle.com', verify) # GOOD
patch = requests.patch
def req2(verify):
patch('https://semmle.com', verify=verify) # BAD (from line 30)
req2(False) # BAD (at line 28)
req2("/path/to/cert/") # GOOD
#Falsey value
requests.post('https://semmle.com', verify=0) # BAD
# requests treat `None` as default value, which means it is turned on
requests.get('https://semmle.com') # OK
requests.get('https://semmle.com', verify=None) # OK
|
Remove no longer needed import check | """Basic set of tests to ensure entire code base is importable"""
import pytest
def test_importable():
"""Simple smoketest to ensure all isort modules are importable"""
import isort
import isort._future
import isort._future._dataclasses
import isort._version
import isort.api
import isort.comments
import isort.exceptions
import isort.finders
import isort.format
import isort.hooks
import isort.isort
import isort.logo
import isort.main
import isort.output
import isort.parse
import isort.profiles
import isort.pylama_isort
import isort.sections
import isort.settings
import isort.setuptools_commands
import isort.sorting
import isort.stdlibs
import isort.stdlibs.all
import isort.stdlibs.py2
import isort.stdlibs.py3
import isort.stdlibs.py27
import isort.stdlibs.py35
import isort.stdlibs.py36
import isort.stdlibs.py37
import isort.utils
import isort.wrap
import isort.wrap_modes
with pytest.raises(SystemExit):
import isort.__main__
| """Basic set of tests to ensure entire code base is importable"""
import pytest
def test_importable():
"""Simple smoketest to ensure all isort modules are importable"""
import isort
import isort._future
import isort._future._dataclasses
import isort._version
import isort.api
import isort.comments
import isort.compat
import isort.exceptions
import isort.finders
import isort.format
import isort.hooks
import isort.isort
import isort.logo
import isort.main
import isort.output
import isort.parse
import isort.profiles
import isort.pylama_isort
import isort.sections
import isort.settings
import isort.setuptools_commands
import isort.sorting
import isort.stdlibs
import isort.stdlibs.all
import isort.stdlibs.py2
import isort.stdlibs.py3
import isort.stdlibs.py27
import isort.stdlibs.py35
import isort.stdlibs.py36
import isort.stdlibs.py37
import isort.utils
import isort.wrap
import isort.wrap_modes
with pytest.raises(SystemExit):
import isort.__main__
|
[Genomics]: Use the utility for removing file extensions instead of doing this manually. | package com.github.sparkcaller.preprocessing;
import com.github.sparkcaller.Utils;
import org.apache.spark.api.java.function.Function;
import picard.sam.SortSam;
import java.io.File;
import java.util.ArrayList;
public class SamToSortedBam implements Function<File, File> {
public File call(File file) throws Exception {
String newFileName = Utils.removeExtenstion(file.getPath(), "sam") + ".bam";
File outputSamFile = new File(newFileName);
ArrayList<String> sorterArgs = new ArrayList<String>();
sorterArgs.add("INPUT=");
sorterArgs.add(file.getPath());
sorterArgs.add("OUTPUT=");
sorterArgs.add(outputSamFile.getPath());
sorterArgs.add("SORT_ORDER=coordinate");
SortSam samSorter = new SortSam();
samSorter.instanceMain(sorterArgs.toArray(new String[0]));
return outputSamFile;
}
}
| package com.github.sparkcaller.preprocessing;
import org.apache.spark.api.java.function.Function;
import picard.sam.SortSam;
import java.io.File;
import java.util.ArrayList;
public class SamToSortedBam implements Function<File, File> {
public File call(File file) throws Exception {
final String ext = "sam";
String newFileName = file.getPath().substring(0, file.getPath().length() - ext.length()) + "bam";
File outputSamFile = new File(newFileName);
ArrayList<String> sorterArgs = new ArrayList<String>();
sorterArgs.add("INPUT=");
sorterArgs.add(file.getPath());
sorterArgs.add("OUTPUT=");
sorterArgs.add(outputSamFile.getPath());
sorterArgs.add("SORT_ORDER=coordinate");
SortSam samSorter = new SortSam();
samSorter.instanceMain(sorterArgs.toArray(new String[0]));
return outputSamFile;
}
}
|
Add angular brush mode to test | var vows = require('vows'),
assert = require('assert'),
events = require('events'),
load = require('./load'),
suite = vows.describe('brushModes');
function d3Parcoords() {
var promise = new(events.EventEmitter);
load(function(d3) {
promise.emit('success', d3.parcoords());
});
return promise;
}
suite.addBatch({
'd3.parcoords': {
'has by default': {
topic: d3Parcoords(),
'four brush modes': function(pc) {
assert.strictEqual(pc.brushModes().length, 4);
},
'the brush mode "None"': function(pc) {
assert.notStrictEqual(pc.brushModes().indexOf("None"), -1);
},
'the brush mode "1D-axes"': function(pc) {
assert.notStrictEqual(pc.brushModes().indexOf("1D-axes"), -1);
},
'the brush mode "2D-strums"': function(pc) {
assert.notStrictEqual(pc.brushModes().indexOf("2D-strums"), -1);
},
'the brush mode "angular"': function(pc) {
assert.notStrictEqual(pc.brushModes().indexOf("angular"), -1);
}
},
}
});
suite.export(module);
| var vows = require('vows'),
assert = require('assert'),
events = require('events'),
load = require('./load'),
suite = vows.describe('brushModes');
function d3Parcoords() {
var promise = new(events.EventEmitter);
load(function(d3) {
promise.emit('success', d3.parcoords());
});
return promise;
}
suite.addBatch({
'd3.parcoords': {
'has by default': {
topic: d3Parcoords(),
'three brush modes': function(pc) {
assert.strictEqual(pc.brushModes().length, 3);
},
'the brush mode "None"': function(pc) {
assert.notStrictEqual(pc.brushModes().indexOf("None"), -1);
},
'the brush mode "1D-axes"': function(pc) {
assert.notStrictEqual(pc.brushModes().indexOf("1D-axes"), -1);
},
'the brush mode "2D-strums"': function(pc) {
assert.notStrictEqual(pc.brushModes().indexOf("2D-strums"), -1);
}
},
}
});
suite.export(module);
|
Remove zDepth from Paper element | import React from 'react'
import AppBar from 'material-ui/lib/app-bar'
import Paper from 'material-ui/lib/paper'
import Theme from '../theme'
class App extends React.Component {
getChildContext () {
return {
muiTheme: Theme
}
}
render () {
const style = {
maxWidth: 800,
minWidth: 300,
minHeight: 300
}
return (
<Paper style={style}>
<AppBar
title='Tasty Todos'
showMenuIconButton={false}
/>
</Paper>
)
}
}
App.childContextTypes = {
muiTheme: React.PropTypes.object
}
export default App
| import React from 'react'
import AppBar from 'material-ui/lib/app-bar'
import Paper from 'material-ui/lib/paper'
import Theme from '../theme'
class App extends React.Component {
getChildContext () {
return {
muiTheme: Theme
}
}
render () {
const style = {
maxWidth: 800,
minWidth: 300,
minHeight: 300
}
return (
<Paper style={style} zDepth={1}>
<AppBar
title='Tasty Todos'
showMenuIconButton={false}
/>
</Paper>
)
}
}
App.childContextTypes = {
muiTheme: React.PropTypes.object
}
export default App
|
Call artisan dump-autoload when run admin:install command | <?php namespace Pingpong\Admin\Console;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
class AdminInstallCommand extends Command {
/**
* The console command name.
*
* @var string
*/
protected $name = 'admin:install';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Install the admin package.';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function fire()
{
$this->call('admin:migration');
$this->call('migrate:publish', ['package' => 'pingpong/trusty']);
$this->call('migrate');
$this->call('db:seed', ['--class' => 'Pingpong\\Admin\\Seeders\\AdminDatabaseSeeder']);
$this->call('config:publish', ['package' => 'pingpong/admin']);
$this->call('asset:publish', ['package' => 'pingpong/admin']);
$this->call('dump-autoload');
}
}
| <?php namespace Pingpong\Admin\Console;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
class AdminInstallCommand extends Command {
/**
* The console command name.
*
* @var string
*/
protected $name = 'admin:install';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Install the admin package.';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function fire()
{
$this->call('admin:migration');
$this->call('migrate:publish', ['package' => 'pingpong/trusty']);
$this->call('migrate');
$this->call('db:seed', ['--class' => 'Pingpong\\Admin\\Seeders\\AdminDatabaseSeeder']);
$this->call('config:publish', ['package' => 'pingpong/admin']);
$this->call('asset:publish', ['package' => 'pingpong/admin']);
}
}
|
Update wording for a V2 context | // Package acctest provides the ability to use the binary test driver. The binary
// test driver allows you to run your acceptance tests with a binary of Terraform.
// This is currently the only mechanism for driving tests. It provides a realistic testing
// experience and matrix testing against multiple versions of Terraform CLI,
// as long as they are >= 0.12.0
//
// The driver must be enabled by initialising the test helper in your TestMain
// function in all provider packages that run acceptance tests. Most providers have only
// one package.
//
// After importing this package, you must define a TestMain and have the following:
//
// func TestMain(m *testing.M) {
// acctest.UseBinaryDriver("provider_name", Provider)
// resource.TestMain(m)
// }
//
// Where `Provider` is the function that returns the instance of a configured `*schema.Provider`
// Some providers already have a TestMain defined, usually for the purpose of enabling test
// sweepers. These additional occurrences should be removed.
//
// It is no longer necessary to import other Terraform providers as Go modules: these
// imports should be removed.
package acctest
| // Package acctest provides the ability to opt in to the new binary test driver. The binary
// test driver allows you to run your acceptance tests with a binary of Terraform instead of
// an emulated version packaged inside the SDK. This allows for a number of important
// enhancements, but most notably a more realistic testing experience and matrix testing
// against multiple versions of Terraform CLI. This also allows the SDK to be completely
// separated, at a dependency level, from the Terraform CLI, as long as it is >= 0.12.0
//
// The new test driver must be enabled by initialising the test helper in your TestMain
// function in all provider packages that run acceptance tests. Most providers have only
// one package.
//
// In v2 of the SDK, the binary test driver will be mandatory.
//
// After importing this package, you can add code similar to the following:
//
// func TestMain(m *testing.M) {
// acctest.UseBinaryDriver("provider_name", Provider)
// resource.TestMain(m)
// }
//
// Where `Provider` is the function that returns the instance of a configured `terraform.ResourceProvider`
// Some providers already have a TestMain defined, usually for the purpose of enabling test
// sweepers. These additional occurrences should be removed.
//
// Initialising the binary test helper using UseBinaryDriver causes all tests to be run using
// the new binary driver. Until SDK v2, the DisableBinaryDriver boolean property can be used
// to use the legacy test driver for an individual TestCase.
//
// It is no longer necessary to import other Terraform providers as Go modules: these
// imports should be removed.
package acctest
|
Hide popups if no error was found | 'use strict';
const form = $('form[action="/create/challenge"]');
form.submit(event => {
event.preventDefault();
let isValid = true;
const title = form.find('input[name="title"]').val();
if (!title) {
isValid = false;
ErrorPopup.create(form, 0, i18n.noTitle);
} else if (title && title.length > 40) {
isValid = false;
ErrorPopup.create(form, 0, i18n.titleLong);
} else {
ErrorPopup.remove(form, 0);
}
const desc = form.find('textarea[name="desc"]').val();
if (!desc) {
isValid = false;
ErrorPopup.create(form, 1, i18n.noDesc);
} else if (desc && desc.length > 250) {
isValid = false;
ErrorPopup.create(form, 1, i18n.descLong);
} else {
ErrorPopup.remove(form, 1);
}
if (!isValid) return false;
$.post($(form).attr('action'), $(form).serialize(), json => {
location.assign('/');
}, 'json').fail(response => {
ErrorPopup.createFull(form, i18n.serverValidation);
});
return false;
});
| 'use strict';
const form = $('form[action="/create/challenge"]');
form.submit(event => {
event.preventDefault();
let isValid = true;
const title = form.find('input[name="title"]').val();
if (!title) {
isValid = false;
ErrorPopup.create(form, 0, i18n.noTitle);
} else if (title && title.length > 40) {
isValid = false;
ErrorPopup.create(form, 0, i18n.titleLong);
}
const desc = form.find('textarea[name="desc"]').val();
if (!desc) {
isValid = false;
ErrorPopup.create(form, 1, i18n.noDesc);
} else if (desc && desc.length > 250) {
isValid = false;
ErrorPopup.create(form, 1, i18n.descLong);
}
if (!isValid) return false;
$.post($(form).attr('action'), $(form).serialize(), json => {
location.assign('/');
}, 'json').fail(response => {
ErrorPopup.createFull(form, i18n.serverValidation);
});
return false;
});
|
Change file name for output for no assembler given | """Null object for the assemblers."""
from os.path import join
import lib.db as db
from lib.assemblers.base import BaseAssembler
class NoneAssembler(BaseAssembler):
"""Null object for the assemblers."""
def __init__(self, args, db_conn):
"""Build the assembler."""
super().__init__(args, db_conn)
self.steps = []
self.blast_only = True # Used to short-circuit the assembler
def write_final_output(self, blast_db, query):
"""Output this file if we are not assembling the contigs."""
prefix = self.final_output_prefix(blast_db, query)
file_name = '{}.fasta'.format(prefix)
with open(file_name, 'w') as output_file:
for row in db.get_sra_blast_hits(self.state['db_conn'], 1):
output_file.write('>{}{}\n'.format(
row['seq_name'], row['seq_end']))
output_file.write('{}\n'.format(row['seq']))
| """Null object for the assemblers."""
from os.path import join
import lib.db as db
from lib.assemblers.base import BaseAssembler
class NoneAssembler(BaseAssembler):
"""Null object for the assemblers."""
def __init__(self, args, db_conn):
"""Build the assembler."""
super().__init__(args, db_conn)
self.steps = []
self.blast_only = True # Used to short-circuit the assembler
def write_final_output(self, blast_db, query):
"""Output this file if we are not assembling the contigs."""
prefix = self.final_output_prefix(blast_db, query)
file_name = join(prefix, 'blast_only.fasta')
with open(file_name, 'w') as output_file:
for row in db.get_sra_blast_hits(self.state['db_conn'], 1):
output_file.write('>{}{}\n'.format(
row['seq_name'], row['seq_end']))
output_file.write('{}\n'.format(row['seq']))
|
Document the xyplot function and support data dict | #! /usr/bin/env python2.7
"""Avoid some boilerplate rpy2 usage code with helpers.
Mostly I wrote this so that I can use xyplot without having
to remember a lot of details.
"""
import click
from rpy2.robjects import DataFrame, Formula, globalenv
from rpy2.robjects.packages import importr
grdevices = importr('grDevices')
lattice = importr('lattice')
rprint = globalenv.get("print")
def xyplot(formula, data, **kwargs):
"""Call lattice's `xyplot` with the given `formula` and `data`.
You can supply `formula` as a string or rpy2 `Formula`.
You can supply `data` as a dict or rpy2 `DataFrame`.
"""
if not isinstance(data, DataFrame):
data = DataFrame(data)
if not isinstance(formula, Formula):
formula = Formula(formula)
plot = lattice.xyplot(
formula, data, **kwargs)
rprint(plot)
@click.command()
def main():
import numpy as np
from rpy2.robjects import numpy2ri
numpy2ri.activate()
x = np.random.random_integers(0, 100, 100)
x.sort()
y = np.square(x)
xyplot('y ~ x', DataFrame({'x': x, 'y': y}))
raw_input('Hit enter to exit.')
grdevices.dev_off()
if __name__ == '__main__':
main()
| #! /usr/bin/env python2.7
"""Avoid some boilerplate rpy2 usage code with helpers.
Mostly I wrote this so that I can use xyplot without having
to remember a lot of details.
"""
import click
from rpy2.robjects import DataFrame, Formula, globalenv
from rpy2.robjects.packages import importr
grdevices = importr('grDevices')
lattice = importr('lattice')
rprint = globalenv.get("print")
def xyplot(formula, data, **kwargs):
if not isinstance(formula, Formula):
formula = Formula(formula)
plot = lattice.xyplot(
formula, data, **kwargs)
rprint(plot)
@click.command()
def main():
import numpy as np
from rpy2.robjects import numpy2ri
numpy2ri.activate()
x = np.random.random_integers(0, 100, 100)
x.sort()
y = np.square(x)
xyplot('y ~ x', DataFrame({'x': x, 'y': y}))
raw_input('Hit enter to exit.')
grdevices.dev_off()
if __name__ == '__main__':
main()
|
Remove unnecessary mkdirp before moving a file, since fs-plus handles it | 'use babel';
import { isFileSync, moveSync, statSync } from 'fs-plus';
/*
code pulled from:
https://github.com/atom/tree-view/blob/492e344149bd42755d90765607743173bb9b7c0a/lib/move-dialog.coffee
*/
function isNewPathValid(previousPath, nextPath) {
if (!isFileSync(nextPath)) return true;
/*
New path exists so check if it points to the same file as the initial
path to see if the case of the file name is being changed on a on a
case insensitive filesystem.
*/
const oldStat = statSync(previousPath);
const newStat = statSync(nextPath);
const haveSamePath = previousPath.toLowerCase() === nextPath.toLowerCase();
const haveSameDev = oldStat.dev === newStat.dev;
const haveSameIno = oldStat.ino === newStat.ino;
return !(haveSamePath && haveSameDev && haveSameIno);
}
export default function renameFile(previousPath, nextPath) {
if (!isNewPathValid(previousPath, nextPath)) return false;
try {
moveSync(previousPath, nextPath);
return true;
} catch (e) {
atom.notifications.addError(e.message, {
dismissable: true,
});
return false;
}
}
| 'use babel';
import { dirname } from 'path';
import { existsSync, isFileSync, makeTreeSync, moveSync, statSync } from 'fs-plus';
/*
code pulled from:
https://github.com/atom/tree-view/blob/492e344149bd42755d90765607743173bb9b7c0a/lib/move-dialog.coffee
*/
function isNewPathValid(previousPath, nextPath) {
if (!isFileSync(nextPath)) return true;
/*
New path exists so check if it points to the same file as the initial
path to see if the case of the file name is being changed on a on a
case insensitive filesystem.
*/
const oldStat = statSync(previousPath);
const newStat = statSync(nextPath);
const haveSamePath = previousPath.toLowerCase() === nextPath.toLowerCase();
const haveSameDev = oldStat.dev === newStat.dev;
const haveSameIno = oldStat.ino === newStat.ino;
return !(haveSamePath && haveSameDev && haveSameIno);
}
export default function renameFile(previousPath, nextPath) {
if (!isNewPathValid(previousPath, nextPath)) return false;
const directoryPath = dirname(nextPath);
try {
if (!existsSync(directoryPath)) {
makeTreeSync(directoryPath);
}
moveSync(previousPath, nextPath);
return true;
} catch (e) {
return false;
}
}
|
Fix a typo in a comment | <?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Models\Bookmark;
use Illuminate\View\View;
class BookmarksController extends Controller
{
/**
* Show the most recent bookmarks.
*
* @return View
*/
public function index(): View
{
$bookmarks = Bookmark::latest()->with('tags')->withCount('tags')->paginate(10);
return view('bookmarks.index', compact('bookmarks'));
}
/**
* Show a single bookmark.
*
* @param Bookmark $bookmark
* @return View
*/
public function show(Bookmark $bookmark): View
{
$bookmark->loadMissing('tags');
return view('bookmarks.show', compact('bookmark'));
}
/**
* Show bookmarks tagged with a specific tag.
*
* @param string $tag
* @return View
*/
public function tagged(string $tag): View
{
$bookmarks = Bookmark::whereHas('tags', function ($query) use ($tag) {
$query->where('tag', $tag);
})->latest()->with('tags')->withCount('tags')->paginate(10);
return view('bookmarks.tagged', compact('bookmarks', 'tag'));
}
}
| <?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Models\Bookmark;
use Illuminate\View\View;
class BookmarksController extends Controller
{
/**
* Show the most recent bookmarks.
*
* @return View
*/
public function index(): View
{
$bookmarks = Bookmark::latest()->with('tags')->withCount('tags')->paginate(10);
return view('bookmarks.index', compact('bookmarks'));
}
/**
* Show a single bookmark.
*
* @param Bookmark $bookmark
* @return View
*/
public function show(Bookmark $bookmark): View
{
$bookmark->loadMissing('tags');
return view('bookmarks.show', compact('bookmark'));
}
/**
* Show bookmakrs tagged with a specific tag.
*
* @param string $tag
* @return View
*/
public function tagged(string $tag): View
{
$bookmarks = Bookmark::whereHas('tags', function ($query) use ($tag) {
$query->where('tag', $tag);
})->latest()->with('tags')->withCount('tags')->paginate(10);
return view('bookmarks.tagged', compact('bookmarks', 'tag'));
}
}
|
Add tests to implement TODO comment | import test from 'ava';
import 'babel-core/register';
import AnalyzerResult from '../src/lib/analyzer-result';
test('addMessage adds expected message', t => {
const testMessageType = 'test';
const testMessageText = 'test-message';
const result = new AnalyzerResult();
result.addMessage(testMessageType, testMessageText);
t.is(result.getMessage(testMessageType).text, testMessageText);
});
test('addMessage adds expected line', t => {
const testMessageType = 'test';
const testMessageLine = 3;
const result = new AnalyzerResult();
result.addMessage(testMessageType, 'test-message', testMessageLine);
t.is(result.getMessage(testMessageType).line, testMessageLine);
});
test('addMessage adds expected column', t => {
const testMessageType = 'test';
const testMessageColumn = 7;
const result = new AnalyzerResult();
result.addMessage(testMessageType, 'test-message', 3, testMessageColumn);
t.is(result.getMessage(testMessageType).column, testMessageColumn);
});
test('getMessage returns null if message type does not exist', t => {
const result = new AnalyzerResult();
const message = result.getMessage('does-not-exist');
t.is(message, null);
});
test('getMessage returns expected message text if it exists', t => {
const testMessageType = 'test';
const testMessageText = 'test-message';
const result = new AnalyzerResult();
result.addMessage(testMessageType, testMessageText);
const messageText = result.getMessage(testMessageType).text;
t.is(messageText, testMessageText);
});
| import test from 'ava';
import 'babel-core/register';
import AnalyzerResult from '../src/lib/analyzer-result';
test('addMessage adds expected message', t => {
const testMessageType = 'test';
const testMessageText = 'test-message';
const result = new AnalyzerResult();
result.addMessage(testMessageType, testMessageText);
t.is(result.getMessage(testMessageType).text, testMessageText);
// TODO: Add tests for line and column after changing what getMessage returns
});
test('getMessage returns null if message type does not exist', t => {
const result = new AnalyzerResult();
const message = result.getMessage('does-not-exist');
t.is(message, null);
});
test('getMessage returns expected message text if it exists', t => {
const testMessageType = 'test';
const testMessageText = 'test-message';
const result = new AnalyzerResult();
result.addMessage(testMessageType, testMessageText);
const messageText = result.getMessage(testMessageType).text;
t.is(messageText, testMessageText);
});
|
Fix Share page permission migration | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
def create_share_permissions(apps, schema_editor):
ContentType = apps.get_model('contenttypes.ContentType')
Permission = apps.get_model('auth.Permission')
Group = apps.get_model('auth.Group')
v1_content_type = ContentType.objects.get(app_label="v1", model="cfgovpage")
# Create share permission
share_permission = Permission.objects.create(
content_type=v1_content_type,
codename='share_page',
name='Can share pages'
)
# Assign it to Editors and Moderators groups
for group in Group.objects.all():
group.permissions.add(share_permission)
class Migration(migrations.Migration):
dependencies = [
('v1', '0011_auto_20151207_1725'),
]
operations = [
migrations.RunPython(create_share_permissions),
]
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
def create_share_permissions(apps, schema_editor):
ContentType = apps.get_model('contenttypes.ContentType')
Permission = apps.get_model('auth.Permission')
Group = apps.get_model('auth.Group')
v1_content_type = ContentType.objects.create(app_label="v1", model="cfgovpage")
# Create share permission
share_permission = Permission.objects.create(
content_type=v1_content_type,
codename='share_page',
name='Can share pages'
)
# Assign it to Editors and Moderators groups
for group in Group.objects.all():
group.permissions.add(share_permission)
class Migration(migrations.Migration):
dependencies = [
('v1', '0011_auto_20151207_1725'),
]
operations = [
migrations.RunPython(create_share_permissions),
]
|
test: Adjust test bootstrap file for new autoloader structure | <?php
$base = dirname(__FILE__) . "/..";
set_include_path(
$base . "/config:" .
$base . "/system/config:" .
$base . "/system:" .
$base . "/tests:" .
$base . "/tests/system:" .
$base . "/application/libraries/enums:" .
$base . "/application/libraries/core:" .
$base . "/application/libraries/db:" .
$base . "/application/controllers:" .
$base . "/application/models:" .
$base . "/application/libraries:" .
$base . "/application/views:" .
get_include_path()
);
// Load and setup class file autloader
include_once("libraries/core/class.autoloader.inc.php");
spl_autoload_register(array(new Lunr\Libraries\Core\Autoloader(), 'load'));
?>
| <?php
$base = dirname(__FILE__) . "/..";
set_include_path(
$base . "/config:" .
$base . "/system/config:" .
$base . "/system:" .
$base . "/tests:" .
$base . "/tests/system:" .
$base . "/application/libraries/enums:" .
$base . "/application/libraries/core:" .
$base . "/application/libraries/db:" .
$base . "/application/controllers:" .
$base . "/application/models:" .
$base . "/application/libraries:" .
$base . "/application/views:" .
get_include_path()
);
// Load and setup class file autloader
include_once("libraries/core/class.autoloader.inc.php");
spl_autoload_register("Lunr\Libraries\Core\Autoloader::load");
?>
|
Test width of progress bar | import pytest
from downloads.download import _progress_bar
@pytest.mark.parametrize(
"current,block_size,total_size",
[
(
100,
32,
100 * 32,
),
(
75,
32,
100 * 32,
),
(
50,
32,
100 * 32,
),
(
25,
32,
100 * 32,
),
(
0,
32,
100 * 32,
),
],
)
def test_progress_bar(current, block_size, total_size):
bar = _progress_bar(
current=current, block_size=block_size, total_size=total_size
)
assert bar.count("#") == current
assert bar.split()[-1] == f"{current:.1f}%"
assert len(bar) == 100 + 8
| import pytest
from downloads.download import _progress_bar
@pytest.mark.parametrize(
"current,block_size,total_size",
[
(
100,
32,
100 * 32,
),
(
75,
32,
100 * 32,
),
(
50,
32,
100 * 32,
),
(
25,
32,
100 * 32,
),
(
0,
32,
100 * 32,
),
],
)
def test_progress_bar(current, block_size, total_size):
bar = _progress_bar(
current=current, block_size=block_size, total_size=total_size
)
assert bar.count("#") == current
assert bar.split()[-1] == f"{current:.1f}%"
|
Add alias to hetu in for finnish personal id code | # __init__.py - collection of Finnish numbers
# coding: utf-8
#
# Copyright (C) 2012 Arthur de Jong
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
"""Collection of Finnish numbers."""
# provide vat as an alias
from stdnum.fi import alv as vat
from stdnum.fi import ytunnus as businessid
from stdnum.fi import hetu as personalid
| # __init__.py - collection of Finnish numbers
# coding: utf-8
#
# Copyright (C) 2012 Arthur de Jong
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
"""Collection of Finnish numbers."""
# provide vat as an alias
from stdnum.fi import alv as vat
from stdnum.fi import ytunnus as businessid
|
Convert all text files to Linux linefeeds | package net.ssehub.kernel_haven.feature_effects;
import net.ssehub.kernel_haven.SetUpException;
import net.ssehub.kernel_haven.analysis.AnalysisComponent;
import net.ssehub.kernel_haven.analysis.PipelineAnalysis;
import net.ssehub.kernel_haven.config.Configuration;
/**
* An analysis that finds feature effect formulas for variables.
*
* @author Adam
*/
public class FeatureEffectAnalysis extends PipelineAnalysis {
/**
* Creates a new {@link FeatureEffectAnalysis}.
*
* @param config The global configuration.
*/
public FeatureEffectAnalysis(Configuration config) {
super(config);
}
@Override
protected AnalysisComponent<?> createPipeline() throws SetUpException {
return new FeatureEffectFinder(config,
new PcFinder(config,
getCmComponent(),
getBmComponent()
)
);
}
}
| package net.ssehub.kernel_haven.feature_effects;
import net.ssehub.kernel_haven.SetUpException;
import net.ssehub.kernel_haven.analysis.AnalysisComponent;
import net.ssehub.kernel_haven.analysis.PipelineAnalysis;
import net.ssehub.kernel_haven.config.Configuration;
/**
* An analysis that finds feature effect formulas for variables.
*
* @author Adam
*/
public class FeatureEffectAnalysis extends PipelineAnalysis {
/**
* Creates a new {@link FeatureEffectAnalysis}.
*
* @param config The global configuration.
*/
public FeatureEffectAnalysis(Configuration config) {
super(config);
}
@Override
protected AnalysisComponent<?> createPipeline() throws SetUpException {
return new FeatureEffectFinder(config,
new PcFinder(config,
getCmComponent(),
getBmComponent()
)
);
}
}
|
Use console.warn instead of console.error | (function() {
// Resolves string keys with dots in a deeply nested object
// http://stackoverflow.com/a/22129960/4405214
var resolveObject = function(path, obj) {
return path
.split('.')
.reduce(function(prev, curr) {
return prev && prev[curr];
}, obj || self);
}
Spree.t = function(key, options) {
options = (options || {});
if(options.scope) {
key = options.scope + "." + key;
}
var translation = resolveObject(key, Spree.translations);
if (translation) {
return translation;
} else {
console.warn("No translation found for " + key + ".");
return key;
}
}
Spree.human_attribute_name = function(model, attr) {
return Spree.t("activerecord.attributes." + model + '.' + attr);
}
})();
| (function() {
// Resolves string keys with dots in a deeply nested object
// http://stackoverflow.com/a/22129960/4405214
var resolveObject = function(path, obj) {
return path
.split('.')
.reduce(function(prev, curr) {
return prev && prev[curr];
}, obj || self);
}
Spree.t = function(key, options) {
options = (options || {});
if(options.scope) {
key = options.scope + "." + key;
}
var translation = resolveObject(key, Spree.translations);
if (translation) {
return translation;
} else {
console.error("No translation found for " + key + ".");
return key;
}
}
Spree.human_attribute_name = function(model, attr) {
return Spree.t("activerecord.attributes." + model + '.' + attr);
}
})();
|
Add checking on current project == null
Signed-off-by: Vitaly Parfonov <3980a3d6ad736918e593101a7ff03dfd34097f49@codenvy.com> | /*******************************************************************************
* Copyright (c) 2012-2016 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.ide.extension.machine.client.command.valueproviders;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import org.eclipse.che.ide.api.app.AppContext;
import org.eclipse.che.ide.api.app.CurrentProject;
/**
* Provides relative path to specific project. Path to project resolves from current workspace root.
* e.g. /project_name.
*
* Need for IDEX-3924 as intermediate solution.
*
* @author Vlad Zhukovskiy
*/
@Singleton
public class CurrentProjectRelativePathProvider implements CommandPropertyValueProvider {
private static final String KEY = "${current.project.relpath}";
private AppContext appContext;
@Inject
public CurrentProjectRelativePathProvider(AppContext appContext) {
this.appContext = appContext;
}
@Override
public String getKey() {
return KEY;
}
@Override
public String getValue() {
CurrentProject currentProject = appContext.getCurrentProject();
if (currentProject == null) {
return "";
}
return currentProject.getProjectConfig().getPath().substring(1);
}
}
| /*******************************************************************************
* Copyright (c) 2012-2016 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.ide.extension.machine.client.command.valueproviders;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import org.eclipse.che.ide.api.app.AppContext;
/**
* Provides relative path to specific project. Path to project resolves from current workspace root.
* e.g. /project_name.
*
* Need for IDEX-3924 as intermediate solution.
*
* @author Vlad Zhukovskiy
*/
@Singleton
public class CurrentProjectRelativePathProvider implements CommandPropertyValueProvider {
private static final String KEY = "${current.project.relpath}";
private AppContext appContext;
@Inject
public CurrentProjectRelativePathProvider(AppContext appContext) {
this.appContext = appContext;
}
@Override
public String getKey() {
return KEY;
}
@Override
public String getValue() {
return appContext.getCurrentProject().getProjectConfig().getPath().substring(1);
}
}
|
Change from error to warn in userdata | core.Class("lowland.base.UserData", {
construct : function() {
this.__$$userdata = {};
},
members : {
setUserData : function(key, value) {
if (core.Env.getValue("debug")) {
if (!key) {
throw new Error("Parameter key not set");
}
if (!value) {
console.warn("Parameter value not set for key " + key);
}
}
this.__$$userdata[key] = value;
},
getUserData : function(key) {
if (core.Env.getValue("debug")) {
if (!key) {
throw new Error("Parameter key not set");
}
}
return this.__$$userdata[key];
},
removeUserData : function(key) {
if (core.Env.getValue("debug")) {
if (!key) {
throw new Error("Parameter key not set");
}
}
this.__$$userdata[key] = undefined;
}
}
}); | core.Class("lowland.base.UserData", {
construct : function() {
this.__$$userdata = {};
},
members : {
setUserData : function(key, value) {
if (core.Env.getValue("debug")) {
if (!key) {
throw new Error("Parameter key not set");
}
if (!value) {
throw new Error("Parameter value not set");
}
}
this.__$$userdata[key] = value;
},
getUserData : function(key) {
if (core.Env.getValue("debug")) {
if (!key) {
throw new Error("Parameter key not set");
}
}
return this.__$$userdata[key];
},
removeUserData : function(key) {
if (core.Env.getValue("debug")) {
if (!key) {
throw new Error("Parameter key not set");
}
}
this.__$$userdata[key] = undefined;
}
}
}); |
Make sure the test fails | var code = multiline([
"(function() {",
" var bar = 'lol';",
" function foo(b){",
" b === bar;",
" foo(b);",
" }",
"})();",
]);
transform(code, {
plugins: [
function (b) {
var t = b.types;
return {
visitor: {
// Replace block statements with a new node without changing anything
BlockStatement: function(path) {
if (path.node.seen) {
return;
}
var node = t.blockStatement(path.node.body);
node.seen = true;
path.replaceWith(node);
},
// do type inference
BinaryExpression: function(path) {
var left = path.get("left");
var right = path.get("right");
left.baseTypeStrictlyMatches(right);
}
}
};
}
]
});
| var code = multiline([
"(function() {",
" function foo(b){",
' b === "lol";',
" foo(b);",
" }",
"})();",
]);
transform(code, {
plugins: [
function (b) {
var t = b.types;
return {
visitor: {
// Replace block statements with a new node without changing anything
BlockStatement: function(path) {
if (path.node.seen) {
return;
}
var node = t.blockStatement(path.node.body);
node.seen = true;
path.replaceWith(node);
},
// do type inference
BinaryExpression: function(path) {
var left = path.get("left");
var right = path.get("right");
left.baseTypeStrictlyMatches(right);
}
}
};
}
]
});
|
Update path on Repetory action | import Ember from 'ember';
import Model from 'ember-data/model';
import DS from 'ember-data';
import {memberAction} from 'ember-api-actions';
import { validator, buildValidations } from 'ember-cp-validations';
const Validations = buildValidations({
chart: validator('presence', true),
});
export default Model.extend(Validations, {
nomen: DS.attr('string'),
status: DS.attr('repertory-status'),
chart: DS.belongsTo('chart', {async: true}),
entity: DS.belongsTo('entity', {async: true}),
submissions: DS.hasMany('submission', {async: true}),
validateRepertory: memberAction({path: 'validate', type: 'post'}),
invalidate: memberAction({path: 'invalidate', type: 'post'}),
permissions: DS.attr(),
statusOptions: [
'New',
'Active',
'Inactive',
],
isOld: Ember.computed.not('isNew'),
});
| import Ember from 'ember';
import Model from 'ember-data/model';
import DS from 'ember-data';
import {memberAction} from 'ember-api-actions';
import { validator, buildValidations } from 'ember-cp-validations';
const Validations = buildValidations({
chart: validator('presence', true),
});
export default Model.extend(Validations, {
nomen: DS.attr('string'),
status: DS.attr('repertory-status'),
chart: DS.belongsTo('chart', {async: true}),
entity: DS.belongsTo('entity', {async: true}),
submissions: DS.hasMany('submission', {async: true}),
validateRepertory: memberAction({path: 'val', type: 'post'}),
invalidate: memberAction({path: 'invalidate', type: 'post'}),
permissions: DS.attr(),
statusOptions: [
'New',
'Active',
'Inactive',
],
isOld: Ember.computed.not('isNew'),
});
|
Remove routing to placeholder components | /**
*
* @flow
*/
'use strict';
import React, { Component } from 'react'
import {
Navigator,
StyleSheet
} from 'react-native'
import HomeView from './tabs/home/HomeView'
export default class EduChainNavigator extends Component {
constructor(props: Object) {
super(props);
}
renderScene(route: Object, navigator: Navigator) {
switch (route.id) {
default:
return (<HomeView navigator={navigator} />);
}
}
render() {
return (
<Navigator
ref="navigator"
initialRoute={ {} }
renderScene={this.renderScene}
/>
);
}
}
| /**
*
* @flow
*/
'use strict';
import React, { Component } from 'react'
import {
Navigator,
StyleSheet
} from 'react-native'
import First from './First'
import Second from './Second'
import HomeView from './tabs/home/HomeView'
export default class EduChainNavigator extends Component {
constructor(props: Object) {
super(props);
}
renderScene(route: Object, navigator: Navigator) {
switch (route.id) {
case "first":
return (<First navigator={navigator} title="first" />);
case "second":
return (<Second navigator={navigator} title="second" />);
default:
return (<HomeView navigator={navigator} />);
}
}
render() {
return (
<Navigator
ref="navigator"
initialRoute={ {} }
renderScene={this.renderScene}
/>
);
}
}
|
Document default bind rule sort order | package org.grouplens.inject.graph;
/**
* A repository for obtaining type nodes and resolving desires. The reflection
* implementation uses annotations and subclassing relationships to attempt to
* resolve desires from the classpath.
*
* @author Michael Ekstrand <ekstrand@cs.umn.edu>
*/
public interface NodeRepository {
/**
* Look up the node for a desire, using whatever default lookup rules are
* specified.
*
* @param desire The desire to resolve.
* @return The node resolved by this desire, or <tt>null</tt> if the desire
* is not instantiable and cannot be resolved.
*/
Node resolve(Desire desire);
/**
* Get a bind rule which uses the repository's defaults to resolve desires.
* For any desire, this bind rule will compare less than all other bind
* rules applicable to that desire.
*
* @return A bind rule that uses defaults and annotations to resolve
* desires.
*/
BindRule defaultBindRule();
}
| package org.grouplens.inject.graph;
/**
* A repository for obtaining type nodes and resolving desires. The reflection
* implementation uses annotations and subclassing relationships to attempt to
* resolve desires from the classpath.
*
* @author Michael Ekstrand <ekstrand@cs.umn.edu>
*/
public interface NodeRepository {
/**
* Look up the node for a desire, using whatever default lookup rules are
* specified.
*
* @param desire The desire to resolve.
* @return The node resolved by this desire, or <tt>null</tt> if the desire
* is not instantiable and cannot be resolved.
*/
Node resolve(Desire desire);
/**
* Get a bind rule which uses the repository's defaults to resolve desires.
*
* @return A bind rule that uses defaults and annotations to resolve
* desires.
*/
BindRule defaultBindRule();
}
|
Fix create review parameter names | import AWS from 'aws-sdk';
import uuid from 'uuid';
export class CreateReview {
constructor(AWS, table) {
this.client = new AWS.DynamoDB.DocumentClient({
params: {
TableName: table,
},
});
}
itemFrom(params) {
return {
id: uuid.v4(),
timestamp: new Date().getTime(),
title: params.title,
description: params.description,
url: params.url,
submitter: params.submitter,
};
}
handle(params) {
const item = this.itemFrom(params);
return this.client.put({
Item: item,
})
.promise()
.then(() => item)
;
}
static handler(event, context, callback) {
AWS.config.update({
region: process.env.AWS_REGION,
});
new CreateReview(AWS, process.env.REKT_REVIEWS_TABLE)
.handle(event)
.then(item => callback(null, item))
.catch(err => callback(err))
;
}
}
export const handler = CreateReview.handler;
| import AWS from 'aws-sdk';
import uuid from 'uuid';
export class CreateReview {
constructor(AWS, table) {
this.client = new AWS.DynamoDB.DocumentClient({
params: {
TableName: table,
},
});
}
itemFrom(params) {
return {
id: uuid.v4(),
timestamp: new Date().getTime(),
title: params.title,
description: params.description,
url: params.url,
submitter: params.submitter,
};
}
handle(params) {
console.log(params);
const item = this.itemFrom(params);
return this.client.put({
Item: item,
})
.promise()
.then(() => item)
;
}
static handler(event, context, callback) {
AWS.config.update({
region: process.env.AWS_REGION,
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
});
new CreateReview(AWS, process.env.REKT_REVIEWS_TABLE)
.handle(params)
.then(item => callback(null, item))
.catch(err => callback(err))
;
}
}
export const handler = CreateReview.handler;
|
Revert "Fix plotline getting removed when children present"
This reverts commit d8dd4d977c3dcec578e083a2cd5beca4b9873e5c. | import React, { useRef, useEffect, useState } from 'react';
import uuid from 'uuid/v4';
import { attempt } from 'lodash-es';
import useModifiedProps from '../UseModifiedProps';
import useAxis from '../UseAxis';
export default function usePlotBandLine(props, plotType) {
const { id = uuid, children, ...rest } = props;
const axis = useAxis();
const idRef = useRef();
const [plotbandline, setPlotbandline] = useState(null);
const modifiedProps = useModifiedProps(rest);
useEffect(() => {
if (!axis) return;
if(!plotbandline || modifiedProps !== false) {
if(!plotbandline) {
idRef.current = typeof id === 'function' ? id() : id;
}
const myId = idRef.current;
const opts = {
id: myId,
...rest
};
setPlotbandline(axis.addPlotBandOrLine(opts, plotType));
}
return () => {
attempt(axis.removePlotBandOrLine, idRef.current);
};
});
return plotbandline;
}
| import React, { useRef, useEffect, useState } from 'react';
import uuid from 'uuid/v4';
import { attempt } from 'lodash-es';
import useModifiedProps from '../UseModifiedProps';
import useAxis from '../UseAxis';
export default function usePlotBandLine(props, plotType) {
const { id = uuid, children, ...rest } = props;
const axis = useAxis();
const idRef = useRef();
const [plotbandline, setPlotbandline] = useState(null);
const modifiedProps = useModifiedProps(rest);
useEffect(() => {
if (!axis) return;
if(!plotbandline || modifiedProps !== false) {
if(!plotbandline) {
idRef.current = typeof id === 'function' ? id() : id;
}
const myId = idRef.current;
const opts = {
id: myId,
...rest
};
if(plotbandline) axis.removePlotBandOrLine(idRef.current);
setPlotbandline(axis.addPlotBandOrLine(opts, plotType));
}
});
useEffect(() => {
return () => {
attempt(axis.removePlotBandOrLine, idRef.current);
};
}, []);
return plotbandline;
}
|
Add SO_REUSEADDR to socket options | # -*- coding: utf-8 -*-
import logging
import socket
import threading
from connection import Connection
import shared
class Listener(threading.Thread):
def __init__(self, host, port, family=socket.AF_INET):
super().__init__(name='Listener')
self.host = host
self.port = port
self.family = family
self.s = socket.socket(self.family, socket.SOCK_STREAM)
self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.s.bind((self.host, self.port))
def run(self):
self.s.listen(1)
self.s.settimeout(1)
while True:
try:
conn, addr = self.s.accept()
logging.info('Incoming connection from: {}:{}'.format(addr[0], addr[1]))
with shared.connections_lock:
c = Connection(addr[0], addr[1], conn)
c.start()
shared.connections.add(c)
except socket.timeout:
pass
| # -*- coding: utf-8 -*-
import logging
import socket
import threading
from connection import Connection
import shared
class Listener(threading.Thread):
def __init__(self, host, port, family=socket.AF_INET):
super().__init__(name='Listener')
self.host = host
self.port = port
self.family = family
self.s = socket.socket(self.family, socket.SOCK_STREAM)
self.s.bind((self.host, self.port))
def run(self):
self.s.listen(1)
self.s.settimeout(1)
while True:
try:
conn, addr = self.s.accept()
logging.info('Incoming connection from: {}:{}'.format(addr[0], addr[1]))
with shared.connections_lock:
c = Connection(addr[0], addr[1], conn)
c.start()
shared.connections.add(c)
except socket.timeout:
pass
|
Add tests for core.views.index.py. The tests presently test only if the corresponding urls can be accessed. | #/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2010-2012 Cidadania S. Coop. Galega
#
# This file is part of e-cidadania.
#
# e-cidadania is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# e-cidadania is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with e-cidadania. If not, see <http://www.gnu.org/licenses/>.
from e_cidadania import url_names
from tests.test_utils import ECDTestCase
class IndexTestCase(ECDTestCase):
"""Class to test index related views.
"""
def testIndexView(self):
"""Tests the index view.
"""
response = self.get(url_name=url_names.SITE_INDEX)
self.assertResponseOK(response)
def testIndexEntriesFeed(self):
"""Tests the index entries feed view.
"""
response = self.get(url_name=url_names.SITE_FEED)
self.assertResponseOK(response) | #/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2010-2012 Cidadania S. Coop. Galega
#
# This file is part of e-cidadania.
#
# e-cidadania is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# e-cidadania is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with e-cidadania. If not, see <http://www.gnu.org/licenses/>.
from tests.test_utils import ECDTestCase
class IndexTestCase(ECDTestCase):
"""Class to test index related views.
"""
def testIndexView(self):
"""Tests the index view.
"""
#url = self.getUrl(url_names.SITE_INDEX)
url = '/'
response = self.get(url)
self.assertResponseOK(response) |
Update for Fall 2015-16 semester | import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.net.URL;
public class CourseCodeTableCrawler {
public static Elements get(String courseCode) {
String url = "https://stars.bilkent.edu.tr/homepage/ajax/plainOfferings.php?SEMESTER=20151&COURSE_CODE=" + courseCode.toUpperCase();
try {
Document doc = Jsoup.parse(new URL(url), 10000);
Element table = doc.getElementById("poTable");
Elements rows = table.getElementsByTag("tr");
return rows;
} catch (Exception e) {
e.printStackTrace();
return new Elements();
}
}
}
| import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.net.URL;
public class CourseCodeTableCrawler {
public static Elements get(String courseCode) {
String url = "https://stars.bilkent.edu.tr/homepage/ajax/plainOfferings.php?SEMESTER=20142&COURSE_CODE=" + courseCode.toUpperCase();
try {
Document doc = Jsoup.parse(new URL(url), 10000);
Element table = doc.getElementById("poTable");
Elements rows = table.getElementsByTag("tr");
return rows;
} catch (Exception e) {
e.printStackTrace();
return new Elements();
}
}
}
|
Fix spoilers with line breaks. | 'use strict';
var plugins = module.parent.require('./plugins'),
fs = require('fs'),
path = require('path'),
util = require('util'),
app;
var plugin = {};
plugin.parse = function(data, callback) {
if (data && typeof data === 'string') {
// preview
data = parser(data);
} else if (data.postData && data.postData.content) {
// post
data.postData.content = parser(data.postData.content);
} else if (data.userData && data.userData.signature) {
// signature
data.userData.signature = parser(data.userData.signature);
}
callback(null, data);
}
// replace [spoiler] fake tags with real tags
function parser(data) {
// replace inline spoilers
var spoilers = /\[spoiler\].*?\[\/spoiler\]/g;
data = data.replace(spoilers, function(match) {
return '<span class="spoiler blur" onclick="toggleBlur(this);">' + match.substring(9, match.length - 10) + '</span>';
});
// replace multi-line spoilers
data = data.replace('[spoiler]', '<div class="spoiler blur" onclick="toggleBlur(this);">').replace('[/spoiler]', '</div>');
return data;
}
module.exports = plugin;
| 'use strict';
var plugins = module.parent.require('./plugins'),
fs = require('fs'),
path = require('path'),
util = require('util'),
app;
var plugin = {};
plugin.parse = function(data, callback) {
if (data && typeof data === 'string') {
// preview
data = parser(data);
} else if (data.postData && data.postData.content) {
// post
data.postData.content = parser(data.postData.content);
} else if (data.userData && data.userData.signature) {
// signature
data.userData.signature = parser(data.userData.signature);
}
callback(null, data);
}
// replace [spoiler] fake tags with real tags
function parser(data) {
data = data
.replace('[spoiler]', '<span class="spoiler blur" onclick="toggleBlur(this);">')
.replace('[/spoiler]', '</span>');
return data;
}
module.exports = plugin;
|
Replace all broken image links in js | $(document).ready(function() {
// Set title preview
$("#title").on('keyup', function(e) {
$("#title-preview").text($("#title").val());
$("#title-preview").attr("href", $("#url").val());
})
// Set image preview
$("#url").on('keyup', function(e) {
$("#img-preview").attr("src", $(this).val());
})
// Replace broken images
$(".grid-img").error(function() {
$(this).attr("src", "http://dummyimage.com/800x600&text=Pinternet");
});
// Show grid
var $grid = $('.grid').masonry({
itemSelector: '.grid-item',
fitWidth: true,
transitionDuration: '0.8s',
columnWidth: 5
});
// Set layout so no image overlap on image load
$grid.imagesLoaded().progress( function() {
$grid.masonry('layout');
});
});
| $(document).ready(function() {
// Set title preview
$("#title").on('keyup', function(e) {
$("#title-preview").text($("#title").val());
$("#title-preview").attr("href", $("#url").val());
})
// Set image preview
$("#url").on('keyup', function(e) {
$("#img-preview").attr("src", $("#url").val());
})
// Replace broken images
$("#img-preview").error(function() {
$(this).attr("src", "http://dummyimage.com/800x600&text=Pinternet");
});
// Show grid
var $grid = $('.grid').masonry({
itemSelector: '.grid-item',
fitWidth: true,
transitionDuration: '0.8s',
columnWidth: 5
});
// Set layout so no image overlap on image load
$grid.imagesLoaded().progress( function() {
$grid.masonry('layout');
});
});
|
Send JWT auth token on the as an authorization header of every HTTP request. | module.exports = (function() {
var Router = require('router'),
Connection = require('lib/connection');
// App namespace.
window.Boards = {
Models: {},
Collections: {}
};
// Load helpers.
require('lib/helpers');
$.ajaxSetup({
beforeSend: function(xhr, settings) {
xhr.setRequestHeader('Authorization', 'JWT ' + _.getModel('User').get('token'));
}
});
// Register Swag Helpers.
Swag.registerHelpers();
// Initialize Router.
Boards.Router = new Router();
// Create a Connection object to communicate with the server through web sockets.
// The `connection` object will be added to the `Application` object so it's available through
// `window.Application.connection`.
Boards.Connection = new Connection({
type: APPLICATION_CONNECTION,
httpUrl: APPLICATION_HTTP_URL,
socketUrl: APPLICATION_WEBSOCKET_URL
});
// Connect to the server.
Boards.Connection.create().done(function() {
Boards.Router.start();
}).fail(function() {
console.log('Connection Error', arguments);
});
})();
| module.exports = (function() {
var Router = require('router'),
Connection = require('lib/connection');
// App namespace.
window.Boards = {
Models: {},
Collections: {}
};
// Load helpers.
require('lib/helpers');
// Register Swag Helpers.
Swag.registerHelpers();
// Initialize Router.
Boards.Router = new Router();
// Create a Connection object to communicate with the server through web sockets.
// The `connection` object will be added to the `Application` object so it's available through
// `window.Application.connection`.
Boards.Connection = new Connection({
type: APPLICATION_CONNECTION,
httpUrl: APPLICATION_HTTP_URL,
socketUrl: APPLICATION_WEBSOCKET_URL
});
// Connect to the server.
Boards.Connection.create().done(function() {
Boards.Router.start();
}).fail(function() {
console.log('Connection Error', arguments);
});
})();
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.