text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Fix bug in imageserver AddImage() RPC handler. | package rpcd
import (
"errors"
"fmt"
"github.com/Symantec/Dominator/lib/hash"
"github.com/Symantec/Dominator/proto/imageserver"
)
func (t *rpcType) AddImage(request imageserver.AddImageRequest,
reply *imageserver.AddImageResponse) error {
if imageDataBase.CheckImage(request.ImageName) {
return errors.New("image already exists")
}
if request.Image == nil {
return errors.New("nil image")
}
if request.Image.FileSystem == nil {
return errors.New("nil file-system")
}
// Verify all objects are available.
hashes := make([]hash.Hash, 0,
len(request.Image.FileSystem.RegularInodeTable))
for _, inode := range request.Image.FileSystem.RegularInodeTable {
if inode.Size > 0 {
hashes = append(hashes, inode.Hash)
}
}
objectsPresent, err := imageDataBase.ObjectServer().CheckObjects(hashes)
if err != nil {
return err
}
for index, present := range objectsPresent {
if !present {
return errors.New(fmt.Sprintf("object: %d %x is not available",
index, hashes[index]))
}
}
// TODO(rgooch): Remove debugging output.
fmt.Printf("AddImage(%s)\n", request.ImageName)
return imageDataBase.AddImage(request.Image, request.ImageName)
}
| package rpcd
import (
"errors"
"fmt"
"github.com/Symantec/Dominator/lib/hash"
"github.com/Symantec/Dominator/proto/imageserver"
)
func (t *rpcType) AddImage(request imageserver.AddImageRequest,
reply *imageserver.AddImageResponse) error {
if imageDataBase.CheckImage(request.ImageName) {
return errors.New("image already exists")
}
if request.Image == nil {
return errors.New("nil image")
}
if request.Image.FileSystem == nil {
return errors.New("nil file-system")
}
// Verify all objects are available.
hashes := make([]hash.Hash, len(request.Image.FileSystem.RegularInodeTable))
for index, inode := range request.Image.FileSystem.RegularInodeTable {
hashes[index] = inode.Hash
}
objectsPresent, err := imageDataBase.ObjectServer().CheckObjects(hashes)
if err != nil {
return err
}
for index, present := range objectsPresent {
if !present {
return errors.New(fmt.Sprintf("object: %x is not available",
hashes[index]))
}
}
// TODO(rgooch): Remove debugging output.
fmt.Printf("AddImage(%s)\n", request.ImageName)
return imageDataBase.AddImage(request.Image, request.ImageName)
}
|
App: Add logic to run npmInstall | 'use strict';
var generators = require('yeoman-generator'),
chalk = require('chalk');
module.exports = generators.Base.extend({
constructor: function () {
generators.Base.apply(this, arguments);
},
writing: {
app: function () {
this.fs.copy(
this.templatePath('_package.json'),
this.destinationPath('package.json')
);
},
projectfiles: function () {
this.fs.copy(
this.templatePath('gitignore'),
this.destinationPath('.gitignore')
);
this.fs.copy(
this.templatePath('eslintrc'),
this.destinationPath('.eslintrc')
);
this.fs.copy(
this.templatePath('_csscomb.json'),
this.destinationPath('csscomb.json')
);
}
},
// Run npm install
install: function () {
this.npmInstall();
}
});
| 'use strict';
var generators = require('yeoman-generator'),
chalk = require('chalk');
module.exports = generators.Base.extend({
constructor: function () {
generators.Base.apply(this, arguments);
},
writing: {
app: function () {
this.fs.copy(
this.templatePath('_package.json'),
this.destinationPath('package.json')
);
},
projectfiles: function () {
this.fs.copy(
this.templatePath('gitignore'),
this.destinationPath('.gitignore')
);
this.fs.copy(
this.templatePath('eslintrc'),
this.destinationPath('.eslintrc')
);
this.fs.copy(
this.templatePath('_csscomb.json'),
this.destinationPath('csscomb.json')
);
}
}
});
|
[FEATURE] Remove balanceId from ripple transactions table | var dbm = require('db-migrate');
var type = dbm.dataType;
exports.up = function(db, callback) {
db.createTable('ripple_transactions', {
id: { type: 'int', primaryKey: true, autoIncrement: true, notNull: true, unique: true },
issuance: { type: 'boolean', notNull: true },
toCurrency: { type: 'string', notNull: true },
toAddress: { type: 'string', notNull: true },
fromAddress: { type: 'string', notNull: true },
toAmount: { type: 'decimal', notNull: true },
fromCurrency: { type: 'string', notNull: true },
fromAmount: { type: 'decimal', notNull: true },
txHash: { type: 'string', unique: true },
createdAt: { type: 'datetime', notNull: true },
destinationTag: { type: 'string' },
sourceTag: { type: 'string' },
txState: { type: 'string' },
updatedAt: { type: 'datetime' }
}, callback);
};
exports.down = function(db, callback) {
db.dropTable('ripple_transactions', callback);
callback();
};
| var dbm = require('db-migrate');
var type = dbm.dataType;
exports.up = function(db, callback) {
db.createTable('ripple_transactions', {
id: { type: 'int', primaryKey: true, autoIncrement: true, notNull: true, unique: true },
issuance: { type: 'boolean', notNull: true },
toCurrency: { type: 'string', notNull: true },
toAddress: { type: 'string', notNull: true },
fromAddress: { type: 'string', notNull: true },
toAmount: { type: 'decimal', notNull: true },
fromCurrency: { type: 'string', notNull: true },
fromAmount: { type: 'decimal', notNull: true },
txHash: { type: 'string', unique: true },
createdAt: { type: 'datetime', notNull: true },
destinationTag: { type: 'string' },
sourceTag: { type: 'string' },
balanceId: { type: 'int', notNull: true },
txState: { type: 'string' },
updatedAt: { type: 'datetime' }
}, callback);
};
exports.down = function(db, callback) {
db.dropTable('ripple_transactions', callback);
callback();
};
|
Add password auth when configured on RTB | package com.xrtb.tests;
import static org.junit.Assert.*;
import org.junit.Test;
import redis.clients.jedis.Jedis;
import com.xrtb.bidder.DeadmanSwitch;
import com.xrtb.common.Configuration;
public class TestDeadmanSwitch {
@Test
public void testSwitch() throws Exception {
Jedis redis = new Jedis("localhost");
redis.connect();
if (Configuration.getInstance().password != null)
redis.auth(Configuration.getInstance().password);
DeadmanSwitch.testmode = true;
if (Configuration.setPassword() != null)
redis.auth(Configuration.setPassword());
redis.del("deadmanswitch");
DeadmanSwitch d = new DeadmanSwitch("localhost",6379, "deadmanswitch");
Thread.sleep(1000);
assertFalse(d.canRun());
redis.set("deadmanswitch", "ready");
redis.expire("deadmanswitch", 5);
assertTrue(d.canRun());
Thread.sleep(10000);
assertFalse(d.canRun());
}
}
| package com.xrtb.tests;
import static org.junit.Assert.*;
import org.junit.Test;
import redis.clients.jedis.Jedis;
import com.xrtb.bidder.DeadmanSwitch;
import com.xrtb.common.Configuration;
public class TestDeadmanSwitch {
@Test
public void testSwitch() throws Exception {
Jedis redis = new Jedis("localhost");
redis.connect();
DeadmanSwitch.testmode = true;
if (Configuration.setPassword() != null)
redis.auth(Configuration.setPassword());
redis.del("deadmanswitch");
DeadmanSwitch d = new DeadmanSwitch("localhost",6379, "deadmanswitch");
Thread.sleep(1000);
assertFalse(d.canRun());
redis.set("deadmanswitch", "ready");
redis.expire("deadmanswitch", 5);
assertTrue(d.canRun());
Thread.sleep(10000);
assertFalse(d.canRun());
}
}
|
Check for db connection or connect | <?php
namespace Purekid\Mongodm\Test\TestCase;
use Phactory\Mongo\Phactory;
use Purekid\Mongodm\MongoDB;
/**
* Test Case Base Class for using Phactory *
*/
abstract class PhactoryTestCase extends \PHPUnit_Framework_TestCase
{
protected static $db;
protected static $phactory;
public static function setUpBeforeClass()
{
MongoDB::setConfigBlock('testing', array(
'connection' => array(
'hostnames' => 'localhost',
'database' => 'test_db'
)
));
MongoDB::instance('testing')->connect();
if (!self::$db || !method_exists(self::$db, 'getDB') || !self::$db->getDB() instanceof MongoDB) {
self::$db = MongoDB::instance('testing');
self::$db->connect();
}
if (!self::$phactory) {
self::$phactory = new Phactory(self::$db->getDB());
self::$phactory->reset();
}
//set up Phactory db connection
self::$phactory->reset();
}
public static function tearDownAfterClass()
{
foreach (self::$db->getDB()->getCollectionNames() as $collection) {
self::$db->getDB()->$collection->drop();
}
}
protected function setUp()
{
}
protected function tearDown()
{
self::$phactory->recall();
}
}
| <?php
namespace Purekid\Mongodm\Test\TestCase;
use Phactory\Mongo\Phactory;
use Purekid\Mongodm\MongoDB;
/**
* Test Case Base Class for using Phactory *
*/
abstract class PhactoryTestCase extends \PHPUnit_Framework_TestCase
{
protected static $db;
protected static $phactory;
public static function setUpBeforeClass()
{
MongoDB::setConfigBlock('testing', array(
'connection' => array(
'hostnames' => 'localhost',
'database' => 'test_db'
)
));
MongoDB::instance('testing')->connect();
if (!self::$db || !method_exists(self::$db, 'getDB') || !self::$db->getDB() instanceof MongoDB) {
self::$db = MongoDB::instance('testing');
}
if (!self::$phactory) {
self::$phactory = new Phactory(self::$db->getDB());
self::$phactory->reset();
}
//set up Phactory db connection
self::$phactory->reset();
}
public static function tearDownAfterClass()
{
foreach (self::$db->getDB()->getCollectionNames() as $collection) {
self::$db->getDB()->$collection->drop();
}
}
protected function setUp()
{
}
protected function tearDown()
{
self::$phactory->recall();
}
}
|
Allow dictGet to have a default value. | package com.github.basking2.sdsai.itrex.packages;
import com.github.basking2.sdsai.itrex.functions.DictFunction;
import com.github.basking2.sdsai.itrex.functions.FunctionInterface;
import java.util.Map;
public class DictPackage {
public static final FunctionInterface<Map<Object, Object>> dict = new DictFunction();
public static final FunctionInterface<Object> dictGet = (args, ctx) -> {
final Map<Object, Object> m = (Map<Object, Object>)args.next();
final Object key = args.next();
if (m.containsKey(key)) {
return m.get(key);
}
else if (args.hasNext()) {
return args.next();
}
else {
return null;
}
};
public static final FunctionInterface<Map<Object, Object>> dictPut = (args, ctx) -> {
final Map<Object, Object> m = (Map<Object, Object>)args.next();
final Object key = args.next();
final Object val = args.next();
m.put(key, val);
return m;
};
}
| package com.github.basking2.sdsai.itrex.packages;
import com.github.basking2.sdsai.itrex.functions.DictFunction;
import com.github.basking2.sdsai.itrex.functions.FunctionInterface;
import java.util.Map;
public class DictPackage {
public static final FunctionInterface<Map<Object, Object>> dict = new DictFunction();
public static final FunctionInterface<Object> dictGet = (args, ctx) -> {
final Map<Object, Object> m = (Map<Object, Object>)args.next();
return m.get(args.next());
};
public static final FunctionInterface<Map<Object, Object>> dictPut = (args, ctx) -> {
final Map<Object, Object> m = (Map<Object, Object>)args.next();
final Object key = args.next();
final Object val = args.next();
m.put(key, val);
return m;
};
}
|
[feat]: Create second view linking to homepage | import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import goHomeActions from 'actions/goHome';
import RaisedButton from 'material-ui/lib/raised-button';
const mapStateToProps = (state) => ({
goHome : state.goHome,
routerState : state.router
});
const mapDispatchToProps = (dispatch) => ({
actions : bindActionCreators(goHomeActions, dispatch)
});
export class ResumeView extends React.Component {
static propTypes = {
actions : React.PropTypes.object
}
render () {
return (
<div className='container'>
<h1>is this thing on?</h1>
<RaisedButton label='This button does nothing' onClick={this.props.actions.goHome} />
<br/>
<br/>
<Link to='/'>but this link will take you back to the counter</Link>
</div>
);
}
}
export default connect(mapStateToProps, mapDispatchToProps)(ResumeView);
| import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import goHomeActions from 'actions/goHome';
import RaisedButton from 'material-ui/lib/raised-button';
const mapStateToProps = (state) => ({
goHome : state.goHome,
routerState : state.router
});
const mapDispatchToProps = (dispatch) => ({
actions : bindActionCreators(goHomeActions, dispatch)
});
export class ResumeView extends React.Component {
static propTypes = {
actions : React.PropTypes.object
}
render () {
return (
<div className='container'>
<h1>is this thing on?</h1>
<RaisedButton secondary={true} label='This button does nothing' onClick={this.props.actions.goHome} />
<br/>
<br/>
<Link to='/'>but this link will take you back to the counter</Link>
</div>
);
}
}
export default connect(mapStateToProps, mapDispatchToProps)(ResumeView);
|
Hide block hover overlay if it's still there when editing a field. | import inlineFieldMixin from 'mixins/inlineFieldMixin';
import imagesLoaded from 'imagesloaded';
import { eventBus } from 'plugins/eventbus';
export default {
props: [
'type',
'index',
'fields',
'other'
],
mixins: [inlineFieldMixin],
data() {
return { ...this.fields };
},
created() {
this.fieldElements = {};
this.watching = {};
this.watchFields(this.fields);
// should only be triggered when all fields are overwitten
this.$watch('fields', () => {
this.watchFields(this.fields);
});
},
methods: {
watchFields(fields) {
Object.keys(fields).map((name) => {
if(!this.watching[name]) {
this.watching[name] = true;
this.$watch(`fields.${name}`, (newVal) => {
if(this.internalChange) {
this.internalChange = false;
return;
}
this[name] = newVal;
eventBus.$emit('block:hideHoverOverlay');
// TODO: use state for this?
imagesLoaded(this.$el, () => {
eventBus.$emit('block:updateBlockOverlays');
});
}, {
deep: true
});
}
});
}
}
};
| import inlineFieldMixin from 'mixins/inlineFieldMixin';
import imagesLoaded from 'imagesloaded';
import { eventBus } from 'plugins/eventbus';
export default {
props: [
'type',
'index',
'fields',
'other'
],
mixins: [inlineFieldMixin],
data() {
return { ...this.fields };
},
created() {
this.fieldElements = {};
this.watching = {};
this.watchFields(this.fields);
// should only be triggered when all fields are overwitten
this.$watch('fields', () => {
this.watchFields(this.fields);
});
},
methods: {
watchFields(fields) {
Object.keys(fields).map((name) => {
if(!this.watching[name]) {
this.watching[name] = true;
this.$watch(`fields.${name}`, (newVal) => {
if(this.internalChange) {
this.internalChange = false;
return;
}
this[name] = newVal;
// TODO: use state for this?
imagesLoaded(this.$el, () => {
eventBus.$emit('block:updateBlockOverlays');
});
}, {
deep: true
});
}
});
}
}
};
|
Add a flush and clear method for batch upload. | /**
* Copyright © 2011-2013 EMBL - European Bioinformatics Institute
*
* 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 uk.ac.ebi.phenotype.dao;
/**
*
* Parent data access manager interface.
*
* @author Gautier Koscielny (EMBL-EBI) <koscieln@ebi.ac.uk>
* @since February 2012
*/
import java.sql.SQLException;
import java.util.Collection;
import org.hibernate.Session;
/**
* Please add a description about HibernateDAO.java
*/
public interface HibernateDAO {
public Session getSession();
public void flushAndClearSession();
@SuppressWarnings("rawtypes")
public Collection executeNativeQuery(String sql) throws SQLException;
}
| /**
* Copyright © 2011-2013 EMBL - European Bioinformatics Institute
*
* 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 uk.ac.ebi.phenotype.dao;
/**
*
* Parent data access manager interface.
*
* @author Gautier Koscielny (EMBL-EBI) <koscieln@ebi.ac.uk>
* @since February 2012
*/
import java.sql.SQLException;
import java.util.Collection;
import org.hibernate.Session;
/**
* Please add a description about HibernateDAO.java
*/
public interface HibernateDAO {
public Session getSession();
@SuppressWarnings("rawtypes")
public Collection executeNativeQuery(String sql) throws SQLException;
}
|
Fix bug OSC-1094 - Incorrect spelling of database | <?php
/*
$Id$
osCommerce, Open Source E-Commerce Solutions
http://www.oscommerce.com
Copyright (c) 2002 osCommerce
Released under the GNU General Public License
*/
define('HEADING_TITLE', 'Server Information');
define('TITLE_SERVER_HOST', 'Server Host:');
define('TITLE_SERVER_OS', 'Server OS:');
define('TITLE_SERVER_DATE', 'Server Date:');
define('TITLE_SERVER_UP_TIME', 'Server Up Time:');
define('TITLE_HTTP_SERVER', 'HTTP Server:');
define('TITLE_PHP_VERSION', 'PHP Version:');
define('TITLE_ZEND_VERSION', 'Zend:');
define('TITLE_DATABASE_HOST', 'Database Host:');
define('TITLE_DATABASE', 'Database:');
define('TITLE_DATABASE_DATE', 'Database Date:');
define('TEXT_EXPORT_INTRO', 'The following information can be submitted to osCommerce by clicking on the Send button. You can also save the information to a file by clicking Save. This information is totally anonymous and cannot be used to identify an individual system. It will be used for support and development purposes only.');
define('TEXT_EXPORT_INFO', 'Export Server Information');
define('SUCCESS_INFO_SUBMIT', 'Your information has been submitted sucessfully.');
define('ERROR_INFO_SUBMIT', 'Could not connect to the osCommerce website to submit your configuration. Please try again later');
?> | <?php
/*
$Id$
osCommerce, Open Source E-Commerce Solutions
http://www.oscommerce.com
Copyright (c) 2002 osCommerce
Released under the GNU General Public License
*/
define('HEADING_TITLE', 'Server Information');
define('TITLE_SERVER_HOST', 'Server Host:');
define('TITLE_SERVER_OS', 'Server OS:');
define('TITLE_SERVER_DATE', 'Server Date:');
define('TITLE_SERVER_UP_TIME', 'Server Up Time:');
define('TITLE_HTTP_SERVER', 'HTTP Server:');
define('TITLE_PHP_VERSION', 'PHP Version:');
define('TITLE_ZEND_VERSION', 'Zend:');
define('TITLE_DATABASE_HOST', 'Database Host:');
define('TITLE_DATABASE', 'Database:');
define('TITLE_DATABASE_DATE', 'Datebase Date:');
define('TEXT_EXPORT_INTRO', 'The following information can be submitted to osCommerce by clicking on the Send button. You can also save the information to a file by clicking Save. This information is totally anonymous and cannot be used to identify an individual system. It will be used for support and development purposes only.');
define('TEXT_EXPORT_INFO', 'Export Server Information');
define('SUCCESS_INFO_SUBMIT', 'Your information has been submitted sucessfully.');
define('ERROR_INFO_SUBMIT', 'Could not connect to the osCommerce website to submit your configuration. Please try again later');
?> |
Migrate worker_main/ to import cross-module
Bug: 1006759
Change-Id: I3b35181af88d569b2d7f803150b9bf147d037510
Reviewed-on: https://chromium-review.googlesource.com/c/devtools/devtools-frontend/+/2019554
Reviewed-by: Paul Lewis <8915f5d5c39a08c5a3e8a8d7314756e4580816f9@chromium.org>
Commit-Queue: Tim van der Lippe <dba8716ee7f8d16236046f74d2167cb94410f6ed@chromium.org> | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import * as Common from '../common/common.js';
import * as Components from '../components/components.js';
import * as MobileThrottling from '../mobile_throttling/mobile_throttling.js';
import * as SDK from '../sdk/sdk.js';
/**
* @implements {Common.Runnable.Runnable}
*/
export class WorkerMainImpl extends Common.ObjectWrapper.ObjectWrapper {
/**
* @override
*/
run() {
SDK.Connections.initMainConnection(() => {
self.SDK.targetManager.createTarget('main', ls`Main`, SDK.SDKModel.Type.ServiceWorker, null);
}, Components.TargetDetachedDialog.TargetDetachedDialog.webSocketConnectionLost);
new MobileThrottling.NetworkPanelIndicator.NetworkPanelIndicator();
}
}
SDK.ChildTargetManager.ChildTargetManager.install(async ({target, waitingForDebugger}) => {
// Only pause the new worker if debugging SW - we are going through the pause on start checkbox.
if (target.parentTarget() || target.type() !== SDK.SDKModel.Type.ServiceWorker || !waitingForDebugger) {
return;
}
const debuggerModel = target.model(SDK.DebuggerModel.DebuggerModel);
if (!debuggerModel) {
return;
}
if (!debuggerModel.isReadyToPause()) {
await debuggerModel.once(SDK.DebuggerModel.Events.DebuggerIsReadyToPause);
}
debuggerModel.pause();
});
| // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @implements {Common.Runnable}
*/
export class WorkerMainImpl extends Common.Object {
/**
* @override
*/
run() {
SDK.initMainConnection(() => {
self.SDK.targetManager.createTarget('main', ls`Main`, SDK.Target.Type.ServiceWorker, null);
}, Components.TargetDetachedDialog.webSocketConnectionLost);
new MobileThrottling.NetworkPanelIndicator();
}
}
SDK.ChildTargetManager.install(async ({target, waitingForDebugger}) => {
// Only pause the new worker if debugging SW - we are going through the pause on start checkbox.
if (target.parentTarget() || target.type() !== SDK.Target.Type.ServiceWorker || !waitingForDebugger) {
return;
}
const debuggerModel = target.model(SDK.DebuggerModel);
if (!debuggerModel) {
return;
}
if (!debuggerModel.isReadyToPause()) {
await debuggerModel.once(SDK.DebuggerModel.Events.DebuggerIsReadyToPause);
}
debuggerModel.pause();
});
|
Split filename only twice (allow ext to contain dots). | #!/usr/bin/env python
import sys
import os
import random
import urllib
import urllib2
import re
# POST_URL = 'http://localhost:8000/domains/'
POST_URL = 'http://scoretool.appspot.com/domains/'
TOP_LEVEL_DOMAINS = 'com net org'.split()
NAMES_PER_REQUEST = 200
def upload(filename):
date, tld, ext = os.path.basename(filename).split('.', 2)
names = []
for line in open(filename):
names.extend(line.split())
while names:
data = {
'names': ' '.join(names[:NAMES_PER_REQUEST]),
'com_expiration': '',
'net_expiration': '',
'org_expiration': '',
'submit_names': 'submit'}
data['%s_expiration' % tld] = date
print data
response = urllib2.urlopen(POST_URL, urllib.urlencode(data))
if len(names) > NAMES_PER_REQUEST:
names = names[NAMES_PER_REQUEST:]
else:
break
if __name__ == '__main__':
for filename in sys.argv[1:]:
upload(filename)
| #!/usr/bin/env python
import sys
import os
import random
import urllib
import urllib2
import re
# POST_URL = 'http://localhost:8000/domains/'
POST_URL = 'http://scoretool.appspot.com/domains/'
TOP_LEVEL_DOMAINS = 'com net org'.split()
NAMES_PER_REQUEST = 200
def upload(filename):
date, tld, ext = os.path.basename(filename).split('.')
names = []
for line in open(filename):
names.extend(line.split())
while names:
data = {
'names': ' '.join(names[:NAMES_PER_REQUEST]),
'com_expiration': '',
'net_expiration': '',
'org_expiration': '',
'submit_names': 'submit'}
data['%s_expiration' % tld] = date
print data
response = urllib2.urlopen(POST_URL, urllib.urlencode(data))
if len(names) > NAMES_PER_REQUEST:
names = names[NAMES_PER_REQUEST:]
else:
break
if __name__ == '__main__':
for filename in sys.argv[1:]:
upload(filename)
|
Allow picking ngrams (list) by cumulative index | // Pick a random ngram weighted by frequency.
function(head, req) {
provides("json", function () {
var allowEmpty = !("nonempty" in req.query);
// Two modes. If chosenIndex is null, read all rows and pick a random
// one. If chosenIndex is a number, read up to the row with that
// cumulative value, and return it.
var chosenNgram = null;
var chosenIndex = req.query.i;
var random = chosenIndex == null;
var total = 0;
var rows = [];
var row;
while (row = getRow()) {
if (allowEmpty || row.key.some(Boolean)) {
total += row.value;
if (random) {
row.cumulative = total;
rows.push(row);
} else if (total > chosenIndex) {
chosenNgram = row.key;
return JSON.stringify(chosenNgram);
}
}
}
chosenIndex = Math.random() * total;
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
if (row.cumulative > chosenIndex) {
chosenNgram = row.key;
break;
}
}
return JSON.stringify(chosenNgram);
});
}
| // Pick a random ngram weighted by frequency.
function(head, req) {
provides("json", function () {
var allowEmpty = !("nonempty" in req.query);
var total = 0;
var rows = [];
var row;
while (row = getRow()) {
if (allowEmpty || row.key.some(Boolean)) {
rows.push(row);
total += row.value;
row.cumulative = total;
}
}
var chosenIndex = Math.random() * total;
var chosenNgram = null;
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
if (row.cumulative > chosenIndex) {
chosenNgram = row.key;
break;
}
}
return JSON.stringify(chosenNgram);
});
}
|
Test that a broken function binding is detected when testing interop, and halts deployment. |
function EmscriptenPrecacheApi(apiPointer, cwrap, runtime) {
var _apiPointer = apiPointer;
var _beginPrecacheOperation = null;
var _cancelPrecacheOperation = null;
var _cancelCallback = null;
var _completeCallback = null;
this.registerCallbacks = function(completeCallback, cancelCallback) {
if (_completeCallback !== null) {
runtime.removeFunction(_completeCallback);
}
_completeCallback = runtime.addFunction(completeCallback);
if (_cancelCallback !== null) {
runtime.removeFunction(_cancelCallback);
}
_cancelCallback = runtime.addFunction(cancelCallback);
};
this.beginPrecacheOperation = function(operationId, operation) {
_beginPrecacheOperation = _beginPrecacheOperation || cwrap("beginPrecacheOperation", null, ["number", "number", "number", "number", "number", "number", "number"]);
var latlong = operation.getCentre();
_beginPrecacheOperation(_apiPointer, operationId, latlong.lat, latlong.lng, operation.getRadius(), _completeCallback, _cancelCallback);
};
this.cancelPrecacheOperation = function(operationId) {
_cancelPrecacheOperation = _cancelPrecacheOperation || cwrap("cancelPrecacheOperation___", null, ["number", "number"]);
_cancelPrecacheOperation(_apiPointer, operationId);
};
}
module.exports = EmscriptenPrecacheApi; |
function EmscriptenPrecacheApi(apiPointer, cwrap, runtime) {
var _apiPointer = apiPointer;
var _beginPrecacheOperation = null;
var _cancelPrecacheOperation = null;
var _cancelCallback = null;
var _completeCallback = null;
this.registerCallbacks = function(completeCallback, cancelCallback) {
if (_completeCallback !== null) {
runtime.removeFunction(_completeCallback);
}
_completeCallback = runtime.addFunction(completeCallback);
if (_cancelCallback !== null) {
runtime.removeFunction(_cancelCallback);
}
_cancelCallback = runtime.addFunction(cancelCallback);
};
this.beginPrecacheOperation = function(operationId, operation) {
_beginPrecacheOperation = _beginPrecacheOperation || cwrap("beginPrecacheOperation", null, ["number", "number", "number", "number", "number", "number", "number"]);
var latlong = operation.getCentre();
_beginPrecacheOperation(_apiPointer, operationId, latlong.lat, latlong.lng, operation.getRadius(), _completeCallback, _cancelCallback);
};
this.cancelPrecacheOperation = function(operationId) {
_cancelPrecacheOperation = _cancelPrecacheOperation || cwrap("cancelPrecacheOperation", null, ["number", "number"]);
_cancelPrecacheOperation(_apiPointer, operationId);
};
}
module.exports = EmscriptenPrecacheApi; |
Exit message: for now, high on the top, will change.
Next step: memory status | // tgotop project main.go
package main
import (
ui "github.com/gizak/termui"
tm "github.com/nsf/termbox-go"
// "time"
)
func main() {
err := ui.Init()
if err != nil {
panic(err)
}
defer ui.Close()
qMess := ui.NewPar(":PRESS q TO QUIT")
qMess.Height = 3
//getting ready to close stuff on command
evt := make(chan tm.Event)
go func() {
for {
evt <- tm.PollEvent()
}
}()
draw := func() {
ui.Render(qMess)
}
ui.Body.AddRows(
ui.NewRow(ui.NewCol(12, 0, qMess)))
ui.Body.Align()
for {
select {
case e := <-evt:
if e.Type == tm.EventKey && e.Ch == 'q' {
return
}
if e.Type == tm.EventResize {
ui.Body.Width = ui.TermWidth()
ui.Body.Align()
}
default:
draw()
}
}
}
| // tgotop project main.go
package main
import (
// proc "github.com/cespare/goproc"
ui "github.com/gizak/termui"
tm "github.com/nsf/termbox-go"
// "time"
)
func main() {
err := ui.Init()
if err != nil {
panic(err)
}
defer ui.Close()
//getting ready to close stuff on command
evt := make(chan tm.Event)
go func() {
for {
evt <- tm.PollEvent()
}
}()
for {
select {
case e := <-evt:
if e.Type == tm.EventKey && e.Ch == 'q' {
return
}
if e.Type == tm.EventResize {
ui.Body.Width = ui.TermWidth()
ui.Body.Align()
}
default:
// draw(i)
}
}
}
|
Update splitEvery test with ES6 syntax | import {assert} from 'chai';
import splitEvery from '../../src/util/split-every.js';
describe('#splitEvery', () => {
it('should split a collection into slices of the specified length', () => {
assert.deepEqual(R.splitEvery(1, [1, 2, 3, 4]), [[1], [2], [3], [4]]);
assert.deepEqual(R.splitEvery(2, [1, 2, 3, 4]), [[1, 2], [3, 4]]);
assert.deepEqual(R.splitEvery(3, [1, 2, 3, 4]), [[1, 2, 3], [4]]);
assert.deepEqual(R.splitEvery(4, [1, 2, 3, 4]), [[1, 2, 3, 4]]);
assert.deepEqual(R.splitEvery(5, [1, 2, 3, 4]), [[1, 2, 3, 4]]);
assert.deepEqual(R.splitEvery(3, []), []);
assert.deepEqual(R.splitEvery(1, 'abcd'), ['a', 'b', 'c', 'd']);
assert.deepEqual(R.splitEvery(2, 'abcd'), ['ab', 'cd']);
assert.deepEqual(R.splitEvery(3, 'abcd'), ['abc', 'd']);
assert.deepEqual(R.splitEvery(4, 'abcd'), ['abcd']);
assert.deepEqual(R.splitEvery(5, 'abcd'), ['abcd']);
assert.deepEqual(R.splitEvery(3, ''), []);
});
});
| import {assert} from 'chai';
import splitEvery from '../../src/util/split-every.js';
describe('#splitEvery', () => {
it('should split a collection into slices of the specified length', function() {
assert.deepEqual(R.splitEvery(1, [1, 2, 3, 4]), [[1], [2], [3], [4]]);
assert.deepEqual(R.splitEvery(2, [1, 2, 3, 4]), [[1, 2], [3, 4]]);
assert.deepEqual(R.splitEvery(3, [1, 2, 3, 4]), [[1, 2, 3], [4]]);
assert.deepEqual(R.splitEvery(4, [1, 2, 3, 4]), [[1, 2, 3, 4]]);
assert.deepEqual(R.splitEvery(5, [1, 2, 3, 4]), [[1, 2, 3, 4]]);
assert.deepEqual(R.splitEvery(3, []), []);
assert.deepEqual(R.splitEvery(1, 'abcd'), ['a', 'b', 'c', 'd']);
assert.deepEqual(R.splitEvery(2, 'abcd'), ['ab', 'cd']);
assert.deepEqual(R.splitEvery(3, 'abcd'), ['abc', 'd']);
assert.deepEqual(R.splitEvery(4, 'abcd'), ['abcd']);
assert.deepEqual(R.splitEvery(5, 'abcd'), ['abcd']);
assert.deepEqual(R.splitEvery(3, ''), []);
});
});
|
Remove assert line from import | # -*- coding: utf-8 -*-
from contextlib import contextmanager
from django.conf import settings
try:
from django.conf.urls.defaults import patterns, url, include
except ImportError:
from django.conf.urls import patterns, url, include # pragma: no cover
from django.core.management.base import BaseCommand
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django.test.client import Client
@contextmanager
def override_urlconf():
has_old = hasattr(settings, 'ROOT_URLCONF')
old = getattr(settings, 'ROOT_URLCONF', None)
settings.ROOT_URLCONF = 'statictemplate.management.commands.statictemplate'
yield
if has_old:
setattr(settings, 'ROOT_URLCONF', old)
else: # pragma: no cover
delattr(settings, 'ROOT_URLCONF')
def make_static(template):
with override_urlconf():
client = Client()
response = client.get('/', {'template': template})
return response.content
class Command(BaseCommand):
def handle(self, template, **options):
output = make_static(template)
self.stdout.write(output)
def render(request):
template_name = request.GET['template']
return render_to_response(template_name, RequestContext(request))
urlpatterns = patterns('',
url('^$', render),
url('^others', include(settings.ROOT_URLCONF))
)
| # -*- coding: utf-8 -*-
from contextlib import contextmanager
from django.conf import settings
try:
from django.conf.urls.defaults import patterns, url, include
assert all((patterns, url, include))
except ImportError:
from django.conf.urls import patterns, url, include # pragma: no cover
from django.core.management.base import BaseCommand
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django.test.client import Client
@contextmanager
def override_urlconf():
has_old = hasattr(settings, 'ROOT_URLCONF')
old = getattr(settings, 'ROOT_URLCONF', None)
settings.ROOT_URLCONF = 'statictemplate.management.commands.statictemplate'
yield
if has_old:
setattr(settings, 'ROOT_URLCONF', old)
else: # pragma: no cover
delattr(settings, 'ROOT_URLCONF')
def make_static(template):
with override_urlconf():
client = Client()
response = client.get('/', {'template': template})
return response.content
class Command(BaseCommand):
def handle(self, template, **options):
output = make_static(template)
self.stdout.write(output)
def render(request):
template_name = request.GET['template']
return render_to_response(template_name, RequestContext(request))
urlpatterns = patterns('',
url('^$', render),
url('^others', include(settings.ROOT_URLCONF))
)
|
Add a "modified" property that will only be updated when the entity is actually updated. | from datetime import datetime, timedelta
from google.appengine.ext import db
class CHPIncident(db.Model):
CenterID = db.StringProperty(required=True)
DispatchID = db.StringProperty(required=True)
LogID = db.StringProperty(required=True)
LogTime = db.DateTimeProperty()
LogType = db.StringProperty()
LogTypeID = db.StringProperty()
Location = db.StringProperty()
Area = db.StringProperty()
ThomasBrothers = db.StringProperty()
TBXY = db.StringProperty()
LogDetails = db.BlobProperty()
geolocation = db.GeoPtProperty()
created = db.DateTimeProperty(auto_now_add=True)
updated = db.DateTimeProperty(auto_now=True)
modified = db.DateTimeProperty()
def getStatus(self):
if self.created > datetime.utcnow() - timedelta(minutes=5):
# less than 5 min old == new
return 'new'
elif self.updated < datetime.utcnow() - timedelta(minutes=5):
# not updated in 5 min == inactive
return 'inactive'
else:
return 'active'
| from datetime import datetime, timedelta
from google.appengine.ext import db
class CHPIncident(db.Model):
CenterID = db.StringProperty(required=True)
DispatchID = db.StringProperty(required=True)
LogID = db.StringProperty(required=True)
LogTime = db.DateTimeProperty()
LogType = db.StringProperty()
LogTypeID = db.StringProperty()
Location = db.StringProperty()
Area = db.StringProperty()
ThomasBrothers = db.StringProperty()
TBXY = db.StringProperty()
LogDetails = db.BlobProperty()
geolocation = db.GeoPtProperty()
created = db.DateTimeProperty(auto_now_add=True)
updated = db.DateTimeProperty(auto_now=True)
def getStatus(self):
if self.created > datetime.utcnow() - timedelta(minutes=5):
# less than 5 min old == new
return 'new'
elif self.updated < datetime.utcnow() - timedelta(minutes=5):
# not updated in 5 min == inactive
return 'inactive'
else:
return 'active'
|
Fix value of max. width ('neatMaxWidth') used by postcss-neat | module.exports = {
plugins: [
require('postcss-import'),
require('postcss-css-reset'),
require('postcss-custom-properties'),
require('postcss-extend'),
require('postcss-nested'),
require('postcss-color-function'),
require('postcss-button'),
require('postcss-inline-svg'),
require('postcss-svgo'),
require('postcss-flexbox'),
require('postcss-neat')({
neatMaxWidth: '1200px'
}),
require('postcss-extend'),
require('postcss-custom-media'),
require('postcss-media-minmax'),
require('postcss-cssnext')({
browsers: [
'last 2 versions',
'ie >= 10'
]
}),
require('cssnano')({
autoprefixer: false, // already prefixed w/ cssnext
save: true,
core: true,
sourcemap: true
})
]
};
| module.exports = {
plugins: [
require('postcss-import'),
require('postcss-css-reset'),
require('postcss-custom-properties'),
require('postcss-extend'),
require('postcss-nested'),
require('postcss-color-function'),
require('postcss-button'),
require('postcss-inline-svg'),
require('postcss-svgo'),
require('postcss-flexbox'),
require('postcss-neat')({
neatMaxWidth: '960px'
}),
require('postcss-extend'),
require('postcss-custom-media'),
require('postcss-media-minmax'),
require('postcss-cssnext')({
browsers: [
'last 2 versions',
'ie >= 10'
]
}),
require('cssnano')({
autoprefixer: false, // already prefixed w/ cssnext
save: true,
core: true,
sourcemap: true
})
]
};
|
Remove unused params from comments. | import { toArray, Class } from './lib/objects';
import { normalizeOperations } from './lib/operations';
import { uuid } from './lib/uuid';
/**
Transforms represent a set of operations that are applied against a
source. After a transform has been applied, it should be assigned the
`result`, a `TransformResult` that represents the result of the transform.
Transforms are automatically assigned a UUID `id`.
@class Transform
@namespace Orbit
@param {Array} [operations] Operations to apply
@param {Object} [options]
@param {String} [options.id] Unique id for this transform (will be assigned a uuid by default)
@constructor
*/
var Transform = Class.extend({
operations: null,
init: function(ops, options) {
this.operations = normalizeOperations( toArray(ops) );
options = options || {};
this.id = options.id || uuid();
},
isEmpty: function() {
return this.operations.length === 0;
}
});
export default Transform;
| import { toArray, Class } from './lib/objects';
import { normalizeOperations } from './lib/operations';
import { uuid } from './lib/uuid';
/**
Transforms represent a set of operations that are applied against a
source. After a transform has been applied, it should be assigned the
`result`, a `TransformResult` that represents the result of the transform.
Transforms are automatically assigned a UUID `id`.
@class Transform
@namespace Orbit
@param {Array} [operations] Operations to apply
@param {Object} [options]
@param {String} [options.id] Unique id for this transform (will be assigned a uuid by default)
@param {Transform} [options.parent] The parent transform that spawned this one.
@param {Array} [options.log]
@constructor
*/
var Transform = Class.extend({
operations: null,
init: function(ops, options) {
this.operations = normalizeOperations( toArray(ops) );
options = options || {};
this.id = options.id || uuid();
},
isEmpty: function() {
return this.operations.length === 0;
}
});
export default Transform;
|
Add fields to the project model. | <?php
class Project extends Eloquent {
protected $fillable = ['title', 'slug', 'closed_statuses', 'workboard_mode'];
/**
* @return \Illuminate\Database\Eloquent\Collection
*/
public function sprints()
{
return $this->hasMany('Sprint')->orderBy('sprint_start', 'desc');
}
/**
* @return \Illuminate\Validation\Validator
*/
public function validate()
{
return Validator::make(
$this->getAttributes(),
['title' => 'required|unique:projects'],
['unique' => 'A project with this title already exists.']
);
}
public function currentSprint()
{
return $this->newestPastSprint() ?: $this->closestFutureSprint();
}
private function newestPastSprint()
{
return Sprint::where('sprint_start', '<=', date('Y-m-d'))
->where('project_id', $this->id)
->orderBy('sprint_start', 'desc')
->first();
}
private function closestFutureSprint()
{
return Sprint::where('sprint_start', '>', date('Y-m-d'))
->where('project_id', $this->id)
->orderBy('sprint_start', 'asc')
->first();
}
}
| <?php
class Project extends Eloquent {
protected $fillable = ['title', 'slug'];
/**
* @return \Illuminate\Database\Eloquent\Collection
*/
public function sprints()
{
return $this->hasMany('Sprint')->orderBy('sprint_start', 'desc');
}
/**
* @return \Illuminate\Validation\Validator
*/
public function validate()
{
return Validator::make(
$this->getAttributes(),
['title' => 'required|unique:projects'],
['unique' => 'A project with this title already exists.']
);
}
public function currentSprint()
{
return $this->newestPastSprint() ?: $this->closestFutureSprint();
}
private function newestPastSprint()
{
return Sprint::where('sprint_start', '<=', date('Y-m-d'))
->where('project_id', $this->id)
->orderBy('sprint_start', 'desc')
->first();
}
private function closestFutureSprint()
{
return Sprint::where('sprint_start', '>', date('Y-m-d'))
->where('project_id', $this->id)
->orderBy('sprint_start', 'asc')
->first();
}
}
|
Split validation checks for more precise error output | <?php
namespace Archibald;
use Archibald\Request;
class Api
{
private $slashToken = SLASHCOMMAND_TOKEN;
private $commandName = '/archie';
public function __construct($request)
{
if ($request['token'] && $request['command']) {
$token = $request['token'];
$command = $request['command'];
if ($this->isValidToken($token)) {
if ($this->isValidCommand($command)) {
$data = array(
'team_id' => $request['team_id'],
'channel' => $request['channel_id'],
'user_id' => $request['user_id'],
'user' => $request['user_name'],
'body' => $request['text']
);
$request = new Request($data);
}
else {
echo 'Invalid Command';
}
}
else {
echo 'Invalid Slash Command Token. Please check your config!';
}
}
else {
echo 'No valid API call.';
}
}
private function isValidToken($token)
{
return $token == $this->slashToken;
}
private function isValidCommand($command)
{
return $command == $this->commandName;
}
}
| <?php
namespace Archibald;
use Archibald\Request;
class Api
{
private $slashToken = SLASHCOMMAND_TOKEN;
private $commandName = '/archie';
public function __construct($request)
{
if ($request['token'] && $request['command']) {
$token = $request['token'];
$command = $request['command'];
if ($this->isValidToken($token) && $this->isValidCommand($command)) {
$data = array(
'team_id' => $request['team_id'],
'channel' => $request['channel_id'],
'user_id' => $request['user_id'],
'user' => $request['user_name'],
'body' => $request['text']
);
$request = new Request($data);
}
else {
echo 'Invalid Token or Command';
}
}
else {
echo 'No valid API call.';
}
}
private function isValidToken($token)
{
return $token == $this->slashToken;
}
private function isValidCommand($command)
{
return $command == $this->commandName;
}
}
|
Optimize react dev entry point | // Licensed under the Apache License, Version 2.0 (the “License”); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an “AS IS” BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
import App from 'App'
import ErrorBoundary from './ErrorBoundary'
import React from 'react'
import {render} from 'react-dom'
const HTML_ROOT = document.getElementById('app')
if (module.hot) {
let {AppContainer} = import('react-hot-loader')
window.addEventListener('load', () => {
render(
<AppContainer>
<ErrorBoundary>
<App/>
</ErrorBoundary>
</AppContainer>,
HTML_ROOT,
)
})
module.hot.accept('App', () => {
let ReloadedApp = require('App').default
render(
<AppContainer>
<ErrorBoundary>
<ReloadedApp/>
</ErrorBoundary>
</AppContainer>,
HTML_ROOT,
)
})
} else {
window.addEventListener('load', () => {
render(
<ErrorBoundary>
<App/>
</ErrorBoundary>,
HTML_ROOT,
)
})
}
| // Licensed under the Apache License, Version 2.0 (the “License”); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an “AS IS” BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
import App from 'App'
import ErrorBoundary from './ErrorBoundary'
import React from 'react'
import {AppContainer} from 'react-hot-loader'
import {render} from 'react-dom'
const HTML_ROOT = document.getElementById('app')
// Enable hot reloading.
if (module.hot) {
module.hot.accept('App', () => {
let ReloadedApp = require('App').default
render(
<AppContainer>
<ErrorBoundary>
<ReloadedApp/>
</ErrorBoundary>
</AppContainer>,
HTML_ROOT,
)
})
}
// Render the page after all resources load.
window.addEventListener('load', () => {
render(
<AppContainer>
<ErrorBoundary>
<App/>
</ErrorBoundary>
</AppContainer>,
HTML_ROOT,
)
})
|
Add loads-dumps test for Appinfo | import io
import os
import pickle
import pytest
from steamfiles import appinfo
test_file_name = os.path.join(os.path.dirname(__file__), 'test_data/appinfo.vdf')
@pytest.yield_fixture
def vdf_data():
with open(test_file_name, 'rb') as f:
yield f.read()
@pytest.mark.usefixtures('vdf_data')
def test_loads_dumps(vdf_data):
assert appinfo.dumps(appinfo.loads(vdf_data)) == vdf_data
@pytest.mark.usefixtures('vdf_data')
def test_load_dump(vdf_data):
with open(test_file_name, 'rb') as in_file:
out_file = io.BytesIO()
obj = appinfo.load(in_file)
appinfo.dump(obj, out_file)
# Rewind to the beginning
out_file.seek(0)
assert out_file.read() == vdf_data
def test_loads_wrong_type():
with pytest.raises(TypeError):
appinfo.loads('JustTestData')
| import io
import os
import pickle
import pytest
from steamfiles import appinfo
test_file_name = os.path.join(os.path.dirname(__file__), 'test_data/appinfo.vdf')
@pytest.yield_fixture
def vdf_data():
with open(test_file_name, 'rb') as f:
yield f.read()
@pytest.mark.usefixtures('vdf_data')
def test_load_dump(vdf_data):
with open(test_file_name, 'rb') as in_file:
out_file = io.BytesIO()
obj = appinfo.load(in_file)
appinfo.dump(obj, out_file)
# Rewind to the beginning
out_file.seek(0)
assert out_file.read() == vdf_data
def test_loads_wrong_type():
with pytest.raises(TypeError):
appinfo.loads('JustTestData')
|
Remove a misleading log message. | // Manage the SHA of the latest control repository commit.
var restify = require('restify');
var storage = require('../storage');
var log = require('../logging').getLogger();
exports.store = function (req, res, next) {
if (req.params.sha === undefined) {
return next(new restify.InvalidContentError('Missing required "sha" attribute'));
}
if (!/[0-9a-fA-F]{40}/.test(req.params.sha)) {
return next(new restify.InvalidContentError('Not a valid "sha"'));
}
storage.storeSHA(req.params.sha, function (err) {
next.ifError(err);
res.send(204);
log.info('Stored control repository SHA', {
sha: req.params.sha
});
next();
});
};
exports.retrieve = function (req, res, next) {
storage.getSHA(function (err, sha) {
next.ifError(err);
res.json(200, {sha: sha});
next();
});
};
| // Manage the SHA of the latest control repository commit.
var restify = require('restify');
var storage = require('../storage');
var log = require('../logging').getLogger();
exports.store = function (req, res, next) {
if (req.params.sha === undefined) {
return next(new restify.InvalidContentError('Missing required "sha" attribute'));
}
if (!/[0-9a-fA-F]{40}/.test(req.params.sha)) {
return next(new restify.InvalidContentError('Not a valid "sha"'));
}
storage.storeSHA(req.params.sha, function (err) {
next.ifError(err);
res.send(204);
log.info('Stored control repository SHA', {
sha: req.params.sha
});
next();
});
};
exports.retrieve = function (req, res, next) {
storage.getSHA(function (err, sha) {
next.ifError(err);
res.json(200, {sha: sha});
log.info('Got control repository SHA', {
sha: sha
});
next();
});
};
|
[fix] Adjust to the new layout | pipe.once('package:initialize', function (pagelet) {
'use strict';
//
// We don't need to have any other information from the pagelet then the
// placeholders/elements that contain our packages-pagelet placeholders.
//
pagelet = $(pagelet.placeholders);
//
// Show more rows when we click on the table footer.
//
pagelet.on('click', '.details .show-all', function click(e) {
if (!~this.href.indexOf('#')) return; // We have a dependencies pagelet.
e.preventDefault();
var element = $(this)
, text = element.text()
, state = element.data('state')
, parent = element.parents('.sixcol');
//
// Show the rows that were hidden and remove the table foot as we're already
// showing all the fields now.
//
parent.find('.gone')[state ? 'fadeOut' : 'fadeIn']();
element.text(element.data('text')).data('text', text).data('state', !state);
});
});
| pipe.once('package:initialize', function (pagelet) {
'use strict';
//
// We don't need to have any other information from the pagelet then the
// placeholders/elements that contain our packages-pagelet placeholders.
//
pagelet = $(pagelet.placeholders);
//
// Show more rows when we click on the table footer.
//
pagelet.on('click', '.details .show-all', function click(e) {
if (!~this.href.indexOf('#')) return; // We have a dependencies pagelet.
e.preventDefault();
var element = $(this)
, text = element.text()
, state = element.data('state')
, parent = element.parents('.fourcol');
//
// Show the rows that were hidden and remove the table foot as we're already
// showing all the fields now.
//
parent.find('.gone')[state ? 'fadeOut' : 'fadeIn']();
element.text(element.data('text')).data('text', text).data('state', !state);
});
});
|
Allow hyphens in page ID | from markdown import markdown
import bleach
import re
from werkzeug.exceptions import NotFound
from . import consts as c
def md2html(md: str):
allowed_tags = ('a', 'abbr', 'acronym', 'b', 'blockquote', 'code', 'em', 'i', 'li', 'ol', 'pre', 'strong', 'ul',
'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'table', 'tr', 'td', 'thead', 'tbody', 'th', 'sub', 'sup',
'del')
return bleach.linkify(bleach.clean(markdown(md, output_format='html'), tags=allowed_tags, strip=True))
def check_pid(pid):
return _pid_check_re.match(pid) is not None and len(pid) < c.PID_MAX_LENGTH
_pid_check_re = re.compile('^[-A-Za-z0-9_]+$')
def check_pid_or_404(pid):
if not check_pid(pid):
raise NotFound
| from markdown import markdown
import bleach
import re
from werkzeug.exceptions import NotFound
from . import consts as c
def md2html(md: str):
allowed_tags = ('a', 'abbr', 'acronym', 'b', 'blockquote', 'code', 'em', 'i', 'li', 'ol', 'pre', 'strong', 'ul',
'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'table', 'tr', 'td', 'thead', 'tbody', 'th', 'sub', 'sup',
'del')
return bleach.linkify(bleach.clean(markdown(md, output_format='html'), tags=allowed_tags, strip=True))
def check_pid(pid):
return _pid_check_re.match(pid) is not None and len(pid) < c.PID_MAX_LENGTH
_pid_check_re = re.compile('^[A-Za-z0-9_]+$')
def check_pid_or_404(pid):
if not check_pid(pid):
raise NotFound
|
Fix legacy use of action result | #!/usr/bin/env python
#
# Delete all secure policies.
#
import os
import sys
import json
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..'))
from sdcclient import SdSecureClient
def usage():
print('usage: %s <sysdig-token>' % sys.argv[0])
print('You can find your token at https://secure.sysdig.com/#/settings/user')
sys.exit(1)
#
# Parse arguments
#
if len(sys.argv) != 2:
usage()
sdc_token = sys.argv[1]
#
# Instantiate the SDC client
#
sdclient = SdSecureClient(sdc_token, 'https://secure.sysdig.com')
# Get a list of policyIds
ok, res = sdclient.list_policies()
policies = []
if not ok:
print(res)
sys.exit(1)
else:
policies = res['policies']
for policy in policies:
print("deleting policy: " + str(policy['id']))
ok, res = sdclient.delete_policy_id(policy['id'])
if not ok:
print(res)
sys.exit(1)
| #!/usr/bin/env python
#
# Delete all secure policies.
#
import os
import sys
import json
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..'))
from sdcclient import SdSecureClient
def usage():
print('usage: %s <sysdig-token>' % sys.argv[0])
print('You can find your token at https://secure.sysdig.com/#/settings/user')
sys.exit(1)
#
# Parse arguments
#
if len(sys.argv) != 2:
usage()
sdc_token = sys.argv[1]
#
# Instantiate the SDC client
#
sdclient = SdSecureClient(sdc_token, 'https://secure.sysdig.com')
# Get a list of policyIds
ok, res = sdclient.list_policies()
policies = []
if not ok:
print(res)
sys.exit(1)
else:
policies = res[1]['policies']
for policy in policies:
print("deleting policy: " + str(policy['id']))
ok, res = sdclient.delete_policy_id(policy['id'])
if not ok:
print(res)
sys.exit(1)
|
Add python3 support for nosetests | import os
import sys
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.md')).read()
sys.path.insert(0, here)
from titlecase import __version__
setup(name='titlecase',
version=__version__,
description="Python Port of John Gruber's titlecase.pl",
long_description=README,
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Programming Language :: Python",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Topic :: Text Processing :: Filters",
],
keywords='string formatting',
author="Stuart Colville",
author_email="pypi@muffinresearch.co.uk",
url="http://muffinresearch.co.uk/",
license="MIT",
packages=find_packages(),
include_package_data=True,
zip_safe=False,
tests_require=['nose'],
setup_requires=['nose>=1.0'],
test_suite="titlecase.tests",
entry_points = """\
"""
)
| import os
import sys
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.md')).read()
sys.path.insert(0, here)
from titlecase import __version__
setup(name='titlecase',
version=__version__,
description="Python Port of John Gruber's titlecase.pl",
long_description=README,
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Programming Language :: Python",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Topic :: Text Processing :: Filters",
],
keywords='string formatting',
author="Stuart Colville",
author_email="pypi@muffinresearch.co.uk",
url="http://muffinresearch.co.uk/",
license="MIT",
packages=find_packages(),
include_package_data=True,
zip_safe=False,
tests_require=['nose'],
test_suite="titlecase.tests",
entry_points = """\
"""
)
|
Add comment to clarify fixture for repliedArticleCount | export default {
'/users/doc/test-user': {
id: 'test-user',
name: 'test user',
email: 'secret@secret.com',
},
'/users/doc/current-user': {
id: 'current-user',
name: 'current user',
email: 'hi@me.com',
},
'/articles/doc/some-doc': {
articleReplies: [
// replies to the same doc only count as 1 for repliedArticleCount
{ status: 'NORMAL', appId: 'WEBSITE', userId: 'current-user' },
{ status: 'NORMAL', appId: 'WEBSITE', userId: 'current-user' },
],
},
'/articles/doc/another-doc': {
articleReplies: [
{ status: 'NORMAL', appId: 'WEBSITE', userId: 'current-user' },
],
},
'/articles/doc/not-this-doc': {
articleReplies: [
{ status: 'DELETED', appId: 'WEBSITE', userId: 'current-user' },
],
},
};
| export default {
'/users/doc/test-user': {
id: 'test-user',
name: 'test user',
email: 'secret@secret.com',
},
'/users/doc/current-user': {
id: 'current-user',
name: 'current user',
email: 'hi@me.com',
},
'/articles/doc/some-doc': {
articleReplies: [
{ status: 'NORMAL', appId: 'WEBSITE', userId: 'current-user' },
{ status: 'NORMAL', appId: 'WEBSITE', userId: 'current-user' },
],
},
'/articles/doc/another-doc': {
articleReplies: [
{ status: 'NORMAL', appId: 'WEBSITE', userId: 'current-user' },
],
},
'/articles/doc/not-this-doc': {
articleReplies: [
{ status: 'DELETED', appId: 'WEBSITE', userId: 'current-user' },
],
},
};
|
Package classifiers: Explicitly target Python 2.7 | #!/usr/bin/env python
from distutils.core import setup
setup(
name='django-payfast',
version='0.2.2',
author='Mikhail Korobov',
author_email='kmike84@gmail.com',
packages=['payfast', 'payfast.south_migrations'],
url='http://bitbucket.org/kmike/django-payfast/',
download_url = 'http://bitbucket.org/kmike/django-payfast/get/tip.gz',
license = 'MIT license',
description = 'A pluggable Django application for integrating payfast.co.za payment system.',
long_description = open('README.rst').read().decode('utf8'),
classifiers=(
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Libraries :: Python Modules',
),
)
| #!/usr/bin/env python
from distutils.core import setup
setup(
name='django-payfast',
version='0.2.2',
author='Mikhail Korobov',
author_email='kmike84@gmail.com',
packages=['payfast', 'payfast.south_migrations'],
url='http://bitbucket.org/kmike/django-payfast/',
download_url = 'http://bitbucket.org/kmike/django-payfast/get/tip.gz',
license = 'MIT license',
description = 'A pluggable Django application for integrating payfast.co.za payment system.',
long_description = open('README.rst').read().decode('utf8'),
classifiers=(
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
),
)
|
Fix directory tests, __file__ may return relative path and now it is
taken into consideration | import unittest
import tempfile
import os
from os import path
from shellpython.helpers import Dir
class TestDirectory(unittest.TestCase):
def test_relative_dirs(self):
cur_dir = path.dirname(path.abspath(__file__))
with Dir(path.join(cur_dir, 'data')):
self.assertEqual(path.join(cur_dir, 'data'), os.getcwd())
with Dir(path.join('locator')):
self.assertEqual(path.join(cur_dir, 'data', 'locator'), os.getcwd())
def test_absolute_dirs(self):
with Dir(tempfile.gettempdir()):
self.assertEqual(tempfile.gettempdir(), os.getcwd())
| import unittest
import tempfile
import os
from shellpython.helpers import Dir
class TestDirectory(unittest.TestCase):
def test_relative_dirs(self):
cur_dir = os.path.split(__file__)[0]
with Dir(os.path.join(cur_dir, 'data')):
self.assertEqual(os.path.join(cur_dir, 'data'), os.getcwd())
with Dir(os.path.join('locator')):
self.assertEqual(os.path.join(cur_dir, 'data', 'locator'), os.getcwd())
def test_absolute_dirs(self):
with Dir(tempfile.gettempdir()):
self.assertEqual(tempfile.gettempdir(), os.getcwd())
|
Make Elron provider count live time (api) | const got = require('got');
const cache = require('../utils/cache.js');
const time = require('../utils/time.js');
// Get trips for stop.
async function getTrips(id) {
const now = time.getSeconds();
const trips = JSON.parse((await got(`http://elron.ee/api/v1/stop?stop=${encodeURIComponent(id)}`)).body).data;
if (!trips) throw new Error("Provider 'Elron' is not returning data");
if (trips.text) throw new Error(trips.text);
// Show not arrived trips until 30 minutes of being late.
return trips.filter((trip) => !trip.tegelik_aeg).map((trip) => ({
time: time.toSeconds(trip.plaaniline_aeg),
countdown: time.toSeconds(trip.plaaniline_aeg) - now,
name: trip.reis,
destination: trip.liin,
type: 'train',
live: false,
provider: 'elron'
})).filter((trip) => now - trip.time < 1800).slice(0, 15);
}
module.exports = {
getTrips
};
| const got = require('got');
const cache = require('../utils/cache.js');
const time = require('../utils/time.js');
// Get trips for stop.
async function getTrips(id) {
const now = time.getSeconds();
return (await cache.use('elron-trips', id, async () => {
const data = JSON.parse((await got(`http://elron.ee/api/v1/stop?stop=${encodeURIComponent(id)}`)).body).data;
if (!data) throw new Error("Provider 'Elron' is not returning data");
if (data.text) throw new Error(data.text);
return data.map((trip) => ({
time: time.toSeconds(trip.plaaniline_aeg),
countdown: time.toSeconds(trip.plaaniline_aeg) - now,
name: trip.reis,
destination: trip.liin,
type: 'train',
live: false,
provider: 'elron'
}));
})).filter((trip) => trip.time > now).slice(0, 15);
}
module.exports = {
getTrips
};
|
Move greeting and invocation of sub generators to methods | "use strict";
var yeoman = require("yeoman-generator");
var incSay = require("incubator-say");
var util = require("util");
var path = require("path");
var IncubatorGenerator = module.exports = function IncubatorGenerator () {
yeoman.generators.Base.apply(this, arguments);
this.argument("appname", { type : String, required : false });
this.appname = this.appname || path.basename(process.cwd());
this.appname = this._.camelize(this._.slugify(this._.humanize(this.appname)));
this.option("skip-welcome-message", {
desc : "Do not print out the welcome message.",
type : Boolean
});
this.option("skip-core", {
desc : "Skip core installation.",
type : Boolean
});
};
util.inherits(IncubatorGenerator, yeoman.generators.Base);
IncubatorGenerator.prototype.greeting = function greeting () {
if (!this.options["skip-welcome-message"]) {
this.log(incSay("Welcome to the Incubator Generator!"));
this.log("By default I will create a Gruntfile and all dotfiles required to work");
this.log("with the Bandwidth Incubator build pipeline.");
this.log();
}
};
IncubatorGenerator.prototype.components = function components () {
if (!this.options["skip-core"]) {
this.invoke("incubator:core", this.args);
}
}; | "use strict";
var yeoman = require("yeoman-generator");
var incSay = require("incubator-say");
var util = require("util");
var path = require("path");
var IncubatorGenerator = module.exports = function IncubatorGenerator (args) {
yeoman.generators.Base.apply(this, arguments);
this.argument("appname", { type : String, required : false });
this.appname = this.appname || path.basename(process.cwd());
this.appname = this._.camelize(this._.slugify(this._.humanize(this.appname)));
this.option("skip-welcome-message", {
desc : "Do not print out the welcome message.",
type : Boolean,
defaults : true
});
this.option("skip-core", {
desc : "Skip core installation.",
type : Boolean,
defaults : true
});
if (!this.options["skip-welcome-message"]) {
this.log(incSay("Welcome to the Incubator Generator!"));
this.log("By default I will create a Gruntfile and all dotfiles required to work");
this.log("with the Bandwidth Incubator build pipeline.");
this.log();
}
if (!this.options["skip-core"]) {
this.invoke("incubator:core", args);
}
};
util.inherits(IncubatorGenerator, yeoman.generators.Base); |
Use double quotes on "use strict" | #!/usr/bin/env node
"use strict";
const moment = require("moment");
const sugar = require("sugar");
const chalk = require("chalk");
const exec = require("child_process").exec;
process.argv.splice(0, 2);
if (process.argv.length > 0) {
// Attempt to parse the date
let date = process.argv.join(" ");
let parsedDate = new sugar.Date.create(date);
if (parsedDate != "Invalid Date") {
// Date could be parsed, parse the date to git date format
let dateString = moment(parsedDate).format("ddd MMM DD HH:mm:ss YYYY ZZ");
// Actually modify the dates
let command = "GIT_COMMITTER_DATE=\"" + dateString + "\" git commit --amend --date=\"" + dateString + "\" --no-edit";
exec(command, (err, stdout, stderr) => {
if (err) {
console.log("fatal: Could not change the previous commit");
} else {
console.log("\nModified previous commit:\n\tAUTHOR_DATE " + chalk.grey(dateString) + "\n\tCOMMITTER_DATE " + chalk.grey(dateString) + "\n\nCommand executed:\n\t" + chalk.bgWhite.black(command) + "\n");
}
});
} else {
console.log("fatal: Could not parse \"" + date + "\" into a valid date");
}
} else {
console.log("fatal: No date string given");
}
| #!/usr/bin/env node
'use strict';
const moment = require("moment");
const sugar = require("sugar");
const chalk = require("chalk");
const exec = require("child_process").exec;
process.argv.splice(0, 2);
if (process.argv.length > 0) {
// Attempt to parse the date
let date = process.argv.join(" ");
let parsedDate = new sugar.Date.create(date);
if (parsedDate != "Invalid Date") {
// Date could be parsed, parse the date to git date format
let dateString = moment(parsedDate).format("ddd MMM DD HH:mm:ss YYYY ZZ");
// Actually modify the dates
let command = "GIT_COMMITTER_DATE=\"" + dateString + "\" git commit --amend --date=\"" + dateString + "\" --no-edit";
exec(command, (err, stdout, stderr) => {
if (err) {
console.log("fatal: Could not change the previous commit");
} else {
console.log("\nModified previous commit:\n\tAUTHOR_DATE " + chalk.grey(dateString) + "\n\tCOMMITTER_DATE " + chalk.grey(dateString) + "\n\nCommand executed:\n\t" + chalk.bgWhite.black(command) + "\n");
}
});
} else {
console.log("fatal: Could not parse \"" + date + "\" into a valid date");
}
} else {
console.log("fatal: No date string given");
}
|
Fix local ban permission node | package com.mcbans.firestar.mcbans;
import com.mcbans.firestar.mcbans.permission.Perms;
public enum BanType {
GLOBAL ("globalBan", Perms.BAN_GLOBAL),
LOCAL ("localBan", Perms.BAN_LOCAL),
TEMP ("tempBan", Perms.BAN_TEMP),
UNBAN ("unBan", Perms.UNBAN),
;
final private String actionName;
final private Perms permission;
private BanType(final String actionName, final Perms permission){
this.actionName = actionName;
this.permission = permission;
}
public String getActionName(){
return this.actionName;
}
public Perms getPermission(){
return this.permission;
}
}
| package com.mcbans.firestar.mcbans;
import com.mcbans.firestar.mcbans.permission.Perms;
public enum BanType {
GLOBAL ("globalBan", Perms.BAN_GLOBAL),
LOCAL ("localBan", Perms.BAN_GLOBAL),
TEMP ("tempBan", Perms.BAN_TEMP),
UNBAN ("unBan", Perms.UNBAN),
;
final private String actionName;
final private Perms permission;
private BanType(final String actionName, final Perms permission){
this.actionName = actionName;
this.permission = permission;
}
public String getActionName(){
return this.actionName;
}
public Perms getPermission(){
return this.permission;
}
}
|
Fix bug on Windows in the edit command | <?php namespace Laravel\Homestead;
use Symfony\Component\Process\Process;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class EditCommand extends Command {
/**
* Configure the command options.
*
* @return void
*/
protected function configure()
{
$this->setName('edit')
->setDescription('Edit the Homestead.yaml file');
}
/**
* Find the correct executable to run depending of the OS.
*
* @return string
*/
protected function executableName()
{
return strpos(strtoupper(PHP_OS), 'WIN') === 0 ? 'start' : 'open';
}
/**
* Execute the command.
*
* @param \Symfony\Component\Console\Input\InputInterface $input
* @param \Symfony\Component\Console\Output\OutputInterface $output
* @return void
*/
public function execute(InputInterface $input, OutputInterface $output)
{
$commandLine = $this->executableName() .' '.homestead_path().'/Homestead.yaml';
$process = new Process($commandLine, realpath(__DIR__.'/../'), null, null, null);
$process->run(function($type, $line) use ($output)
{
$output->write($line);
});
}
}
| <?php namespace Laravel\Homestead;
use Symfony\Component\Process\Process;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class EditCommand extends Command {
/**
* Configure the command options.
*
* @return void
*/
protected function configure()
{
$this->setName('edit')
->setDescription('Edit the Homestead.yaml file');
}
/**
* Execute the command.
*
* @param \Symfony\Component\Console\Input\InputInterface $input
* @param \Symfony\Component\Console\Output\OutputInterface $output
* @return void
*/
public function execute(InputInterface $input, OutputInterface $output)
{
$process = new Process('open ~/.homestead/Homestead.yaml', realpath(__DIR__.'/../'), null, null, null);
$process->run(function($type, $line) use ($output)
{
$output->write($line);
});
}
}
|
Adjust test (refers prev commit) | # -*- coding: utf-8 -*-
from django.test import TestCase
from bakery.auth.models import BakeryUser
class TestBakeryUserModel(TestCase):
def test_get_absolute_url(self):
user = BakeryUser.objects.create_user('user', 'password')
user.name = 'John Doe'
self.assertEqual(user.get_absolute_url(), '/profile/user/')
def test_get_full_name(self):
user = BakeryUser.objects.create_user('user', 'password')
user.name = 'John Doe'
self.assertEqual(user.get_full_name(), 'John Doe')
def test_get_short_name(self):
user = BakeryUser.objects.create_user('user', 'password')
user.name = 'John Doe'
self.assertEqual(user.get_short_name(), 'John Doe')
| # -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.utils import unittest
from bakery.auth.models import BakeryUser
class TestBakeryUserModel(TestCase):
@unittest.skip('Not yet implemented')
def test_get_absolute_url(self):
user = BakeryUser.objects.create_user('user', 'password')
user.name = 'John Doe'
self.assertEqual(user.get_absolute_url(), reverse('user-detail-view'))
def test_get_full_name(self):
user = BakeryUser.objects.create_user('user', 'password')
user.name = 'John Doe'
self.assertEqual(user.get_full_name(), 'John Doe')
def test_get_short_name(self):
user = BakeryUser.objects.create_user('user', 'password')
user.name = 'John Doe'
self.assertEqual(user.get_short_name(), 'John Doe')
|
Fix Express error in dummy app: "Can't set headers after they are sent." as a result of returning the response object twice. | module.exports = function(app) {
var express = require('express');
var accountsRouter = express.Router();
accountsRouter.get('/1', function(req, res) {
if (/Bearer .+/.test(req.headers.authorization)) {
const response = {
data: {
type: 'accounts',
id: '1',
attributes: {
login: 'letme',
name: 'Some person'
}
}
};
res.status(200).send(response);
} else {
res.status(401).end();
}
});
app.use('/accounts', accountsRouter);
};
| module.exports = function(app) {
var express = require('express');
var accountsRouter = express.Router();
accountsRouter.get('/1', function(req, res) {
if (/Bearer .+/.test(req.headers.authorization)) {
const response = {
data: {
type: 'accounts',
id: '1',
attributes: {
login: 'letme',
name: 'Some person'
}
}
};
res.status(200).send(response);
res.status(200).send('{ "account": { "id": 1, "login": "letme", "name": "Some Person"} }');
} else {
res.status(401).end();
}
});
app.use('/accounts', accountsRouter);
};
|
Add Windows to *nix path conversion
Make external traversal detection comply with external static folder as *nix path | package spark.staticfiles;
import static spark.utils.StringUtils.removeLeadingAndTrailingSlashesFrom;
import java.nio.file.Paths;
/**
* Protecting against Directory traversal
*/
public class DirectoryTraversal {
public static void protectAgainstInClassPath(String path) {
if (!removeLeadingAndTrailingSlashesFrom(path).startsWith(StaticFilesFolder.local())) {
throw new DirectoryTraversalDetection("classpath");
}
}
public static void protectAgainstForExternal(String path) {
String nixLikePath = Paths.get(path).toAbsolutePath().toString().replace("\\", "/");
if (!removeLeadingAndTrailingSlashesFrom(nixLikePath).startsWith(StaticFilesFolder.external())) {
throw new DirectoryTraversalDetection("external");
}
}
public static final class DirectoryTraversalDetection extends RuntimeException {
public DirectoryTraversalDetection(String msg) {
super(msg);
}
}
}
| package spark.staticfiles;
import static spark.utils.StringUtils.removeLeadingAndTrailingSlashesFrom;
/**
* Protecting against Directory traversal
*/
public class DirectoryTraversal {
public static void protectAgainstInClassPath(String path) {
if (!removeLeadingAndTrailingSlashesFrom(path).startsWith(StaticFilesFolder.local())) {
throw new DirectoryTraversalDetection("classpath");
}
}
public static void protectAgainstForExternal(String path) {
if (!removeLeadingAndTrailingSlashesFrom(path).startsWith(StaticFilesFolder.external())) {
throw new DirectoryTraversalDetection("external");
}
}
public static final class DirectoryTraversalDetection extends RuntimeException {
public DirectoryTraversalDetection(String msg) {
super(msg);
}
}
}
|
Implement unit test for custodian (admin) password change | var utils = require('./utils.js');
var temporary_password = "typ0drome@absurd.org";
describe('receiver first login', function() {
it('should redirect to /firstlogin upon successful authentication', function() {
utils.login_custodian('Custodian1', utils.vars['default_password'], '/#/custodian', true);
});
it('should be able to change password from the default one', function() {
element(by.model('preferences.old_password')).sendKeys(utils.vars['default_password']);
element(by.model('preferences.password')).sendKeys(temporary_password);
element(by.model('preferences.check_password')).sendKeys(temporary_password);
element(by.css('[data-ng-click="pass_save()"]')).click();
utils.waitForUrl('/custodian/identityaccessrequests');
});
it('should be able to login with the new password', function() {
utils.login_custodian('Custodian1', temporary_password, '/#/custodian', false);
});
it('should be able to change password accessing the user preferences', function() {
element(by.cssContainingText("a", "Password configuration")).click();
element(by.model('preferences.old_password')).sendKeys(temporary_password);
element(by.model('preferences.password')).sendKeys(utils.vars['user_password']);
element(by.model('preferences.check_password')).sendKeys(utils.vars['user_password']);
element(by.css('[data-ng-click="pass_save()"]')).click();
});
});
| var utils = require('./utils.js');
describe('receiver first login', function() {
it('should redirect to /firstlogin upon successful authentication', function() {
utils.login_custodian('Custodian1', utils.vars['default_password'], '/#/custodian', true);
});
it('should be able to change password from the default one', function() {
element(by.model('preferences.old_password')).sendKeys(utils.vars['default_password']);
element(by.model('preferences.password')).sendKeys(utils.vars['user_password']);
element(by.model('preferences.check_password')).sendKeys(utils.vars['user_password']);
element(by.css('[data-ng-click="pass_save()"]')).click();
utils.waitForUrl('/custodian/identityaccessrequests');
});
it('should be able to login with the new password', function() {
utils.login_custodian();
});
});
|
Modify some charge action messages | <?php
/**
* @package Billing
* @copyright Copyright (C) 2012-2016 BillRun Technologies Ltd. All rights reserved.
* @license GNU Affero General Public License Version 3; see LICENSE.txt
*/
/**
* Charge action controller class
*
* @package Controllers
* @subpackage Action
*/
class ChargeAction extends Action_Base {
/**
* method to execute the pay process for payment gateways.
* it's called automatically by the cli main controller
*/
public function execute() {
$possibleOptions = array(
'stamp' => true,
);
if (($options = $this->_controller->getInstanceOptions($possibleOptions)) === FALSE) {
return;
}
$extraParams = $this->_controller->getParameters();
if (!empty($extraParams)) {
$options = array_merge($extraParams, $options);
}
$this->getController()->addOutput("Checking pending payments...");
Billrun_Bill_Payment::checkPendingStatus($options);
if (!isset($options['pending'])) {
$this->getController()->addOutput("Starting to charge unpaid payments...");
Billrun_Bill_Payment::makePayment($options);
}
$this->getController()->addOutput("Charging Done");
}
}
| <?php
/**
* @package Billing
* @copyright Copyright (C) 2012-2016 BillRun Technologies Ltd. All rights reserved.
* @license GNU Affero General Public License Version 3; see LICENSE.txt
*/
/**
* Charge action controller class
*
* @package Controllers
* @subpackage Action
*/
class ChargeAction extends Action_Base {
/**
* method to execute the pay process for payment gateways.
* it's called automatically by the cli main controller
*/
public function execute() {
$possibleOptions = array(
'stamp' => true,
);
if (($options = $this->_controller->getInstanceOptions($possibleOptions)) === FALSE) {
return;
}
$extraParams = $this->_controller->getParameters();
if (!empty($extraParams)) {
$options = array_merge($extraParams, $options);
}
Billrun_Bill_Payment::checkPendingStatus($options);
if (!isset($options['pending'])) {
$this->getController()->addOutput("Starting to charge unpaid payments");
Billrun_Bill_Payment::makePayment($options);
$this->getController()->addOutput("Charging Done");
}
}
}
|
Add video convert script to install. | #!/usr/bin/env python
import os
import sys
import re
from setuptools import find_packages, setup, Extension
def get_version():
ver = 'unknown'
if os.path.isfile("photosort/_version.py"):
f = open("photosort/_version.py", "r")
for line in f.readlines():
mo = re.match("__version__ = '(.*)'", line)
if mo:
ver = mo.group(1)
f.close()
return ver
current_version = get_version()
setup (
name = 'photosort',
provides = 'photosort',
version = current_version,
description = 'Sort photos based on EXIF data',
author = 'Theodore Kisner',
author_email = 'mail@theodorekisner.com',
url = 'https://github.com/tskisner/photosort',
packages = [ 'photosort' ],
scripts = [ 'phts_sync', 'phts_dirmd5', 'phts_album', 'phts_verify', 'phts_fixdate',
'phts_info', 'phts_export', 'phts_convert_video' ],
license = 'None',
requires = ['Python (>3.3.0)', ]
)
| #!/usr/bin/env python
import os
import sys
import re
from setuptools import find_packages, setup, Extension
def get_version():
ver = 'unknown'
if os.path.isfile("photosort/_version.py"):
f = open("photosort/_version.py", "r")
for line in f.readlines():
mo = re.match("__version__ = '(.*)'", line)
if mo:
ver = mo.group(1)
f.close()
return ver
current_version = get_version()
setup (
name = 'photosort',
provides = 'photosort',
version = current_version,
description = 'Sort photos based on EXIF data',
author = 'Theodore Kisner',
author_email = 'mail@theodorekisner.com',
url = 'https://github.com/tskisner/photosort',
packages = [ 'photosort' ],
scripts = [ 'phts_sync', 'phts_dirmd5', 'phts_album', 'phts_verify', 'phts_fixdate', 'phts_info', 'phts_export' ],
license = 'None',
requires = ['Python (>3.3.0)', ]
)
|
Make sure to avoid PHP error if no module will be available for the dashboard | <?php
/**
* @package Mautic
* @copyright 2014 Mautic Contributors. All rights reserved.
* @author Mautic
* @link http://mautic.org
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
?>
<div id="dashboard-modules">
<?php if ($modules): ?>
<?php foreach ($modules as $module): ?>
<div class="module" data-module-id="<?php echo $module->getId(); ?>" style="width: <?php echo !empty($module->getWidth()) ? $module->getWidth() . '' : '100' ?>%; height: <?php echo !empty($module->getHeight()) ? $module->getHeight() . 'px' : '300px' ?>">
<?php echo $view->render('MauticDashboardBundle:Module:module.html.php', array(
'module' => $module
)); ?>
</div>
<?php endforeach; ?>
<?php endif; ?>
<div class="clearfix"></div>
</div>
| <?php
/**
* @package Mautic
* @copyright 2014 Mautic Contributors. All rights reserved.
* @author Mautic
* @link http://mautic.org
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
?>
<div id="dashboard-modules">
<?php foreach ($modules as $module): ?>
<div class="module" data-module-id="<?php echo $module->getId(); ?>" style="width: <?php echo !empty($module->getWidth()) ? $module->getWidth() . '' : '100' ?>%; height: <?php echo !empty($module->getHeight()) ? $module->getHeight() . 'px' : '300px' ?>">
<?php echo $view->render('MauticDashboardBundle:Module:module.html.php', array(
'module' => $module
)); ?>
</div>
<?php endforeach; ?>
<div class="clearfix"></div>
</div>
|
Update console command with new job | <?php
namespace App\Console\Commands;
use App\Jobs\CrawlSite;
use App\Models\Site;
use Illuminate\Console\Command;
class CrawlSites extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'crawl';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Index sites in the sites table';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$sites = Site::all();
foreach ($sites as $site) {
dispatch(new LinkWorker($site));
}
}
}
| <?php
namespace App\Console\Commands;
use App\Jobs\CrawlSite;
use App\Models\Site;
use Illuminate\Console\Command;
class CrawlSites extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'crawl';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Index sites in the sites table';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$sites = Site::all();
foreach ($sites as $site) {
$this->line($site->url);
$job = (new CrawlSite($site));
dispatch($job);
}
}
}
|
BUG: Update the required argparse version since the version change is not backwards-compatible.
git-svn-id: 228151c6c098cf6fb629a8cadc3a43437d5f10bd@69 b5260ef8-a2c4-4e91-82fd-f242746c304a | import os
from setuptools import setup
kwds = {}
# Read the long description from the README.txt
thisdir = os.path.abspath(os.path.dirname(__file__))
f = open(os.path.join(thisdir, 'README.txt'))
kwds['long_description'] = f.read()
f.close()
setup(
name = 'grin',
version = '1.1.1',
author = 'Robert Kern',
author_email = 'robert.kern@enthought.com',
description = "A grep program configured the way I like it.",
license = "BSD",
classifiers = [
"License :: OSI Approved :: BSD License",
"Development Status :: 5 - Production/Stable",
"Environment :: Console",
"Intended Audience :: Developers",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Topic :: Utilities",
],
py_modules = ["grin"],
entry_points = dict(
console_scripts = [
"grin = grin:grin_main",
"grind = grin:grind_main",
],
),
install_requires = [
'argparse >= 1.1',
],
tests_require = [
'nose >= 0.10',
],
test_suite = 'nose.collector',
**kwds
)
| import os
from setuptools import setup
kwds = {}
# Read the long description from the README.txt
thisdir = os.path.abspath(os.path.dirname(__file__))
f = open(os.path.join(thisdir, 'README.txt'))
kwds['long_description'] = f.read()
f.close()
setup(
name = 'grin',
version = '1.1.1',
author = 'Robert Kern',
author_email = 'robert.kern@enthought.com',
description = "A grep program configured the way I like it.",
license = "BSD",
classifiers = [
"License :: OSI Approved :: BSD License",
"Development Status :: 5 - Production/Stable",
"Environment :: Console",
"Intended Audience :: Developers",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Topic :: Utilities",
],
py_modules = ["grin"],
entry_points = dict(
console_scripts = [
"grin = grin:grin_main",
"grind = grin:grind_main",
],
),
install_requires = [
'argparse',
],
tests_require = [
'nose >= 0.10',
],
test_suite = 'nose.collector',
**kwds
)
|
FIX selectedPanel not being stored to persisted store | import { types } from '@storybook/addons';
export function ensurePanel(panels, selectedPanel, currentPanel) {
const keys = Object.keys(panels);
if (keys.indexOf(selectedPanel) >= 0) {
return selectedPanel;
}
if (keys.length) {
return keys[0];
}
return currentPanel;
}
export default ({ provider, store }) => {
const api = {
getElements: type => provider.getElements(type),
getPanels: () => api.getElements(types.PANEL),
getSelectedPanel: () => {
const { selectedPanel } = store.getState();
return ensurePanel(api.getPanels(), selectedPanel, selectedPanel);
},
setSelectedPanel: panelName => {
store.setState({ selectedPanel: panelName }, { persistence: 'session' });
},
};
return {
api,
state: {
selectedPanel: ensurePanel(
api.getPanels(),
store.getState().selectedPanel,
store.getState().selectedPanel
),
},
};
};
| import { types } from '@storybook/addons';
export function ensurePanel(panels, selectedPanel, currentPanel) {
const keys = Object.keys(panels);
if (keys.indexOf(selectedPanel) >= 0) {
return selectedPanel;
}
if (keys.length) {
return keys[0];
}
return currentPanel;
}
export default ({ provider, store }) => {
const api = {
getElements: type => provider.getElements(type),
getPanels: () => api.getElements(types.PANEL),
getSelectedPanel: () => {
const { selectedPanel } = store.getState();
return ensurePanel(api.getPanels(), selectedPanel, selectedPanel);
},
setSelectedPanel: panelName => {
store.setState({ selectedPanel: panelName });
},
};
return {
api,
state: {
selectedPanel: ensurePanel(api.getPanels()),
},
};
};
|
Check success exists before using it | <?php
namespace Isotop\Cargo\Pusher;
class HTTP extends Abstract_Pusher {
/**
* Send data to receiver.
*
* @param mixed $data
*
* @return mixed
*/
public function send( $data ) {
$options = $this->cargo->config( 'pusher.http', ['url' => ''] );
$options = is_array( $options ) ? $options : ['url' => ''];
$json = $this->to_json( $data );
if ( empty( $json ) ) {
return false;
}
$args = array_merge( [
'headers' => [
'Content-Type' => 'application/json; charset=utf-8'
],
'body' => $json,
'timeout' => 30
], $options );
$res = wp_remote_post( $options['url'], $args );
if ( is_wp_error( $res ) ) {
$this->save( $args['body'], $res );
return $res;
}
$body = (array) json_decode( $res['body'] );
if ( empty( $body ) ) {
return false;
}
if ( isset( $body['success'] ) && $body['success'] ) {
return true;
}
$this->save( $args['body'], $res );
return false;
}
}
| <?php
namespace Isotop\Cargo\Pusher;
class HTTP extends Abstract_Pusher {
/**
* Send data to receiver.
*
* @param mixed $data
*
* @return mixed
*/
public function send( $data ) {
$options = $this->cargo->config( 'pusher.http', ['url' => ''] );
$options = is_array( $options ) ? $options : ['url' => ''];
$json = $this->to_json( $data );
if ( empty( $json ) ) {
return false;
}
$args = array_merge( [
'headers' => [
'Content-Type' => 'application/json; charset=utf-8'
],
'body' => $json,
'timeout' => 30
], $options );
$res = wp_remote_post( $options['url'], $args );
if ( is_wp_error( $res ) ) {
$this->save( $args['body'], $res );
return $res;
}
$body = (array) json_decode( $res['body'] );
if ( empty( $body ) ) {
return false;
}
if ( $body['success'] ) {
return true;
}
$this->save( $args['body'], $res );
return false;
}
}
|
Include client's WebSocket in onMessage function. | const url = require('url');
const WebSocket = require('ws');
var wss;
/* Initializes the WebSocket on the given server. */
function start(server) {
wss = new WebSocket.Server({ server, perMessageDeflate: false });
wss.on('connection', onConnection);
}
/* Called when a client connects to the WebSocket. */
function onConnection(ws) {
const location = url.parse(ws.upgradeReq.url, true);
// On message received from client
ws.on('message', function(message) {onIncomingMessage(message, ws)});
// When each client first connects
ws.send('Connection opened.');
}
/* Called when the server receives a message from a client. */
function onIncomingMessage(message, ws) {
// Broadcast the echoed message
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
}
module.exports = {start: start};
| const url = require('url');
const WebSocket = require('ws');
var wss;
/* Initializes the WebSocket on the given server. */
function start(server) {
wss = new WebSocket.Server({ server, perMessageDeflate: false });
wss.on('connection', onConnection);
}
/* Called when a client connects to the WebSocket. */
function onConnection(ws) {
const location = url.parse(ws.upgradeReq.url, true);
// On message received from client
ws.on('message', onIncomingMessage);
// When each client first connects
ws.send('Connection opened.');
}
/* Called when the server receives a message from a client. */
function onIncomingMessage(message) {
// Broadcast the echoed message
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
}
module.exports = {start: start};
|
Use process.cwd() to get actual project path. | 'use strict';
var path = require('path');
module.exports = function(name){
// read the project package.json
var cwd = process.cwd();
var pkg = require(path.join(cwd, 'package.json'));
var moduleRoot = path.join(cwd, 'node_modules', name);
var modulePkg = require(path.join(moduleRoot, 'package.json'));
// make sure that the specified module exists
var hasDep = pkg.dependencies && pkg.dependencies[name];
var hasDevDep = pkg.devDependencies && pkg.devDependencies[name];
if(!hasDep && !hasDevDep) {
console.log(pkg);
throw new Error('Requested module "' + name + '" not installed in dependencies or devDependencies.');
}
// get the bin path from the module's package.json
var bin = modulePkg.bin;
// make sure there is at least one executable
if(Object.keys(bin).length === 0) {
throw new Error('Requested module "' + name + '" does not have a binary executable listed in its package.json.');
}
else if(Object.keys(bin).length > 1) {
console.log('WARNING: Requested module "' + name + '" has more than 1 binary executable so I\'m going to return the first one. Returning others is not currently implemented.');
console.log(bin);
}
// return the path of the first binary
return path.join(moduleRoot, bin[Object.keys(bin)[0]]);
};
| 'use strict';
var path = require('path');
module.exports = function(name){
// read the project package.json
var pkg = require('./package.json');
// make sure that the specified module exists
var hasDep = pkg.dependencies && pkg.dependencies[name];
var hasDevDep = pkg.devDependencies && pkg.devDependencies[name];
if(!hasDep && !hasDevDep) {
throw new Error('Requested module "' + name + '" not installed in dependencies or devDependencies.');
}
// get the bin path from the module's package.json
var bin = require(name + '/package').bin;
// make sure there is exactly one executable
if(Object.keys(bin).length === 0) {
throw new Error('Requested module "' + name + '" does not have a binary executable listed in its package.json.');
}
else if(Object.keys(bin).length > 1) {
console.log('WARNING: Requested module "' + name + '" has more than 1 binary executable so I\'m going to return the first one. Returning others is not currently implemented.');
console.log(bin);
}
// return the path of the first binary
return path.join(__dirname, 'node_modules', name, bin[Object.keys(bin)[0]]);
};
|
Disable the menubar when running from source | var electron = require('electron'); // Module to control application life.
var process = require('process');
const {app} = electron;
const {BrowserWindow} = electron;
let win; // Ensure that our win isn't garbage collected
app.on('ready', function() {
// Create the browser window.
if (process.platform == 'win32')
win = new BrowserWindow({width: 670, height: 510, frame: true, resizable: false});
else
win = new BrowserWindow({width: 640, height: 480, frame: true, resizable: false});
// Load the main interface
win.loadURL('file://' + __dirname + '/index.html');
// Uncomment this line to open the DevTools upon launch.
//win.webContents.openDevTools({'mode':'undocked'});
//Disable the menubar for dev versions
win.setMenu(null);
win.on('closed', function() {
// Dereference the window object so our app exits
win = null;
});
});
// Quit when all windows are closed.
app.on('window-all-closed', function() {
app.quit();
});
| var electron = require('electron'); // Module to control application life.
var process = require('process');
const {app} = electron;
const {BrowserWindow} = electron;
let win; // Ensure that our win isn't garbage collected
app.on('ready', function() {
// Create the browser window.
if (process.platform == 'win32')
win = new BrowserWindow({width: 670, height: 510, frame: true, resizable: false});
else
win = new BrowserWindow({width: 640, height: 480, frame: true, resizable: false});
// Load the main interface
win.loadURL('file://' + __dirname + '/index.html');
// Uncomment this line to open the DevTools upon launch.
//win.webContents.openDevTools({'mode':'undocked'});
win.on('closed', function() {
// Dereference the window object so our app exits
win = null;
});
});
// Quit when all windows are closed.
app.on('window-all-closed', function() {
app.quit();
});
|
Upgrade to PyJWT 1.0.0 and cryptography 0.8 | import os, io
from setuptools import setup, find_packages
long_description = (
io.open('README.rst', encoding='utf-8').read()
+ '\n' +
io.open('CHANGES.txt', encoding='utf-8').read())
setup(name='more.jwtauth',
version='0.1.dev0',
description="JWT Access Auth Identity Policy for Morepath",
long_description=long_description,
author="Henri Schumacher",
author_email="henri.hulski@gazeta.pl",
keywords='morepath JWT identity authentication',
license="BSD",
url="https://github.com/henri-hulski/more.jwtauth",
namespace_packages=['more'],
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=[
'setuptools',
'morepath > 0.9',
'PyJWT >= 1.0.0',
'cryptography >= 0.8'
],
extras_require=dict(
test=['pytest >= 2.6.0',
'pytest-cov',
'WebTest'],
),
)
| import os, io
from setuptools import setup, find_packages
long_description = (
io.open('README.rst', encoding='utf-8').read()
+ '\n' +
io.open('CHANGES.txt', encoding='utf-8').read())
setup(name='more.jwtauth',
version='0.1.dev0',
description="JWT Access Auth Identity Policy for Morepath",
long_description=long_description,
author="Henri Schumacher",
author_email="henri.hulski@gazeta.pl",
keywords='morepath JWT identity authentication',
license="BSD",
url="https://github.com/henri-hulski/more.jwtauth",
namespace_packages=['more'],
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=[
'setuptools',
'morepath > 0.9',
'cryptography',
'PyJWT >= 0.4.2'
],
extras_require=dict(
test=['pytest >= 2.6.0',
'pytest-cov',
'WebTest'],
),
)
|
Return the top most group name of an object | #**********************************************************************************************#
#********* Return the top most group name of an object ****************************************#
#********* by Djordje Spasic ******************************************************************#
#********* issworld2000@yahoo.com 6-May-2014 **************************************************#
"""
This small function replicates the "ObjectTopGroup" RhinoScript function, which still hasn't been implemented
into PythonScript.
Returns the top most group name that an object is assigned. This function primarily applies to objects that are
members of nested groups.
"""
import rhinoscriptsyntax as rs
import scriptcontext as sc
def objectTopGroup(_id):
groupNames = sc.doc.Groups.GroupNames(False)
groupName = False
for i in range(rs.GroupCount()):
groupRO = sc.doc.Groups.GroupMembers(i)
for ele in groupRO:
if ele.Id == _id:
groupName = groupNames[i]
if groupName:
print groupName
else:
print "The element you chose does not belong to any group"
id = rs.GetObject()
objectTopGroup(id)
| #**********************************************************************************************#
#********* Return the top most group name of an object ****************************************#
#********* by Djordje Spasic ******************************************************************#
#********* issworld2000@yahoo.com 6-May-2014 **************************************************#
"""
This small function replicates the "ObjectTopGroup" RhinoScript function, which still hasn't been implemented
into PythonScript.
Returns the top most group name that an object is assigned. This function primarily applies to objects that are
members of nested groups.
"""
import rhinoscriptsyntax as rs
import scriptcontext as sc
def objectTopGroup(_id):
groupNames = sc.doc.Groups.GroupNames(False)
groupName = False
for i in range(rs.GroupCount()):
groupRO = sc.doc.Groups.GroupMembers(i)
for ele in groupRO:
if rs.coercerhinoobject(ele).Id == _id:
groupName = groupNames[i]
if groupName:
print groupName
else:
print "The element you chose does not belong to any group"
id = rs.GetObject()
objectTopGroup(id)
|
Handle case iframe is rendered too early. | define([
'backbone',
'jquery',
'underscore',
'chartsM',
'visualizationsServiceM',
], function (Backbone, $, _, chartsM, visualizationsServiceM) {
'use strict';
var IframeChartV = Backbone.View.extend({
initialize: function () {
this.listenTo(chartsM, 'change:apiData', this.render);
},
render: function() {
var visualizationData = _.find(visualizationsServiceM.get('visualizations'), function(item) {
return item.slug === chartsM.get('currentChartSlug');
});
if ( ! _.isUndefined(visualizationData)) {
this.$el.empty().append($('<iframe>', {
'class': 'visualization-iframe',
src: visualizationData.iframeSrcUrl + '&height=' + this.$el.height() + '&width=' + this.$el.width() +
'&legislation_url=' + (chartsM.get('legislation') || '') + '&year=' + chartsM.get('year'),
}));
}
},
});
return IframeChartV;
});
| define([
'backbone',
'jquery',
'underscore',
'chartsM',
'visualizationsServiceM',
], function (Backbone, $, _, chartsM, visualizationsServiceM) {
'use strict';
var IframeChartV = Backbone.View.extend({
initialize: function () {
this.listenTo(chartsM, 'change:apiData', this.render);
},
render: function() {
var visualizationData = _.find(visualizationsServiceM.get('visualizations'), function(item) {
return item.slug === chartsM.get('currentChartSlug');
});
this.$el.empty().append($('<iframe>', {
'class': 'visualization-iframe',
src: visualizationData.iframeSrcUrl + '&height=' + this.$el.height() + '&width=' + this.$el.width() +
'&legislation_url=' + (chartsM.get('legislation') || '') + '&year=' + chartsM.get('year'),
}));
},
});
return IframeChartV;
});
|
Make the config dependency's origin
Set in global namespace from a script tag rendered by Rails app | var Router = require('new_dashboard/router');
var $ = require('jquery');
var cdb = require('cartodb.js');
var MainView = require('new_dashboard/main_view');
/**
* The Holy Dashboard
*/
$(function() {
cdb.init(function() {
cdb.templates.namespace = 'cartodb/';
cdb.config.set(window.config); // import config
if (cdb.config.isOrganizationUrl()) {
cdb.config.set('url_prefix', cdb.config.organizationUrl());
}
var router = new Router();
// Mixpanel test
if (window.mixpanel) {
new cdb.common.Mixpanel({
user: user_data,
token: mixpanel_token
});
}
// Store JS errors
new cdb.admin.ErrorStats({ user_data: user_data });
// Main view
var dashboard = new MainView({
el: document.body,
user_data: user_data,
upgrade_url: upgrade_url,
config: config,
router: router
});
window.dashboard = dashboard;
// History
Backbone.history.start({
pushState: true,
root: cdb.config.prefixUrl() + '/' //cdb.config.prefixUrl() + '/dashboard/'
});
});
});
| var Router = require('new_dashboard/router');
var $ = require('jquery');
var cdb = require('cartodb.js');
var MainView = require('new_dashboard/main_view');
/**
* The Holy Dashboard
*/
$(function() {
cdb.init(function() {
cdb.templates.namespace = 'cartodb/';
cdb.config.set(config); // import config
if (cdb.config.isOrganizationUrl()) {
cdb.config.set('url_prefix', cdb.config.organizationUrl());
}
var router = new Router();
// Mixpanel test
if (window.mixpanel) {
new cdb.common.Mixpanel({
user: user_data,
token: mixpanel_token
});
}
// Store JS errors
new cdb.admin.ErrorStats({ user_data: user_data });
// Main view
var dashboard = new MainView({
el: document.body,
user_data: user_data,
upgrade_url: upgrade_url,
config: config,
router: router
});
window.dashboard = dashboard;
// History
Backbone.history.start({
pushState: true,
root: cdb.config.prefixUrl() + '/' //cdb.config.prefixUrl() + '/dashboard/'
});
});
});
|
Add '/admin' url_prefix to main blueprint
Also attaches the authentication check to main blueprint instead of
the app itself. This means we can use other blueprints for status
and internal use that don't require authentication.
One important note: before_request must be added before registering
the blueprint, otherwise it won't be activated. | from flask import Flask
from flask.ext.bootstrap import Bootstrap
from config import config
from datetime import timedelta
from .main import main as main_blueprint
from .main.helpers.auth import requires_auth
bootstrap = Bootstrap()
def create_app(config_name):
application = Flask(__name__,
static_folder='static/',
static_url_path=config[config_name].STATIC_URL_PATH)
application.config.from_object(config[config_name])
config[config_name].init_app(application)
bootstrap.init_app(application)
if application.config['AUTHENTICATION']:
application.permanent_session_lifetime = timedelta(minutes=60)
main_blueprint.before_request(requires_auth)
application.register_blueprint(main_blueprint, url_prefix='/admin')
main_blueprint.config = application.config.copy()
return application
| from flask import Flask
from flask.ext.bootstrap import Bootstrap
from config import config
from datetime import timedelta
from .main import main as main_blueprint
from .main.helpers.auth import requires_auth
bootstrap = Bootstrap()
def create_app(config_name):
application = Flask(__name__,
static_folder='static/',
static_url_path=config[config_name].STATIC_URL_PATH)
application.config.from_object(config[config_name])
config[config_name].init_app(application)
bootstrap.init_app(application)
application.register_blueprint(main_blueprint)
main_blueprint.config = application.config.copy()
if application.config['AUTHENTICATION']:
application.permanent_session_lifetime = timedelta(minutes=60)
application.before_request(requires_auth)
return application
|
Use falcon methods as HTTP methods | from functools import wraps
from collections import OrderedDict
import sys
from falcon import HTTP_METHODS
def call(url, methods=HTTP_METHODS):
def decorator(api_function):
module = sys.modules[api_function.__name__]
api_definition = sys.modules['hug.hug'].__dict__.setdefault('HUG_API_CALLS', OrderedDict())
for method in methods:
api_definition.setdefault(url, {})["on_{0}".format(method.lower())] = api_function
def interface(request, reponse):
return api_function(**request.attributes)
api_function.interface = interface
return api_function
def get(url):
return call(url=url, accept=('GET', ))
def post(url):
return call(url=url, accept=('POST', ))
def put(url):
return call(url=url, acccept('PUT', ))
def delete(url):
return call(url=url, accept=('DELETE', ))
| from functools import wraps
from collections import OrderedDict
import sys
def call(url, methods=('ALL', )):
def decorator(api_function):
module = sys.modules[api_function.__name__]
api_definition = sys.modules['hug.hug'].__dict__.setdefault('API_CALLS', OrderedDict())
for method in methods:
api_definition.setdefault(url, {})['ALL'] = api_function
def interface(request, reponse):
return api_function(**request.attributes)
api_function.interface = interface
return api_function
def get(url):
return call(url=url, accept=('GET', ))
def post(url):
return call(url=url, accept=('POST', ))
def put(url):
return call(url=url, acccept('PUT', ))
def delete(url):
return call(url=url, accept=('DELETE', ))
|
Include passphrase for validation and connection | var fs = require('fs');
var q = require('q');
var sysu = require('util');
var resolve = require('./resolve');
function loadCredentials(credentials) {
// Prepare PKCS#12 data if available
var pfxPromise = resolve(credentials.pfx || credentials.pfxData);
// Prepare Certificate data if available.
var certPromise = resolve(credentials.cert || credentials.certData);
// Prepare Key data if available
var keyPromise = resolve(credentials.key || credentials.keyData);
// Prepare Certificate Authority data if available.
var caPromises = [];
if (credentials.ca != null && !sysu.isArray(credentials.ca)) {
credentials.ca = [ credentials.ca ];
}
for(var i in credentials.ca) {
var ca = credentials.ca[i];
caPromises.push(resolve(ca));
}
if (caPromises.length == 0) {
delete caPromises;
}
else {
caPromises = q.all(caPromises);
}
return q.all([pfxPromise, certPromise, keyPromise, caPromises])
.spread(function(pfx, cert, key, ca) {
return { pfx: pfx, cert: cert, key: key, ca: ca, passphrase: credentials.passphrase };
});
}
module.exports = loadCredentials; | var fs = require('fs');
var q = require('q');
var sysu = require('util');
var resolve = require('./resolve');
function loadCredentials(credentials) {
// Prepare PKCS#12 data if available
var pfxPromise = resolve(credentials.pfx || credentials.pfxData);
// Prepare Certificate data if available.
var certPromise = resolve(credentials.cert || credentials.certData);
// Prepare Key data if available
var keyPromise = resolve(credentials.key || credentials.keyData);
// Prepare Certificate Authority data if available.
var caPromises = [];
if (credentials.ca != null && !sysu.isArray(credentials.ca)) {
credentials.ca = [ credentials.ca ];
}
for(var i in credentials.ca) {
var ca = credentials.ca[i];
caPromises.push(resolve(ca));
}
if (caPromises.length == 0) {
delete caPromises;
}
else {
caPromises = q.all(caPromises);
}
return q.all([pfxPromise, certPromise, keyPromise, caPromises])
.spread(function(pfx, cert, key, ca) {
return { pfx: pfx, cert: cert, key: key, ca: ca };
});
}
module.exports = loadCredentials; |
Migrate from Folly Format to fmt
Summary: Migrate from Folly Format to fmt which provides smaller compile times and per-call binary code size.
Reviewed By: alandau
Differential Revision: D14954926
fbshipit-source-id: 9d2c39e74a5d11e0f90c8ad0d71b79424c56747f | #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import specs.folly as folly
import specs.fizz as fizz
import specs.fmt as fmt
import specs.rsocket as rsocket
import specs.sodium as sodium
import specs.wangle as wangle
import specs.zstd as zstd
from shell_quoting import ShellQuoted
def fbcode_builder_spec(builder):
# This API should change rarely, so build the latest tag instead of master.
builder.add_option(
'no1msd/mstch:git_hash',
ShellQuoted('$(git describe --abbrev=0 --tags)')
)
return {
'depends_on': [folly, fizz, fmt, sodium, rsocket, wangle, zstd],
'steps': [
# This isn't a separete spec, since only fbthrift uses mstch.
builder.github_project_workdir('no1msd/mstch', 'build'),
builder.cmake_install('no1msd/mstch'),
builder.fb_github_cmake_install('fbthrift/thrift'),
],
}
| #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import specs.folly as folly
import specs.fizz as fizz
import specs.rsocket as rsocket
import specs.sodium as sodium
import specs.wangle as wangle
import specs.zstd as zstd
from shell_quoting import ShellQuoted
def fbcode_builder_spec(builder):
# This API should change rarely, so build the latest tag instead of master.
builder.add_option(
'no1msd/mstch:git_hash',
ShellQuoted('$(git describe --abbrev=0 --tags)')
)
return {
'depends_on': [folly, fizz, sodium, rsocket, wangle, zstd],
'steps': [
# This isn't a separete spec, since only fbthrift uses mstch.
builder.github_project_workdir('no1msd/mstch', 'build'),
builder.cmake_install('no1msd/mstch'),
builder.fb_github_cmake_install('fbthrift/thrift'),
],
}
|
Add copyId to card schema | const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const CardSchema = new Schema({
name: {
type: String,
unique: true,
require: true,
},
idName: {
type: String,
unique: true,
require: true,
},
rarity: {
type: String,
enum: 'Common Rare Epic Legendary'.split(' '),
require: true,
},
type: {
type: String,
enum: 'Troop Building Spell'.split(' '),
require: true,
},
description: {
type: String,
require: true,
},
arena: {
type: Number,
require: true,
},
elixirCost: {
type: Number,
require: true,
},
order: {
type: Number,
require: true,
},
copyId: {
type: Number,
require: true,
},
});
CardSchema.pre('save', function preSave(next) {
if (!this.idName) {
this.idName = JSON.parse(JSON.stringify(this.name.toLowerCase()));
this.idName = this.idName.replace(/ /g, '-');
this.idName = this.idName.replace(/\./g, '');
}
next();
});
module.exports = mongoose.model('Card', CardSchema);
| const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const CardSchema = new Schema({
name: {
type: String,
unique: true,
require: true,
},
idName: {
type: String,
unique: true,
require: true,
},
rarity: {
type: String,
enum: 'Common Rare Epic Legendary'.split(' '),
require: true,
},
type: {
type: String,
enum: 'Troop Building Spell'.split(' '),
require: true,
},
description: {
type: String,
require: true,
},
arena: {
type: Number,
require: true,
},
elixirCost: {
type: Number,
require: true,
},
order: {
type: Number,
require: true,
},
});
CardSchema.pre('save', function preSave(next) {
if (!this.idName) {
this.idName = JSON.parse(JSON.stringify(this.name.toLowerCase()));
this.idName = this.idName.replace(/ /g, '-');
this.idName = this.idName.replace(/\./g, '');
}
next();
});
module.exports = mongoose.model('Card', CardSchema);
|
Add missing @since 7.6 tags
Change-Id: Iffa8655403615d1f7345709c865dd14c6fa861b2 | /*
* Copyright 2000-2014 Vaadin Ltd.
*
* 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.vaadin.client.connectors;
import com.vaadin.client.ServerConnector;
import com.vaadin.client.widget.grid.selection.SelectionModel;
import com.vaadin.client.widget.grid.selection.SelectionModelNone;
import com.vaadin.shared.ui.Connect;
import com.vaadin.ui.Grid.NoSelectionModel;
import elemental.json.JsonObject;
/**
* Connector for server-side {@link NoSelectionModel}.
*
* @since 7.6
* @author Vaadin Ltd
*/
@Connect(NoSelectionModel.class)
public class NoSelectionModelConnector extends
AbstractSelectionModelConnector<SelectionModel<JsonObject>> {
@Override
protected void extend(ServerConnector target) {
getGrid().setSelectionModel(createSelectionModel());
}
@Override
protected SelectionModel<JsonObject> createSelectionModel() {
return new SelectionModelNone<JsonObject>();
}
} | /*
* Copyright 2000-2014 Vaadin Ltd.
*
* 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.vaadin.client.connectors;
import com.vaadin.client.ServerConnector;
import com.vaadin.client.widget.grid.selection.SelectionModel;
import com.vaadin.client.widget.grid.selection.SelectionModelNone;
import com.vaadin.shared.ui.Connect;
import com.vaadin.ui.Grid.NoSelectionModel;
import elemental.json.JsonObject;
/**
* Connector for server-side {@link NoSelectionModel}.
*/
@Connect(NoSelectionModel.class)
public class NoSelectionModelConnector extends
AbstractSelectionModelConnector<SelectionModel<JsonObject>> {
@Override
protected void extend(ServerConnector target) {
getGrid().setSelectionModel(createSelectionModel());
}
@Override
protected SelectionModel<JsonObject> createSelectionModel() {
return new SelectionModelNone<JsonObject>();
}
} |
Make sure we keep EVENTS below the MAX_EVENTS threshold | package com.peterphi.std.guice.common.logging.appender;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.spi.LoggingEvent;
import java.util.LinkedList;
import java.util.function.Consumer;
public class InMemoryAppender extends AppenderSkeleton
{
private static final LinkedList<LoggingEvent> EVENTS = new LinkedList<>();
private static final int MAX_EVENTS = 5000;
/**
* Clear all the logged events
*/
public static void clear()
{
synchronized (EVENTS)
{
EVENTS.clear();
}
}
public static void visit(Consumer<LoggingEvent> consumer)
{
synchronized (EVENTS)
{
for (LoggingEvent event : EVENTS)
consumer.accept(event);
}
}
@Override
protected void append(final LoggingEvent event)
{
synchronized (EVENTS)
{
EVENTS.push(event);
while (EVENTS.size() >= MAX_EVENTS)
EVENTS.removeLast();
}
}
@Override
public void close()
{
synchronized (EVENTS)
{
EVENTS.clear();
}
}
@Override
public boolean requiresLayout()
{
return false;
}
}
| package com.peterphi.std.guice.common.logging.appender;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.spi.LoggingEvent;
import java.util.LinkedList;
import java.util.function.Consumer;
public class InMemoryAppender extends AppenderSkeleton
{
private static final LinkedList<LoggingEvent> EVENTS = new LinkedList<>();
private static final int MAX_EVENTS = 5000;
/**
* Clear all the logged events
*/
public static void clear()
{
synchronized (EVENTS)
{
EVENTS.clear();
}
}
public static void visit(Consumer<LoggingEvent> consumer)
{
synchronized (EVENTS)
{
for (LoggingEvent event : EVENTS)
consumer.accept(event);
}
}
@Override
protected void append(final LoggingEvent event)
{
synchronized (EVENTS)
{
EVENTS.push(event);
if (EVENTS.size() >= MAX_EVENTS)
EVENTS.removeFirst();
}
}
@Override
public void close()
{
synchronized (EVENTS)
{
EVENTS.clear();
}
}
@Override
public boolean requiresLayout()
{
return false;
}
}
|
Prepare to use marina as a package | from marina.plugins import get_plugins_configuration
from setuptools import setup, find_packages
def get_console_scripts():
"""Guess if we use marina as a package or if it has been cloned"""
scripts = "[console_scripts]\n"
try:
from marina import cli, docker_clean
scripts += "marina=marina.cli:main\n"
scripts += "docker-clean=marina.docker_clean:main\n"
except Exception:
scripts += "marina=cli:main\n"
scripts += "docker-clean=docker_clean:main\n"
return scripts
setup(
name='Marina',
version='2.0',
description='A stack based on docker to run PHP Applications',
url='http://github.com/inetprocess/marina',
author='Emmanuel Dyan',
author_email='emmanuel.dyan@inetprocess.com',
license='Apache 2.0',
packages=find_packages(exclude=['contrib', 'docs', 'tests*']),
py_modules=['marina'],
entry_points='{}{}'.format(get_console_scripts(), get_plugins_configuration()),
install_requires=[
'clint',
'click', 'click-plugins',
'docker-compose',
'configobj',
'requests>=2.11.0,<2.12'
]
)
| from marina.plugins import get_plugins_configuration
from setuptools import setup, find_packages
setup(
name='Marina',
version='2.0',
description='A stack based on docker to run PHP Applications',
url='http://github.com/inetprocess/marina',
author='Emmanuel Dyan',
author_email='emmanuel.dyan@inetprocess.com',
license='Apache 2.0',
packages=find_packages(exclude=['contrib', 'docs', 'tests*']),
py_modules=['marina'],
entry_points='''
[console_scripts]
marina=cli:main
docker-clean=docker_clean:main
{}
'''.format(get_plugins_configuration()),
install_requires=[
'clint',
'click', 'click-plugins',
'requests>=2.11.0,<2.12',
'docker-compose',
'configobj'
]
)
|
Remove <1.9 limit on Django version | import os
from setuptools import setup
import sys
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
tests_require = ['responses>=0.5']
if sys.version_info < (3, 3):
tests_require.append('mock>=1.3')
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-moj-irat',
version='0.3',
packages=['moj_irat'],
include_package_data=True,
license='BSD License',
description="Tools to support adding a Django-based service to "
"Ministry of Justice's Incidence Response and Tuning",
long_description=README,
install_requires=['Django>=1.8', 'requests'],
classifiers=[
'Framework :: Django',
'Intended Audience :: MoJ Developers',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
],
test_suite='runtests.runtests',
tests_require=tests_require
)
| import os
from setuptools import setup
import sys
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
tests_require = ['responses>=0.5']
if sys.version_info < (3, 3):
tests_require.append('mock>=1.3')
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-moj-irat',
version='0.3',
packages=['moj_irat'],
include_package_data=True,
license='BSD License',
description="Tools to support adding a Django-based service to "
"Ministry of Justice's Incidence Response and Tuning",
long_description=README,
install_requires=['Django>=1.8,<1.9', 'requests'],
classifiers=[
'Framework :: Django',
'Intended Audience :: MoJ Developers',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
],
test_suite='runtests.runtests',
tests_require=tests_require
)
|
Change LOG_ONLY config value from 'log-only' to 'log_only' | // Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.security.tls;
import java.util.Arrays;
/**
* @author bjorncs
*/
public enum AuthorizationMode {
DISABLE("disable"),
LOG_ONLY("log_only"),
ENFORCE("enforce");
final String configValue;
AuthorizationMode(String configValue) {
this.configValue = configValue;
}
public String configValue() {
return configValue;
}
static AuthorizationMode fromConfigValue(String configValue) {
return Arrays.stream(values())
.filter(v -> v.configValue.equals(configValue))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("Unknown value: " + configValue));
}
}
| // Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.security.tls;
import java.util.Arrays;
/**
* @author bjorncs
*/
public enum AuthorizationMode {
DISABLE("disable"),
LOG_ONLY("log-only"),
ENFORCE("enforce");
final String configValue;
AuthorizationMode(String configValue) {
this.configValue = configValue;
}
public String configValue() {
return configValue;
}
static AuthorizationMode fromConfigValue(String configValue) {
return Arrays.stream(values())
.filter(v -> v.configValue.equals(configValue))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("Unknown value: " + configValue));
}
}
|
Add feedback for unidentified errors | import config from '../config'
export const feedback: (feedback) => any =
(feedback) => {
const options = {
method: 'POST',
headers: {
'Content-Type': "application/json",
"Voter-ID": feedback.uuid
},
body: JSON.stringify(feedback.feedback)
}
return fetch(`${config.urls.devnull}/events/${feedback.eventId}/sessions/${feedback.sessionId}/feedbacks`, options)
.then(res => {
if (res.status === 202) {
return { message: 'Feedback submitted' }
} else if(res.status === 403) {
return { message : 'Please try again. Feedback opens 10 min before session ends.' }
} else {
return { message: 'Ops somthing went wrong.' }
}
}
)
} | import config from '../config'
export const feedback: (feedback) => any =
(feedback) => {
const options = {
method: 'POST',
headers: {
'Content-Type': "application/json",
"Voter-ID": feedback.uuid
},
body: JSON.stringify(feedback.feedback)
}
return fetch(`${config.urls.devnull}/events/${feedback.eventId}/sessions/${feedback.sessionId}/feedbacks`, options)
.then(res => {
if (res.status === 202) {
return { message: 'Feedback submitted' }
} else if(res.status === 403) {
return { message : 'Please try again. Feedback opens 10 min before session ends.' }
} else {
return res.status
}
}
)
} |
Add accounts url for registration backend | """imagersite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.conf import settings
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^accounts/', include('registration.backends.default.urls')),
]
if settings.DEBUG:
urlpatterns += static(
settings.MEDIA_URL, document_root=settings.MEDIA_ROOT
)
| """imagersite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.conf import settings
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
]
if settings.DEBUG:
urlpatterns += static(
settings.MEDIA_URL, document_root=settings.MEDIA_ROOT
)
|
Disable admin page auto refresh | 'use strict';
angular.module('hornbyApp')
.controller('HornbyAdminCtrl', function ($scope, $http, socket, $log) {
var refreshMeasurements = function () {
$http.get('/api/measurements').success(function(measurements) {
$scope.measurements = measurements;
$log.log("measurements: ", measurements);
//socket.syncUpdates('measurement', $scope.measurements);
})
};
$http.get('/api/measurements').success(function(measurements) {
$scope.measurements = measurements;
$log.log("measurements: ", measurements);
socket.syncUpdates('measurement', $scope.measurements);
});
$scope.saveMeasurement = function (measurement) {
$http.put('/api/measurements/' + measurement.uid, measurement);
refreshMeasurements();
};
$scope.sendMeasurement = function (measurement) {
var copyMeasurement = angular.copy(measurement);
copyMeasurement.name = null;
copyMeasurement.video.data += 1000;
$http.put('/api/measurements/' + copyMeasurement.uid, copyMeasurement);
};
refreshMeasurements();
});
| 'use strict';
angular.module('hornbyApp')
.controller('HornbyAdminCtrl', function ($scope, $http, socket, $log) {
var refreshMeasurements = function () {
$http.get('/api/measurements').success(function(measurements) {
$scope.measurements = measurements;
$log.log("measurements: ", measurements);
socket.syncUpdates('measurement', $scope.measurements);
})
};
$http.get('/api/measurements').success(function(measurements) {
$scope.measurements = measurements;
$log.log("measurements: ", measurements);
socket.syncUpdates('measurement', $scope.measurements);
});
$scope.saveMeasurement = function (measurement) {
$http.put('/api/measurements/' + measurement.uid, measurement);
refreshMeasurements();
};
$scope.sendMeasurement = function (measurement) {
var copyMeasurement = angular.copy(measurement);
copyMeasurement.name = null;
copyMeasurement.video.data += 1000;
$http.put('/api/measurements/' + copyMeasurement.uid, copyMeasurement);
};
refreshMeasurements();
});
|
WATCH now defaults to False | import os
from optional_django import conf
class Conf(conf.Conf):
# Environment configuration
STATIC_ROOT = None
STATIC_URL = None
BUILD_SERVER_URL = 'http://127.0.0.1:9009'
OUTPUT_DIR = 'webpack_assets'
CONFIG_DIRS = None
CONTEXT = None
# Watching
WATCH = False
AGGREGATE_TIMEOUT = 200
POLL = None
HMR = False
# Caching
CACHE = True
CACHE_DIR = None
def get_path_to_output_dir(self):
return os.path.join(self.STATIC_ROOT, self.OUTPUT_DIR)
def get_public_path(self):
static_url = self.STATIC_URL
if static_url and static_url.endswith('/'):
static_url = static_url[0:-1]
return '/'.join([static_url, self.OUTPUT_DIR])
settings = Conf()
| import os
from optional_django import conf
class Conf(conf.Conf):
# Environment configuration
STATIC_ROOT = None
STATIC_URL = None
BUILD_SERVER_URL = 'http://127.0.0.1:9009'
OUTPUT_DIR = 'webpack_assets'
CONFIG_DIRS = None
CONTEXT = None
# Watching
WATCH = True # TODO: should default to False
AGGREGATE_TIMEOUT = 200
POLL = None
HMR = False
# Caching
CACHE = True
CACHE_DIR = None
def get_path_to_output_dir(self):
return os.path.join(self.STATIC_ROOT, self.OUTPUT_DIR)
def get_public_path(self):
static_url = self.STATIC_URL
if static_url and static_url.endswith('/'):
static_url = static_url[0:-1]
return '/'.join([static_url, self.OUTPUT_DIR])
settings = Conf()
|
Add help message to cli tool | # -*- coding: utf-8 -*-
65;5403;1c
import argparse
from twstock.codes import __update_codes
from twstock.cli import best_four_point
from twstock.cli import stock
from twstock.cli import realtime
def run():
parser = argparse.ArgumentParser()
parser.add_argument('-b', '--bfp', nargs='+')
parser.add_argument('-s', '--stock', nargs='+')
parser.add_argument('-r', '--realtime', nargs='+')
parser.add_argument('-U', '--upgrade-codes', action='store_true', help='Update entites codes')
args = parser.parse_args()
if args.bfp:
best_four_point.run(args.bfp)
elif args.stock:
stock.run(args.stock)
elif args.realtime:
realtime.run(args.realtime)
elif args.upgrade_codes:
print('Start to update codes')
__update_codes()
print('Done!')
else:
parser.print_help()
| # -*- coding: utf-8 -*-
import argparse
from twstock.codes import __update_codes
from twstock.cli import best_four_point
from twstock.cli import stock
from twstock.cli import realtime
def run():
parser = argparse.ArgumentParser()
parser.add_argument('-b', '--bfp', nargs='+')
parser.add_argument('-s', '--stock', nargs='+')
parser.add_argument('-r', '--realtime', nargs='+')
parser.add_argument('-U', '--upgrade-codes', action='store_true', help='Update entites codes')
args = parser.parse_args()
if args.bfp:
best_four_point.run(args.bfp)
elif args.stock:
stock.run(args.stock)
elif args.realtime:
realtime.run(args.realtime)
elif args.upgrade_codes:
print('Start to update codes')
__update_codes()
print('Done!')
|
Update hashing to match eagel eye |
var passport = require('passport')
var util = require('util')
var crypto = require('crypto')
var db = require('mongo-promise')
db.shortcut('clients')
function ClientKeyStrategy() {
this.name = 'client-key'
};
util.inherits(ClientKeyStrategy, passport.Strategy)
ClientKeyStrategy.prototype.authenticate = function(req, options) {
var authId = req.param('authId')
var authHash = req.param('authHash')
var authTimestamp = req.param('authTimestamp')
if (!authId || !authHash || !authTimestamp) return this.fail()
db.clients.find({ authId: authId }).then(function(clients) {
var client = clients[0]
return this.fail()
}
req.user = client
this.pass()
}.bind(this))
};
module.exports = ClientKeyStrategy;
|
var passport = require('passport')
var util = require('util')
var crypto = require('crypto')
var db = require('mongo-promise')
db.shortcut('clients')
function ClientKeyStrategy() {
this.name = 'client-key'
};
util.inherits(ClientKeyStrategy, passport.Strategy)
ClientKeyStrategy.prototype.authenticate = function(req, options) {
var authId = req.param('authId')
var authHash = req.param('authHash')
var authTimestamp = req.param('authTimestamp')
if (!authId || !authHash || !authTimestamp) return this.fail()
db.clients.find({ authId: authId }).then(function(clients) {
var client = clients[0]
if (!client || crypto.createHash('md5').update(authTimestamp).update(client.authSecret).digest('hex') != authHash) {
return this.fail()
}
req.user = client
this.pass()
}.bind(this))
};
module.exports = ClientKeyStrategy;
|
Fix private value in Grave | package com.ForgeEssentials.afterlife;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.inventory.InventoryBasic;
import net.minecraft.item.ItemStack;
public class InventroyGrave extends InventoryBasic
{
private Grave grave;
public InventroyGrave(Grave grave)
{
super(grave.owner + "'s grave.", grave.getSize());
this.grave = grave;
}
@Override
public void openChest()
{
for (int i = 0; i < getSizeInventory(); i++)
{
setInventorySlotContents(i, (ItemStack) null);
}
for (int i = 0; i < grave.inv.length; i++)
{
setInventorySlotContents(i, grave.inv[i].copy());
}
super.openChest();
}
@Override
public void closeChest()
{
List<ItemStack> list = new ArrayList<ItemStack>();
for (int i = 0; i < getSizeInventory(); i++)
{
ItemStack is = getStackInSlot(i);
if (is != null)
{
list.add(is);
}
}
grave.inv = list.toArray(new ItemStack[list.size()]);
grave.checkGrave();
super.closeChest();
}
}
| package com.ForgeEssentials.afterlife;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.inventory.InventoryBasic;
import net.minecraft.item.ItemStack;
public class InventroyGrave extends InventoryBasic
{
private Grave grave;
public InventroyGrave(Grave grave)
{
super(grave.owner + "'s grave.", grave.getSize());
this.grave = grave;
}
@Override
public void openChest()
{
for (int i = 0; i < getSizeInventory(); i++)
{
setInventorySlotContents(i, (ItemStack) null);
}
for (int i = 0; i < grave.inv.length; i++)
{
setInventorySlotContents(i, grave.inv[i].copy());
}
super.openChest();
}
@Override
public void closeChest()
{
List<ItemStack> list = new ArrayList<ItemStack>();
for (ItemStack is : inventoryContents)
{
if (is != null)
{
list.add(is);
}
}
grave.inv = list.toArray(new ItemStack[list.size()]);
grave.checkGrave();
super.closeChest();
}
}
|
Add support for appending fixtures | <?php namespace Nord\Lumen\Doctrine\ORM\Console;
use Doctrine\Common\DataFixtures\Executor\ORMExecutor;
use Doctrine\Common\DataFixtures\Loader;
use Doctrine\Common\DataFixtures\Purger\ORMPurger;
use Symfony\Component\Console\Input\InputOption;
class FixturesLoadCommand extends DoctrineCommand
{
/**
* @var string
*/
protected $name = 'doctrine:fixtures:load';
/**
* @var string
*/
protected $description = 'Loads data fixtures into the database';
/**
* @inheritdoc
*/
public function fire()
{
$loader = new Loader();
$this->info('Loading fixtures ...');
$loader->loadFromDirectory($this->option('path'));
$fixtures = $loader->getFixtures();
$purger = new ORMPurger();
$executor = new ORMExecutor($this->getEntityManager(), $purger);
$executor->execute($fixtures, $this->option('append'));
$this->info('Fixtures loaded!');
}
/**
* @return array
*/
protected function getOptions()
{
return [
['path', null, InputOption::VALUE_REQUIRED, 'Path to fixtures.'],
['append', true, InputOption::VALUE_OPTIONAL, 'Whether to append fixtures and preserve the database.'],
];
}
}
| <?php namespace Nord\Lumen\Doctrine\ORM\Console;
use Doctrine\Common\DataFixtures\Executor\ORMExecutor;
use Doctrine\Common\DataFixtures\Loader;
use Doctrine\Common\DataFixtures\Purger\ORMPurger;
use Symfony\Component\Console\Input\InputOption;
class FixturesLoadCommand extends DoctrineCommand
{
/**
* @var string
*/
protected $name = 'doctrine:fixtures:load';
/**
* @var string
*/
protected $description = 'Loads data fixtures into the database';
/**
* @inheritdoc
*/
public function fire()
{
$loader = new Loader();
$this->info('Loading fixtures ...');
$loader->loadFromDirectory($this->option('path'));
$fixtures = $loader->getFixtures();
$purger = new ORMPurger();
$executor = new ORMExecutor($this->getEntityManager(), $purger);
$executor->execute($fixtures);
$this->info('Fixtures loaded!');
}
/**
* @return array
*/
protected function getOptions()
{
return [
['path', false, InputOption::VALUE_REQUIRED, 'Path to fixtures.'],
];
}
}
|
Add instalment on quote process | <?php
abstract class Ebanx_Gateway_Model_Payment_CreditCard extends Ebanx_Gateway_Model_Payment
{
protected $_canSaveCc = false;
public function __construct()
{
parent::__construct();
$this->ebanx = Mage::getSingleton('ebanx/api')->ebanxCreditCard();
}
public function setupData()
{
parent::setupData();
$this->data->setGatewayFields(Mage::app()->getRequest()->getPost('payment'));
$this->data->setInstalmentTerms(
$this->gateway->getPaymentTermsForCountryAndValue(
$this->helper->transformCountryCodeToName($this->data->getBillingAddress()->getCountry()),
$this->data->getAmountTotal()
)
);
}
public function transformPaymentData()
{
$this->paymentData = $this->adapter->transformCard($this->data);
}
public function persistPayment()
{
parent::persistPayment();
$gatewayFields = $this->data->getGatewayFields();
$this->payment->setInstalments($gatewayFields['instalments']);
}
}
| <?php
abstract class Ebanx_Gateway_Model_Payment_CreditCard extends Ebanx_Gateway_Model_Payment
{
protected $_canSaveCc = false;
public function __construct()
{
parent::__construct();
$this->ebanx = Mage::getSingleton('ebanx/api')->ebanxCreditCard();
}
public function setupData()
{
parent::setupData();
$this->data->setGatewayFields(Mage::app()->getRequest()->getPost('payment'));
$this->data->setInstalmentTerms(
$this->gateway->getPaymentTermsForCountryAndValue(
$this->helper->transformCountryCodeToName($this->data->getBillingAddress()->getCountry()),
$this->data->getAmountTotal()
)
);
}
public function transformPaymentData()
{
$this->paymentData = $this->adapter->transformCard($this->data);
}
}
|
Include possible additional lines in output | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Drew Brokke
# Copyright (c) 2015 Drew Brokke
#
# License: MIT
#
"""This module exports the CheckSourceFormatting plugin class."""
from SublimeLinter.lint import NodeLinter, util
class CheckSourceFormatting(NodeLinter):
"""Provides an interface to check-source-formatting."""
syntax = ('javascript', 'html', 'css', 'velocity', 'freemarker', 'java server pages (jsp)', 'sass')
cmd = 'check_sf @ --no-color'
version_args = '--version'
version_re = r'(?P<version>\d+\.\d+\.\d+)'
version_requirement = '>= 1.0'
regex = r'^.+?(?P<line>\d+).*?: (?P<message>.+)'
multiline = False
line_col_base = (1, 1)
tempfile_suffix = '-'
error_stream = util.STREAM_BOTH
comment_re = r'\s*/[/*]'
| #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Drew Brokke
# Copyright (c) 2015 Drew Brokke
#
# License: MIT
#
"""This module exports the CheckSourceFormatting plugin class."""
from SublimeLinter.lint import NodeLinter, util
class CheckSourceFormatting(NodeLinter):
"""Provides an interface to check-source-formatting."""
syntax = ('javascript', 'html', 'css', 'velocity', 'freemarker', 'java server pages (jsp)', 'sass')
cmd = 'check_sf @ --no-color'
version_args = '--version'
version_re = r'(?P<version>\d+\.\d+\.\d+)'
version_requirement = '>= 1.0'
regex = r'^.+?(?P<line>\d+): (?P<message>.+)'
multiline = False
line_col_base = (1, 1)
tempfile_suffix = '-'
error_stream = util.STREAM_BOTH
comment_re = r'\s*/[/*]'
|
Remove accidental extra line - shouldn't have been part of last commit | package nallar.tickthreading.mod;
import me.nallar.modpatcher.ModPatcher;
import nallar.tickthreading.log.Log;
import nallar.tickthreading.util.PropertyUtil;
import nallar.tickthreading.util.Version;
import nallar.tickthreading.util.unsafe.UnsafeUtil;
import net.minecraftforge.fml.relauncher.IFMLLoadingPlugin;
import java.util.*;
@IFMLLoadingPlugin.Name("@MOD_NAME@Core")
@IFMLLoadingPlugin.MCVersion("@MC_VERSION@")
@IFMLLoadingPlugin.SortingIndex(1002)
public class CoreMod implements IFMLLoadingPlugin {
static {
if (PropertyUtil.get("removeSecurityManager", false)) {
UnsafeUtil.removeSecurityManager();
}
ModPatcher.requireVersion("latest", "beta");
Log.info(Version.DESCRIPTION + " CoreMod initialised");
}
@Override
public String[] getASMTransformerClass() {
return new String[0];
}
@Override
public String getModContainerClass() {
return null;
}
@Override
public String getSetupClass() {
return ModPatcher.getSetupClass();
}
@Override
public void injectData(Map<String, Object> map) {
ModPatcher.loadMixins("nallar.tickthreading.mixin");
}
@Override
public String getAccessTransformerClass() {
return null;
}
}
| package nallar.tickthreading.mod;
import me.nallar.modpatcher.ModPatcher;
import nallar.tickthreading.log.Log;
import nallar.tickthreading.util.PropertyUtil;
import nallar.tickthreading.util.Version;
import nallar.tickthreading.util.unsafe.UnsafeUtil;
import net.minecraftforge.fml.relauncher.IFMLLoadingPlugin;
import java.util.*;
@IFMLLoadingPlugin.Name("@MOD_NAME@Core")
@IFMLLoadingPlugin.MCVersion("@MC_VERSION@")
@IFMLLoadingPlugin.SortingIndex(1002)
public class CoreMod implements IFMLLoadingPlugin {
public static boolean
static {
if (PropertyUtil.get("removeSecurityManager", false)) {
UnsafeUtil.removeSecurityManager();
}
ModPatcher.requireVersion("latest", "beta");
Log.info(Version.DESCRIPTION + " CoreMod initialised");
}
@Override
public String[] getASMTransformerClass() {
return new String[0];
}
@Override
public String getModContainerClass() {
return null;
}
@Override
public String getSetupClass() {
return ModPatcher.getSetupClass();
}
@Override
public void injectData(Map<String, Object> map) {
ModPatcher.loadMixins("nallar.tickthreading.mixin");
}
@Override
public String getAccessTransformerClass() {
return null;
}
}
|
Fix casing of bluebird import | import {browser} from '../mini-testium-mocha';
import {delay} from 'bluebird';
describe('proxy', () => {
before(browser.beforeHook);
describe('handles errors', () => {
it('with no content type and preserves status code', () =>
browser
.navigateTo('/').assertStatusCode(200)
.navigateTo('/error').assertStatusCode(500));
it('that crash and preserves status code', () =>
browser.navigateTo('/crash').assertStatusCode(500));
});
it('handles request abortion', async () => {
// loads a page that has a resource that will
// be black holed
await browser
.navigateTo('/blackholed-resource.html').assertStatusCode(200);
// this can't simply be sync
// because firefox blocks dom-ready
// if we don't wait on the client-side
await delay(50);
// when navigating away, the proxy should
// abort the resource request;
// this should not interfere with the new page load
// or status code retrieval
await browser.navigateTo('/').assertStatusCode(200);
});
it('handles hashes in urls', () =>
browser.navigateTo('/#deals').assertStatusCode(200));
});
| import {browser} from '../mini-testium-mocha';
import {delay} from 'Bluebird';
describe('proxy', () => {
before(browser.beforeHook);
describe('handles errors', () => {
it('with no content type and preserves status code', () =>
browser
.navigateTo('/').assertStatusCode(200)
.navigateTo('/error').assertStatusCode(500));
it('that crash and preserves status code', () =>
browser.navigateTo('/crash').assertStatusCode(500));
});
it('handles request abortion', async () => {
// loads a page that has a resource that will
// be black holed
await browser
.navigateTo('/blackholed-resource.html').assertStatusCode(200);
// this can't simply be sync
// because firefox blocks dom-ready
// if we don't wait on the client-side
await delay(50);
// when navigating away, the proxy should
// abort the resource request;
// this should not interfere with the new page load
// or status code retrieval
await browser.navigateTo('/').assertStatusCode(200);
});
it('handles hashes in urls', () =>
browser.navigateTo('/#deals').assertStatusCode(200));
});
|
Simplify test for controller_map key within $config['view_manager']. | <?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Mvc\Service;
use ArrayAccess;
use Zend\ServiceManager\FactoryInterface;
use Zend\Mvc\View\Http\InjectTemplateListener;
use Zend\ServiceManager\ServiceLocatorInterface;
class InjectTemplateListenerFactory implements FactoryInterface
{
/**
* Create and return an InjectTemplateListener instance.
*
* @param ServiceLocatorInterface $serviceLocator
* @return InjectTemplateListener
*/
public function createService(ServiceLocatorInterface $serviceLocator)
{
$listener = new InjectTemplateListener();
$config = $serviceLocator->get('Config');
if (isset($config['view_manager']['controller_map'])
&& (is_array($config['view_manager']['controller_map']))
) {
$listener->setControllerMap($config['view_manager']['controller_map']);
}
return $listener;
}
}
| <?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Mvc\Service;
use ArrayAccess;
use Zend\ServiceManager\FactoryInterface;
use Zend\Mvc\View\Http\InjectTemplateListener;
use Zend\ServiceManager\ServiceLocatorInterface;
class InjectTemplateListenerFactory implements FactoryInterface
{
/**
* Create and return an InjectTemplateListener instance.
*
* @param ServiceLocatorInterface $serviceLocator
* @return InjectTemplateListener
*/
public function createService(ServiceLocatorInterface $serviceLocator)
{
$listener = new InjectTemplateListener();
$config = $serviceLocator->get('Config');
if (isset($config['view_manager'])
&& (is_array($config['view_manager']) || $config['view_manager'] instanceof ArrayAccess)
&& isset($config['view_manager']['controller_map'])
&& (is_array($config['view_manager']['controller_map']))
) {
$listener->setControllerMap($config['view_manager']['controller_map']);
}
return $listener;
}
}
|
Handle errors from agile source | /* jshint browser: true, jquery: true */
/* global AgileSprint:false, console:false */
var AgileSprintManager = function(options) {
// if(options.server === null || options.server === undefined) {
// return null;
// }
this.widgetManager = (options.widgetManager !== null && options.widgetManager !== undefined) ? options.widgetManager : null;
this.panelManager = (options.panelManager !== null && options.panelManager !== undefined) ? options.panelManager : null;
this.server = options.server;
};
AgileSprintManager.prototype.processMessages = function(server, id, content) {
var processed = false;
switch (id) {
case AgileSprint.MESSAGE_STATS:
this.__receivedStats(server, content);
processed = true;
break;
case AgileSprint.MESSAGE_CONNECTIVITY_ERROR:
this.__receivedError(server, content);
processed = true;
break;
}
return processed;
};
AgileSprintManager.prototype.__receivedStats = function(server, d) {
if(this.widgetManager !== null) {
this.widgetManager.receivedData(d);
}
};
AgileSprintManager.prototype.__receivedError = function(server, d) {
if(this.widgetManager !== null) {
this.widgetManager.receivedError(d);
}
}; | /* jshint browser: true, jquery: true */
/* global AgileSprint:false, console:false */
var AgileSprintManager = function(options) {
// if(options.server === null || options.server === undefined) {
// return null;
// }
this.widgetManager = (options.widgetManager !== null && options.widgetManager !== undefined) ? options.widgetManager : null;
this.panelManager = (options.panelManager !== null && options.panelManager !== undefined) ? options.panelManager : null;
this.server = options.server;
};
AgileSprintManager.prototype.processMessages = function(server, id, content) {
var processed = false;
switch (id) {
case AgileSprint.MESSAGE_STATS:
this.__receivedStats(server, content);
processed = true;
break;
}
return processed;
};
AgileSprintManager.prototype.__receivedStats = function(server, d) {
if(this.widgetManager !== null) {
this.widgetManager.receivedData(d);
}
}; |
Fix null pointer error for asGuests in batchRegister | package org.xcolab.view.pages.contestmanagement.beans;
import org.hibernate.validator.constraints.NotBlank;
import java.io.Serializable;
public class BatchRegisterBean implements Serializable {
@NotBlank
private boolean asGuests;
@NotBlank
private String batchText;
public String getBatchText() {
return batchText;
}
public void setBatchText(String batchText) {
this.batchText = batchText;
}
public boolean getAsGuests() {
return asGuests;
}
public void setAsGuest(boolean asGuests) {
this.asGuests = asGuests;
}
@Override
public String toString() {
return "BatchRegisterBean [batchText='" + batchText + "', asGuests='" + String.valueOf(asGuests) + "']";
}
}
| package org.xcolab.view.pages.contestmanagement.beans;
import org.hibernate.validator.constraints.NotBlank;
import java.io.Serializable;
public class BatchRegisterBean implements Serializable {
@NotBlank
private Boolean asGuests;
@NotBlank
private String batchText;
public String getBatchText() {
return batchText;
}
public void setBatchText(String batchText) {
this.batchText = batchText;
}
public Boolean getAsGuests() {
return asGuests;
}
public void setAsGuest(Boolean asGuests) {
this.asGuests = asGuests;
}
@Override
public String toString() {
return "BatchRegisterBean [batchText='" + batchText + "', asGuests='" + asGuests.toString() + "']";
}
}
|
Add named function parameters for clarity | package sirius
import (
"time"
)
type Execution struct {
Ext Extension
Msg Message
Cfg ExtensionConfig
}
type ExecutionResult struct {
Err error
Action MessageAction
}
type ExtensionRunner interface {
Run(exe []Execution, res chan<- ExecutionResult, timeout time.Duration)
}
type AsyncRunner struct{}
func NewExecution(x Extension, m Message, cfg ExtensionConfig) *Execution {
return &Execution{
Ext: x,
Msg: m,
Cfg: cfg,
}
}
func NewAsyncRunner() *AsyncRunner {
return &AsyncRunner{}
}
// Run executes all extensions in exe, and returns all ExecutionResults that
// are received before timeout has elapsed.
func (r *AsyncRunner) Run(exe []Execution, res chan<- ExecutionResult, timeout time.Duration) {
er := make(chan ExecutionResult, len(exe))
for _, e := range exe {
go func(ex Execution, r chan<- ExecutionResult) {
a, err := ex.Ext.Run(ex.Msg, ex.Cfg)
r <- ExecutionResult{
Err: err,
Action: a,
}
}(e, er)
}
Execution:
for range exe {
select {
case <-time.After(timeout):
break Execution
case res <- <-er:
}
}
close(res)
}
| package sirius
import (
"time"
)
type Execution struct {
Ext Extension
Msg Message
Cfg ExtensionConfig
}
type ExecutionResult struct {
Err error
Action MessageAction
}
type ExtensionRunner interface {
Run([]Execution, chan<- ExecutionResult, time.Duration)
}
type AsyncRunner struct{}
func NewExecution(x Extension, m Message, cfg ExtensionConfig) *Execution {
return &Execution{
Ext: x,
Msg: m,
Cfg: cfg,
}
}
func NewAsyncRunner() *AsyncRunner {
return &AsyncRunner{}
}
// Run executes all extensions in exe, and returns all ExecutionResults that
// are received before timeout has elapsed.
func (r *AsyncRunner) Run(exe []Execution, res chan<- ExecutionResult, timeout time.Duration) {
er := make(chan ExecutionResult, len(exe))
for _, e := range exe {
go func(ex Execution, r chan<- ExecutionResult) {
a, err := ex.Ext.Run(ex.Msg, ex.Cfg)
r <- ExecutionResult{
Err: err,
Action: a,
}
}(e, er)
}
Execution:
for range exe {
select {
case <-time.After(timeout):
break Execution
case res <- <-er:
}
}
close(res)
}
|
Fix message tests after in message.parseMessage args three commits ago
(three commits ago is 08a6c170daa79e74ba538c928e183f441a0fb441) | import os
import unittest
from txdbus import error, message
class MessageTester(unittest.TestCase):
def test_too_long(self):
class E(message.ErrorMessage):
_maxMsgLen = 1
def c():
E('foo.bar', 5)
self.assertRaises(error.MarshallingError, c)
def test_reserved_path(self):
def c():
message.MethodCallMessage('/org/freedesktop/DBus/Local', 'foo')
self.assertRaises(error.MarshallingError, c)
def test_invalid_message_type(self):
class E(message.ErrorMessage):
_messageType=99
try:
message.parseMessage(E('foo.bar', 5).rawMessage, oobFDs=[])
self.assertTrue(False)
except Exception as e:
self.assertEquals(str(e), 'Unknown Message Type: 99')
| import os
import unittest
from txdbus import error, message
class MessageTester(unittest.TestCase):
def test_too_long(self):
class E(message.ErrorMessage):
_maxMsgLen = 1
def c():
E('foo.bar', 5)
self.assertRaises(error.MarshallingError, c)
def test_reserved_path(self):
def c():
message.MethodCallMessage('/org/freedesktop/DBus/Local', 'foo')
self.assertRaises(error.MarshallingError, c)
def test_invalid_message_type(self):
class E(message.ErrorMessage):
_messageType=99
try:
message.parseMessage(E('foo.bar', 5).rawMessage)
self.assertTrue(False)
except Exception as e:
self.assertEquals(str(e), 'Unknown Message Type: 99')
|
Handle case with no configuration options | /*
* Javacript for the API Configuration
*/
/* jshint browser: true */
/* jshint -W097 */
/* globals apiRequest */
'use strict';
export class apiConfiguration {
constructor(resource, resolve, reject) {
var obj = this;
apiRequest('GET', resource, 'maxResults=all')
.then(function(response) {
var v = JSON.parse(response.responseText).data;
if (v) {
v.forEach(function(e) {
obj[e.field] = e;
});
}
if (resolve) {
resolve(response);
}
})
.catch(function(response) {
if (response instanceof Error) { throw response; }
if (reject) {
reject(response);
}
});
}
}
| /*
* Javacript for the API Configuration
*/
/* jshint browser: true */
/* jshint -W097 */
/* globals apiRequest */
'use strict';
export class apiConfiguration {
constructor(resource, resolve, reject) {
var obj = this;
apiRequest('GET', resource, 'maxResults=all')
.then(function(response) {
var v = JSON.parse(response.responseText).data;
v.forEach(function(e) {
obj[e.field] = e;
});
if (resolve) {
resolve(response);
}
})
.catch(function(response) {
if (response instanceof Error) { throw response; }
if (reject) {
reject(response);
}
});
}
}
|
Use static Item.CREATE rather than Item.CONFIGURE and check permission
from the given container. | package hudson.plugins.copyProjectLink;
import hudson.model.Action;
import hudson.model.Item;
import hudson.model.ItemGroup;
import hudson.model.AbstractProject;
import hudson.model.Hudson;
import hudson.security.AccessControlled;
public class CopyProjectAction implements Action {
final private AbstractProject<?, ?> project;
public CopyProjectAction(AbstractProject project) {
this.project = project;
}
public String getCloneName() {
return project.getDisplayName() + "-clone";
}
public String getProjectName() {
return project.getDisplayName();
}
public String getIconFileName() {
if (hasPermission()) {
return "/plugin/copy-project-link/img/edit-copy.png";
}
return null;
}
public String getDisplayName() {
if (hasPermission()) {
return "Copy project";
}
return null;
}
public String getUrlName() {
if(hasPermission()) {
return "copy-project";
}
return null;
}
private boolean hasPermission(){
ItemGroup parent = project.getParent();
if (parent instanceof AccessControlled) {
AccessControlled accessControlled = (AccessControlled)parent;
return accessControlled.hasPermission(Item.CREATE);
}
return Hudson.getInstance().hasPermission(Item.CREATE);
}
}
| package hudson.plugins.copyProjectLink;
import hudson.model.Action;
import hudson.model.AbstractProject;
import hudson.model.Hudson;
public class CopyProjectAction implements Action {
final private AbstractProject<?, ?> project;
public CopyProjectAction(AbstractProject project) {
this.project = project;
}
public String getCloneName() {
return project.getDisplayName() + "-clone";
}
public String getProjectName() {
return project.getDisplayName();
}
public String getIconFileName() {
if (hasPermission()) {
return "/plugin/copy-project-link/img/edit-copy.png";
}
return null;
}
public String getDisplayName() {
if (hasPermission()) {
return "Copy project";
}
return null;
}
public String getUrlName() {
if(hasPermission()) {
return "copy-project";
}
return null;
}
private boolean hasPermission(){
return Hudson.getInstance().hasPermission(project.CONFIGURE);
}
}
|
[FIX] l10n_br_coa_simple: Use admin user to create COA | # Copyright (C) 2020 - Gabriel Cardoso de Faria <gabriel.cardoso@kmee.com.br>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from odoo import api, tools, SUPERUSER_ID
def post_init_hook(cr, registry):
env = api.Environment(cr, SUPERUSER_ID, {})
coa_simple_tmpl = env.ref(
'l10n_br_coa_simple.l10n_br_coa_simple_chart_template')
if env['ir.module.module'].search_count([
('name', '=', 'l10n_br_account'),
('state', '=', 'installed'),
]):
from odoo.addons.l10n_br_account.hooks import load_fiscal_taxes
# Relate fiscal taxes to account taxes.
load_fiscal_taxes(env, coa_simple_tmpl)
# Load COA to Demo Company
if not tools.config.get('without_demo'):
user_admin = env.ref('base.user_admin')
user_admin.company_id = env.ref(
'l10n_br_base.empresa_simples_nacional')
coa_simple_tmpl.sudo(
user=user_admin.id).try_loading_for_current_company()
user_admin.company_id = env.ref('base.main_company')
| # Copyright (C) 2020 - Gabriel Cardoso de Faria <gabriel.cardoso@kmee.com.br>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from odoo import api, tools, SUPERUSER_ID
def post_init_hook(cr, registry):
env = api.Environment(cr, SUPERUSER_ID, {})
coa_simple_tmpl = env.ref(
'l10n_br_coa_simple.l10n_br_coa_simple_chart_template')
if env['ir.module.module'].search_count([
('name', '=', 'l10n_br_account'),
('state', '=', 'installed'),
]):
from odoo.addons.l10n_br_account.hooks import load_fiscal_taxes
# Relate fiscal taxes to account taxes.
load_fiscal_taxes(env, coa_simple_tmpl)
# Load COA to Demo Company
if not tools.config.get('without_demo'):
env.user.company_id = env.ref(
'l10n_br_fiscal.empresa_simples_nacional')
coa_simple_tmpl.try_loading_for_current_company()
|
Fix error with app prefix. We will assume all urls fall under the same root as the landing page | from django.conf import settings
from regulations.generator import generator
from django.core.urlresolvers import reverse
def get_layer_list(names):
layer_names = generator.LayerCreator.LAYERS
return set(l.lower() for l in names.split(',') if l.lower() in layer_names)
def handle_specified_layers(
layer_names, regulation_id, version, sectional=False):
layer_list = get_layer_list(layer_names)
layer_creator = generator.LayerCreator()
layer_creator.add_layers(layer_list, regulation_id, version, sectional)
return layer_creator.get_appliers()
def handle_diff_layers(
layer_names, regulation_id, older, newer, sectional=False):
layer_list = get_layer_list(layer_names)
layer_creator = generator.DiffLayerCreator(newer)
layer_creator.add_layers(layer_list, regulation_id, older, sectional)
return layer_creator.get_appliers()
def add_extras(context):
context['env'] = 'source' if settings.DEBUG else 'built'
prefix = reverse('regulation_landing_view', kwargs={'label_id': '9999'})
prefix = prefix.replace('9999', '')
if prefix != '/': # Strip final slash
prefix = prefix[:-1]
context['APP_PREFIX'] = prefix
context['GOOGLE_ANALYTICS_SITE'] = settings.GOOGLE_ANALYTICS_SITE
context['GOOGLE_ANALYTICS_ID'] = settings.GOOGLE_ANALYTICS_ID
return context
| from django.conf import settings
from regulations.generator import generator
from django.core.urlresolvers import get_script_prefix
def get_layer_list(names):
layer_names = generator.LayerCreator.LAYERS
return set(l.lower() for l in names.split(',') if l.lower() in layer_names)
def handle_specified_layers(
layer_names, regulation_id, version, sectional=False):
layer_list = get_layer_list(layer_names)
layer_creator = generator.LayerCreator()
layer_creator.add_layers(layer_list, regulation_id, version, sectional)
return layer_creator.get_appliers()
def handle_diff_layers(
layer_names, regulation_id, older, newer, sectional=False):
layer_list = get_layer_list(layer_names)
layer_creator = generator.DiffLayerCreator(newer)
layer_creator.add_layers(layer_list, regulation_id, older, sectional)
return layer_creator.get_appliers()
def add_extras(context):
context['env'] = 'source' if settings.DEBUG else 'built'
context['APP_PREFIX'] = get_script_prefix()
context['GOOGLE_ANALYTICS_SITE'] = settings.GOOGLE_ANALYTICS_SITE
context['GOOGLE_ANALYTICS_ID'] = settings.GOOGLE_ANALYTICS_ID
return context
|
Expand the error message to recommend updating REDCap versions | <?php
namespace Vanderbilt\EmailTriggerExternalModule;
use ExternalModules\AbstractExternalModule;
use ExternalModules\ExternalModules;
require_once 'EmailTriggerExternalModule.php';
$passthruData = $module->resetSurveyAndGetCodes($_REQUEST['pid'], $_REQUEST['record'], $_REQUEST['instrument'], $_REQUEST['event']);
$returnCode = $passthruData['return_code'];
$hash = $passthruData['hash'];
if($returnCode == $_REQUEST['returnCode']){
$surveyLink = APP_PATH_SURVEY_FULL."?s=".$hash;
$link = ($_REQUEST['returnCode'] == "NULL")? "":"<input type='hidden' value='".$returnCode."' name='__code'/>";
?>
<html>
<body>
<form id='passthruform' name='passthruform' action='<?=$surveyLink?>' method='post' enctype='multipart/form-data'>
<?=$link?>
<input type='hidden' value='1' name='__prefill' />
</form>
<script type='text/javascript'>
window.onload = function(){
document.passthruform.submit();
}
</script>
</body>
</html>
<?php }
else {
echo "Error: Incorrect return code specified.<br /><br />This error can also be caused by using an outdated version of the External Modules framework with a longitudinal study project. You may be able to correct this error by updating to a version of REDCap above 8.7.0";
}?>
| <?php
namespace Vanderbilt\EmailTriggerExternalModule;
use ExternalModules\AbstractExternalModule;
use ExternalModules\ExternalModules;
require_once 'EmailTriggerExternalModule.php';
$passthruData = $module->resetSurveyAndGetCodes($_REQUEST['pid'], $_REQUEST['record'], $_REQUEST['instrument'], $_REQUEST['event']);
$returnCode = $passthruData['return_code'];
$hash = $passthruData['hash'];
if($returnCode == $_REQUEST['returnCode']){
$surveyLink = APP_PATH_SURVEY_FULL."?s=".$hash;
$link = ($_REQUEST['returnCode'] == "NULL")? "":"<input type='hidden' value='".$returnCode."' name='__code'/>";
?>
<html>
<body>
<form id='passthruform' name='passthruform' action='<?=$surveyLink?>' method='post' enctype='multipart/form-data'>
<?=$link?>
<input type='hidden' value='1' name='__prefill' />
</form>
<script type='text/javascript'>
window.onload = function(){
document.passthruform.submit();
}
</script>
</body>
</html>
<?php }
else {
echo "Error: Incorrect return code specified";
}?>
|
Check blacklist against duplicate entries as well
Additionally, refactor into a def test_* to run like the other unit tests. | #!/usr/bin/env python3
from glob import glob
def test_blacklist_integrity():
for bl_file in glob('bad_*.txt') + glob('blacklisted_*.txt'):
with open(bl_file, 'r') as lines:
seen = dict()
for lineno, line in enumerate(lines, 1):
if line.endswith('\r\n'):
raise(ValueError('{0}:{1}:DOS line ending'.format(bl_file, lineno)))
if not line.endswith('\n'):
raise(ValueError('{0}:{1}:No newline'.format(bl_file, lineno)))
if line == '\n':
raise(ValueError('{0}:{1}:Empty line'.format(bl_file, lineno)))
if line in seen:
raise(ValueError('{0}:{1}:Duplicate entry {2} (also on line {3})'.format(
bl_file, lineno, line.rstrip('\n'), seen[line])))
seen[line] = lineno
| #!/usr/bin/env python3
from glob import glob
for bl_file in glob('bad_*.txt') + glob('blacklisted_*.txt'):
with open(bl_file, 'r') as lines:
for lineno, line in enumerate(lines, 1):
if line.endswith('\r\n'):
raise(ValueError('{0}:{1}:DOS line ending'.format(bl_file, lineno)))
if not line.endswith('\n'):
raise(ValueError('{0}:{1}:No newline'.format(bl_file, lineno)))
if line == '\n':
raise(ValueError('{0}:{1}:Empty line'.format(bl_file, lineno)))
|
Use the original COUNTRIES_FLAG_URL string for the JS replace. | from django.conf import settings
from django.forms import widgets
from django.utils.safestring import mark_safe
COUNTRY_CHANGE_HANDLER = """
this.nextSibling.src = %s.replace('{code}', this.value.toLowerCase() || '__').replace('{code_upper}', this.value.toUpperCase() || '__');
"""
FLAG_IMAGE = """<img style="margin: 6px 4px; position: absolute;" src="%s" id="%%s-flag">"""
class CountrySelectWidget(widgets.Select):
def render(self, name, value, attrs=None):
attrs = attrs or {}
attrs['onchange'] = COUNTRY_CHANGE_HANDLER % settings.COUNTRIES_FLAG_URL
data = super(CountrySelectWidget, self).render(name, value, attrs)
data += mark_safe((FLAG_IMAGE % settings.COUNTRIES_FLAG_URL) % (
settings.STATIC_URL,
unicode(value).lower() or '__',
attrs['id']
))
return data
| from django.conf import settings
from django.forms import widgets
from django.utils.safestring import mark_safe
COUNTRY_CHANGE_HANDLER = """
this.nextSibling.src = this.nextSibling.src.replace(/[a-z_]{2}(\.[a-zA-Z]*)$/, (this.value.toLowerCase() || '__') + '$1');
"""
FLAG_IMAGE = """<img style="margin: 6px 4px; position: absolute;" src="%s" id="%%s-flag">"""
class CountrySelectWidget(widgets.Select):
def render(self, name, value, attrs=None):
attrs = attrs or {}
attrs['onchange'] = COUNTRY_CHANGE_HANDLER
data = super(CountrySelectWidget, self).render(name, value, attrs)
data += mark_safe((FLAG_IMAGE % settings.COUNTRIES_FLAG_URL) % (
settings.STATIC_URL,
unicode(value).lower() or '__',
attrs['id']
))
return data
|
Fix test with ES6 compatible Promise | var suite = new core.testrunner.Suite("Flow");
suite.test("sequence", function() {
var result = [];
var func1 = function() {
return new core.event.Promise(function(resolve) {
core.Function.timeout(function() {
result.push("func1");
resolve("func1");
}, null, 50);
});
};
var func2 = function() {
result.push("func2");
return "func2";
};
var func3 = function() {
result.push("func3");
return "func3";
};
core.event.Flow.sequence([func1, func2, func3]).then(function() {
this.isIdentical(result.length, 3);
this.isIdentical(result[0], "func1");
this.isIdentical(result[1], "func2");
this.isIdentical(result[2], "func3");
this.done();
}, null, this).done();
}, 4, 1000);
| var suite = new core.testrunner.Suite("Flow");
suite.test("sequence", function() {
var result = [];
var func1 = function() {
var promise = new core.event.Promise;
core.Function.timeout(function() {
result.push("func1");
promise.fulfill("func1");
}, null, 50);
return promise;
};
var func2 = function() {
result.push("func2");
return "func2";
};
var func3 = function() {
result.push("func3");
return "func3";
};
core.event.Flow.sequence([func1, func2, func3]).then(function() {
this.isIdentical(result.length, 3);
this.isIdentical(result[0], "func1");
this.isIdentical(result[1], "func2");
this.isIdentical(result[2], "func3");
this.done();
}, null, this).done();
}, 4, 1000);
|
Add code to block deletion of a folder | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
(function (aGlobal) {
var DeleteOnlyEmptyFolder = {
isEmpty : function(aFolder) {
return true;
},
init: function() {
gFolderTreeController.__delete_only_empty_folder__deleteFolder = gFolderTreeController.deleteFolder;
gFolderTreeController.deleteFolder = function(aFolder, ...aArgs) {
if (!DeleteOnlyEmptyFolder.isEmpty(aFolder))
return;
return gFolderTreeController.__delete_only_empty_folder__deleteFolder.apply(this, [aFolder].concat(aArgs));
};
}
};
document.addEventListener('DOMContentLoaded', function onDOMContentLoaded(aEvent) {
document.removeEventListener('DOMContentLoaded', onDOMContentLoaded);
DeleteOnlyEmptyFolder.init();
});
aGlobal.DeleteOnlyEmptyFolder = DeleteOnlyEmptyFolder;
})(this);
| /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
(function (aGlobal) {
var Ci = Components.interfaces;
var Cc = Components.classes;
var ObserverService = Cc['@mozilla.org/observer-service;1']
.getService(Ci.nsIObserverService);
var DeleteOnlyEmptyFolder = {
// nsIObserver
observe: function observe(aEvent) {
ObserverService.removeObserver(this, 'mail-startup-done', false);
this.init();
}
};
document.addEventListener('DOMContentLoaded', function onDOMContentLoaded(aEvent) {
document.removeEventListener('DOMContentLoaded', onDOMContentLoaded);
ObserverService.addObserver(DeleteOnlyEmptyFolder, 'mail-startup-done', false);
});
aGlobal.DeleteOnlyEmptyFolder = DeleteOnlyEmptyFolder;
})(this);
|
Fix writing method of anonymous function | <?php
/**
* This file is part of the php-utils.php package.
*
* Copyright (C) 2015 Tadatoshi Tokutake <tadatoshi.tokutake@gmail.com>
*
* Licensed under the MIT License
*/
/**
* Return the path with DIRECTORY_SEPARATOR.
*
* @param array $dirs
* @return string
*/
function create_path(array $dirs)
{
return array_reduce($dirs, function($path, $dir) { return "$path$dir" . DIRECTORY_SEPARATOR; }, '');
}
define('PATH_TO_LIB_FOR_PHP_UTILS', create_path(array(__DIR__, 'lib')));
require_once PATH_TO_LIB_FOR_PHP_UTILS . 'error.inc' ;
require_once PATH_TO_LIB_FOR_PHP_UTILS . 'debug.inc' ;
require_once PATH_TO_LIB_FOR_PHP_UTILS . 'general.inc' ;
require_once PATH_TO_LIB_FOR_PHP_UTILS . 'string.inc' ;
require_once PATH_TO_LIB_FOR_PHP_UTILS . 'array.inc' ;
require_once PATH_TO_LIB_FOR_PHP_UTILS . 'array_of_array.inc';
| <?php
/**
* This file is part of the php-utils.php package.
*
* Copyright (C) 2015 Tadatoshi Tokutake <tadatoshi.tokutake@gmail.com>
*
* Licensed under the MIT License
*/
/**
* Return the path with DIRECTORY_SEPARATOR.
*
* @param array $dirs
* @return string
*/
function create_path(array $dirs)
{
return array_reduce($dirs, function ($path, $dir) { return "$path$dir" . DIRECTORY_SEPARATOR; }, '');
}
define('PATH_TO_LIB_FOR_PHP_UTILS', create_path(array(__DIR__, 'lib')));
require_once PATH_TO_LIB_FOR_PHP_UTILS . 'error.inc' ;
require_once PATH_TO_LIB_FOR_PHP_UTILS . 'debug.inc' ;
require_once PATH_TO_LIB_FOR_PHP_UTILS . 'general.inc' ;
require_once PATH_TO_LIB_FOR_PHP_UTILS . 'string.inc' ;
require_once PATH_TO_LIB_FOR_PHP_UTILS . 'array.inc' ;
require_once PATH_TO_LIB_FOR_PHP_UTILS . 'array_of_array.inc';
|
Add initial query parameters child member | package com.datasift.client.pylon;
import com.fasterxml.jackson.annotation.JsonProperty;
public class PylonQueryParameters {
@JsonProperty("analysis_type")
protected String analysisType;
@JsonProperty
protected PylonParametersData parameters;
@JsonProperty("child")
protected PylonQueryParameters childAnalysis;
public PylonQueryParameters() {
}
public PylonQueryParameters(String analysisType, PylonParametersData parameters, PylonQueryParameters child) {
this.analysisType = analysisType;
this.parameters = parameters;
this.childAnalysis = child;
}
public String getAnalysisType() {
return this.analysisType;
}
public PylonParametersData getParameters() {
return this.parameters;
}
public PylonQueryParameters getChildAnalysis() { return this.childAnalysis; }
public void setAnalysisType(String analysisType) {
this.analysisType = analysisType;
}
public void setParameters(PylonParametersData parameters) {
this.parameters = parameters;
}
public void setChildAnalysis(PylonQueryParameters childAnalysis) { this.childAnalysis = childAnalysis; }
}
| package com.datasift.client.pylon;
import com.fasterxml.jackson.annotation.JsonProperty;
public class PylonQueryParameters {
@JsonProperty("analysis_type")
protected String analysisType;
@JsonProperty
protected PylonParametersData parameters;
public PylonQueryParameters() {
}
public PylonQueryParameters(String analysisType, PylonParametersData parameters) {
this.analysisType = analysisType;
this.parameters = parameters;
}
public String getAnalysisType() {
return this.analysisType;
}
public PylonParametersData getParameters() {
return this.parameters;
}
public void setAnalysisType(String analysisType) {
this.analysisType = analysisType;
}
public void setParameters(PylonParametersData parameters) {
this.parameters = parameters;
}
}
|
Remove is not ready yet | 'use strict';
var Heroku = require('heroku-client');
var co = require('co');
var heroku;
module.exports = {
topic: 'access',
needsAuth: true,
needsApp: true,
command: 'remove',
description: 'Remove users from your app',
help: 'heroku access:remove user@email.com --app APP',
args: [{name: 'user', optional: false}],
run: function (context) {
let appName;
appName = context.app;
co(function* () {
heroku = new Heroku({token: context.auth.password});
yield heroku.apps(appName).collaborators(context.args.user).delete(function (err) {
if (err) { throw err; }
console.log(`Removing ${context.args.user} from application appName...done`);
});
}).catch(function (err) {
console.error(err);
});
}
};
| 'use strict';
var Heroku = require('heroku-client');
var co = require('co');
var heroku;
module.exports = {
topic: 'access',
needsAuth: true,
needsApp: true,
command: 'remove',
description: 'Remove users from your app',
help: 'heroku access:remove user@email.com --app APP',
args: [{name: 'user', optional: false}],
run: function (context) {
let appName;
appName = context.app;
co(function* () {
heroku = new Heroku({token: context.auth.password});
yield heroku.apps(appName).collaborators(context.args.user).delete(function (err) {
if (err) { throw err; }
console.log(`Removing ${context.args.user} from application ${cli.color.cyan(appName)}...done`);
});
}).catch(function (err) {
console.error(err);
});
}
};
|
Fix non ascii symbols in json | """ Data layer """
# pylint: disable=line-too-long
import json
import os
from frontui.models import ChecklistInfo
class DataProvider:
""" Data provider (objects, questions, etc) """
def __init__(self):
self.data_dir = './frontui/app_data'
self.checklists_dir = self.data_dir + '/checklists'
self.objects = list()
self.checklist = ChecklistInfo()
def add_object(self, obj):
""" Add object to collection """
self.objects.append(obj)
def save_checklist(self, obj_num, obj_date, obj_dict):
""" Save checklist data """
obj_json = json.dumps(obj_dict, sort_keys=True, indent=4, ensure_ascii=False)
filedir = self.checklists_dir + '/' + obj_num
if not os.path.exists(filedir):
os.makedirs(filedir)
filename = obj_date + '.json'
with open(filedir + '/' + filename, 'w', encoding='utf8') as file:
file.write(obj_json)
return
| """ Data layer """
# pylint: disable=line-too-long
import json
import os
from frontui.models import ChecklistInfo
class DataProvider:
""" Data provider (objects, questions, etc) """
def __init__(self):
self.data_dir = './frontui/app_data'
self.checklists_dir = self.data_dir + '/checklists'
self.objects = list()
self.checklist = ChecklistInfo()
def add_object(self, obj):
""" Add object to collection """
self.objects.append(obj)
def save_checklist(self, obj_num, obj_date, obj_dict):
""" Save checklist data """
obj_json = json.dumps(obj_dict, sort_keys=True, indent=4)
filedir = self.checklists_dir + '/' + obj_num
if not os.path.exists(filedir):
os.makedirs(filedir)
filename = obj_date + '.json'
with open(filedir + '/' + filename, 'w', encoding='utf8') as file:
file.write(obj_json)
return
|
Add documentation for IOException thrown | /**
*
*/
package com.grayben.riskExtractor.htmlScorer;
import java.io.IOException;
import java.io.InputStream;
/**
* A class implementing this interface is able to process HTML from a number of sources
* and output a representation of the readable text in that HTML, with scores attached to
* elements of this text.
* <p>
* Created by Ben Gray, 2015.
*/
public interface HtmlScorer {
/**
* Score HTML stored locally.
*
* @param htmlStream the stream containing the HTML to score
* @param charsetName the name of the charset used to encode the file
* @param baseUri the baseURI of the HTML document
* @return the scored text
*
*/
ScoredText scoreHtml(InputStream htmlStream, String charsetName, String baseUri) throws IOException;
/**
* Score HTML stored remotely.
*
* @param url the URL of the file containing the HTML to score
* @return the scored text
* @throws IOException if unable to connect to url
*/
ScoredText scoreHtml(String url) throws IOException;
}
| /**
*
*/
package com.grayben.riskExtractor.htmlScorer;
import java.io.IOException;
import java.io.InputStream;
/**
* A class implementing this interface is able to process HTML from a number of sources
* and output a representation of the readable text in that HTML, with scores attached to
* elements of this text.
* <p>
* Created by Ben Gray, 2015.
*/
public interface HtmlScorer {
/**
* Score HTML stored locally.
*
* @param htmlStream the stream containing the HTML to score
* @param charsetName the name of the charset used to encode the file
* @param baseUri the baseURI of the HTML document
* @return the scored text
*
*/
ScoredText scoreHtml(InputStream htmlStream, String charsetName, String baseUri) throws IOException;
/**
* Score HTML stored remotely.
*
* @param url the URL of the file containing the HTML to score
* @return the scored text
* @throws IOException
*/
ScoredText scoreHtml(String url) throws IOException;
}
|
Fix redirecting and back button bug | $().ready(() => {
loadContentSection().then(() =>{
$("#loader").addClass("hide");
$("#real-body").removeClass("hide");
$("#real-body").addClass("body");
$(".keyword").click(function() {
$(this).addClass("active");
$(".base").hide(200);
$("#real-body").addClass("focus");
$(".active .item").click(function() {
$(".item").off("click");
const url = $(this).attr("data-url");
window.location.href = url;
});
});
$(".close").click(function(event) {
event.stopPropagation();
$(this).parent().removeClass("active");
$(".base").show(200);
$("#real-body").removeClass("focus");
});
});
});
| $().ready(() => {
loadContentSection().then(() =>{
$("#loader").addClass("hide");
$("#real-body").removeClass("hide");
$("#real-body").addClass("body");
$(".keyword").click(function() {
$(this).addClass("active");
$(".base").hide(200);
$("#real-body").addClass("focus");
});
$(".close").click(function(event) {
event.stopPropagation();
$(this).parent().removeClass("active");
$(".base").show(200);
$("#real-body").removeClass("focus");
});
$(".active .item").click(function() {
$(".item").off("click");
const url = $(this).attr("data-url");
window.location.replace(url);
});
});
});
|
Put ‘test_frozenset’ back into BuiltinSumFunctionTests.not_implemented
I’m fairly certain that this was accidentally removed by my automatic processing | from .. utils import TranspileTestCase, BuiltinFunctionTestCase
class SumTests(TranspileTestCase):
def test_sum_list(self):
self.assertCodeExecution("""
print(sum([1, 2, 3, 4, 5, 6, 7]))
""")
def test_sum_tuple(self):
self.assertCodeExecution("""
print(sum((1, 2, 3, 4, 5, 6, 7)))
""")
def test_sum_iterator(self):
self.assertCodeExecution("""
i = iter([1, 2])
print(sum(i))
print(sum(i))
""")
def test_sum_mix_floats_and_ints(self):
self.assertCodeExecution("""
print(sum([1, 1.414, 2, 3.14159]))
""")
class BuiltinSumFunctionTests(BuiltinFunctionTestCase, TranspileTestCase):
functions = ["sum"]
not_implemented = [
'test_bytearray',
'test_frozenzet',
]
| from .. utils import TranspileTestCase, BuiltinFunctionTestCase
class SumTests(TranspileTestCase):
def test_sum_list(self):
self.assertCodeExecution("""
print(sum([1, 2, 3, 4, 5, 6, 7]))
""")
def test_sum_tuple(self):
self.assertCodeExecution("""
print(sum((1, 2, 3, 4, 5, 6, 7)))
""")
def test_sum_iterator(self):
self.assertCodeExecution("""
i = iter([1, 2])
print(sum(i))
print(sum(i))
""")
def test_sum_mix_floats_and_ints(self):
self.assertCodeExecution("""
print(sum([1, 1.414, 2, 3.14159]))
""")
class BuiltinSumFunctionTests(BuiltinFunctionTestCase, TranspileTestCase):
functions = ["sum"]
not_implemented = [
'test_bytearray',
]
|
Check submission names more leniently
Fixes #55 | from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
from dulwich.repo import check_ref_format
import re
sha1_validator = RegexValidator(regex="^[a-f0-9]{40}$",
message="Must be valid sha1 sum")
tag_regex = re.compile(r'^[\w\-\.]+$')
def tag_validator(value):
if not tag_regex.match(value):
msg = "Must be letters and numbers separated "
msg += "by dashes, dots, or underscores"
raise ValidationError(msg)
if not check_ref_format('refs/tags/' + value):
msg = "Invalid tag. Tags must adhere to ref formats defined here: "
msg += "https://www.kernel.org/pub/software/scm/git/docs/git-check-ref-format.html"
raise ValidationError(msg)
| from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
from dulwich.repo import check_ref_format
import re
sha1_validator = RegexValidator(regex="^[a-f0-9]{40}$",
message="Must be valid sha1 sum")
tag_regex = re.compile(r'^[A-Za-z][\w\-\.]+[A-Za-z]$')
def tag_validator(value):
if not tag_regex.match(value):
msg = "Must be letters and numbers separated "
msg += "by dashes, dots, or underscores"
raise ValidationError(msg)
if not check_ref_format('refs/tags/' + value):
msg = "Invalid tag. Tags must adhere to ref formats defined here: "
msg += "https://www.kernel.org/pub/software/scm/git/docs/git-check-ref-format.html"
raise ValidationError(msg)
|
Use a safer test for isExpression
It is now safe to use `isConstant` on un-trusted input, but it is still
not safe to use `toConstant` on un-trusted input. | 'use strict'
var detect = require('acorn-globals');
var lastSRC = '(null)';
var lastRes = true;
var lastConstants = undefined;
module.exports = isConstant;
function isConstant(src, constants) {
src = '(' + src + ')';
if (lastSRC === src && lastConstants === constants) return lastRes;
lastSRC = src;
lastConstants = constants;
try {
isExpression(src);
return lastRes = (detect(src).filter(function (key) {
return !constants || !(key.name in constants);
}).length === 0);
} catch (ex) {
return lastRes = false;
}
}
isConstant.isConstant = isConstant;
isConstant.toConstant = toConstant;
function toConstant(src, constants) {
if (!isConstant(src, constants)) throw new Error(JSON.stringify(src) + ' is not constant.');
return Function(Object.keys(constants || {}).join(','), 'return (' + src + ')').apply(null, Object.keys(constants || {}).map(function (key) {
return constants[key];
}));
}
function isExpression(src) {
try {
eval('throw "STOP"; (function () { return (' + src + '); })()');
return false;
}
catch (err) {
return err === 'STOP';
}
}
| 'use strict'
var detect = require('acorn-globals');
var lastSRC = '(null)';
var lastRes = true;
var lastConstants = undefined;
module.exports = isConstant;
function isConstant(src, constants) {
src = '(' + src + ')';
if (lastSRC === src && lastConstants === constants) return lastRes;
lastSRC = src;
lastConstants = constants;
try {
Function('return (' + src + ')');
return lastRes = (detect(src).filter(function (key) {
return !constants || !(key.name in constants);
}).length === 0);
} catch (ex) {
return lastRes = false;
}
}
isConstant.isConstant = isConstant;
isConstant.toConstant = toConstant;
function toConstant(src, constants) {
if (!isConstant(src, constants)) throw new Error(JSON.stringify(src) + ' is not constant.');
return Function(Object.keys(constants || {}).join(','), 'return (' + src + ')').apply(null, Object.keys(constants || {}).map(function (key) {
return constants[key];
}));
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.