text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Implement unregistration of configuration plug-ins
Perhaps we should not give a warning, but instead an exception, when registering or unregistering fails? | #!/usr/bin/env python
#-*- coding: utf-8 -*-
#This software is distributed under the Creative Commons license (CC0) version 1.0. A copy of this license should have been distributed with this software.
#The license can also be read online: <https://creativecommons.org/publicdomain/zero/1.0/>. If this online license differs from the license provided with this software, the license provided with this software should be applied.
import luna.plugins
_configurations = {}
"""
The configuration classes that have been registered here so far, keyed by their
identities.
"""
def register(identity, metadata):
"""
Registers a new configuration plug-in to track configuration with.
This expects the metadata to already be verified as configuration's
metadata.
:param identity: The identity of the plug-in to register.
:param metadata: The metadata of a configuration plug-in.
"""
if identity in _configurations:
luna.plugins.api("logger").warning("Configuration {configuration} is already registered.", configuration=identity)
return
_configurations[identity] = metadata["configuration"]["class"]
def unregister(identity):
"""
Undoes the registration of a configuration plug-in.
The configuration plug-in will no longer keep track of any configuration.
Existing configuration will be stored persistently.
:param identity: The identity of the plug-in to unregister.
"""
if identity not in _configurations:
luna.plugins.api("logger").warning("Configuration {configuration} is not registered, so I can't unregister it.", configuration=identity)
return
del _configurations[identity] #The actual unregistration.
def validate_metadata(metadata):
raise Exception("Not implemented yet.") | #!/usr/bin/env python
#-*- coding: utf-8 -*-
#This software is distributed under the Creative Commons license (CC0) version 1.0. A copy of this license should have been distributed with this software.
#The license can also be read online: <https://creativecommons.org/publicdomain/zero/1.0/>. If this online license differs from the license provided with this software, the license provided with this software should be applied.
import luna.plugins
_configurations = {}
"""
The configuration classes that have been registered here so far, keyed by their
identities.
"""
def register(identity, metadata):
"""
Registers a new configuration plug-in to track configuration with.
This expects the metadata to already be verified as configuration's
metadata.
:param identity: The identity of the plug-in to register.
:param metadata: The metadata of a configuration plug-in.
"""
if identity in _configurations:
luna.plugins.api("logger").warning("Configuration {configuration} is already registered.", configuration=identity)
return
_configurations[identity] = metadata["configuration"]["class"]
def unregister(identity):
raise Exception("Not implemented yet.")
def validate_metadata(metadata):
raise Exception("Not implemented yet.") |
Fix query. Has to use java.util.Date | package ch.rasc.eds.starter.schedule;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
import ch.rasc.eds.starter.config.MongoDb;
import ch.rasc.eds.starter.entity.CUser;
import ch.rasc.eds.starter.entity.User;
@Component
public class DisableInactiveUser {
private final MongoDb mongoDb;
@Autowired
public DisableInactiveUser(MongoDb mongoDb) {
this.mongoDb = mongoDb;
}
@Scheduled(cron = "0 0 5 * * *")
public void doCleanup() {
// Inactivate users that have a lastAccess timestamp that is older than one year
ZonedDateTime oneYearAgo = ZonedDateTime.now(ZoneOffset.UTC).minusYears(1);
this.mongoDb.getCollection(User.class).updateMany(
Filters.lte(CUser.lastAccess, Date.from(oneYearAgo.toInstant())),
Updates.set(CUser.enabled, false));
}
}
| package ch.rasc.eds.starter.schedule;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
import ch.rasc.eds.starter.config.MongoDb;
import ch.rasc.eds.starter.entity.CUser;
import ch.rasc.eds.starter.entity.User;
@Component
public class DisableInactiveUser {
private final MongoDb mongoDb;
@Autowired
public DisableInactiveUser(MongoDb mongoDb) {
this.mongoDb = mongoDb;
}
@Scheduled(cron = "0 0 5 * * *")
public void doCleanup() {
// Inactivate users that have a lastAccess timestamp that is older than one year
ZonedDateTime oneYearAgo = ZonedDateTime.now(ZoneOffset.UTC).minusYears(1);
this.mongoDb.getCollection(User.class).updateMany(
Filters.lte(CUser.lastAccess, oneYearAgo),
Updates.set(CUser.enabled, false));
}
}
|
Use a static field for tracking wifi connected state | package nl.rmokveld.castnotifications;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
public class WifiStateReceiver extends BroadcastReceiver {
private static final String TAG = "WifiStateReceiver";
private static Boolean sWasConnected;
@Override
public void onReceive(Context context, Intent intent) {
if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())) {
Log.d(TAG, "onWifiStateChanged()");
NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
boolean isConnected = networkInfo.isConnected();
if (sWasConnected == null || sWasConnected != isConnected) {
sWasConnected = isConnected;
if (isConnected) {
CastNotificationManager.getInstance().getDiscoveryStrategy().onWifiConnected();
} else {
CastNotificationManager.getInstance().getDiscoveryStrategy().onWifiDisconnected();
}
}
}
}
}
| package nl.rmokveld.castnotifications;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
public class WifiStateReceiver extends BroadcastReceiver {
private static final String TAG = "WifiStateReceiver";
private Boolean mWasConnected;
@Override
public void onReceive(Context context, Intent intent) {
if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())) {
Log.d(TAG, "onWifiStateChanged()");
boolean isConnected = DeviceStateHelper.isWifiConnected(context);
if (mWasConnected == null || mWasConnected != isConnected) {
if (isConnected) {
CastNotificationManager.getInstance().getDiscoveryStrategy().onWifiConnected();
} else {
CastNotificationManager.getInstance().getDiscoveryStrategy().onWifiDisconnected();
}
mWasConnected = isConnected;
}
}
}
}
|
Add rating field to User model | import datetime
from project import db, bcrypt
class User(db.Model):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String, unique=True, nullable=False)
password = db.Column(db.String, nullable=False)
registered_on = db.Column(db.DateTime, nullable=False)
admin = db.Column(db.Boolean, nullable=False, default=False)
confirmed = db.Column(db.Boolean, nullable=False, default=False)
confirmed_on = db.Column(db.DateTime, nullable=True)
rating = db.Column(db.Float, nullable=True)
def __init__(self, email, password, confirmed,
paid=False, admin=False, confirmed_on=None):
self.email = email
self.password = bcrypt.generate_password_hash(password)
self.registered_on = datetime.datetime.now()
self.admin = admin
self.confirmed = confirmed
self.confirmed_on = confirmed_on
def is_authenticated(self):
return True
def is_active(self):
return True
def is_anonymous(self):
return False
def get_id(self):
return self.id
def __repr__(self):
return '<email {}'.format(self.email)
| import datetime
from project import db, bcrypt
class User(db.Model):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String, unique=True, nullable=False)
password = db.Column(db.String, nullable=False)
registered_on = db.Column(db.DateTime, nullable=False)
admin = db.Column(db.Boolean, nullable=False, default=False)
confirmed = db.Column(db.Boolean, nullable=False, default=False)
confirmed_on = db.Column(db.DateTime, nullable=True)
def __init__(self, email, password, confirmed,
paid=False, admin=False, confirmed_on=None):
self.email = email
self.password = bcrypt.generate_password_hash(password)
self.registered_on = datetime.datetime.now()
self.admin = admin
self.confirmed = confirmed
self.confirmed_on = confirmed_on
def is_authenticated(self):
return True
def is_active(self):
return True
def is_anonymous(self):
return False
def get_id(self):
return self.id
def __repr__(self):
return '<email {}'.format(self.email)
|
Fix null response issue with sitemap | package burp;
public class BHttpRequestResponseFactory {
public static BHttpRequestResponse create(IHttpRequestResponse requestResponse,
IBurpExtenderCallbacks callbacks, IExtensionHelpers helpers) {
BHttpRequestResponse bHttpRequestResponse = new BHttpRequestResponse();
if (requestResponse.getRequest() != null && requestResponse.getRequest().length > 0) {
bHttpRequestResponse.request = BHttpRequestFactory.create(0x00004242, requestResponse,
helpers.analyzeRequest(requestResponse), callbacks);
}
if (requestResponse.getResponse() != null && requestResponse.getResponse().length > 0) {
bHttpRequestResponse.response = BHttpResponseFactory.create(0x00004242, requestResponse,
helpers.analyzeResponse(requestResponse.getResponse()), callbacks);
}
bHttpRequestResponse.messageType = "requestResponse";
return bHttpRequestResponse;
}
}
| package burp;
public class BHttpRequestResponseFactory {
public static BHttpRequestResponse create(IHttpRequestResponse requestResponse,
IBurpExtenderCallbacks callbacks, IExtensionHelpers helpers) {
BHttpRequestResponse bHttpRequestResponse = new BHttpRequestResponse();
bHttpRequestResponse.request = BHttpRequestFactory.create(0x00004242, requestResponse,
helpers.analyzeRequest(requestResponse), callbacks);
bHttpRequestResponse.response = BHttpResponseFactory.create(0x00004242, requestResponse,
helpers.analyzeResponse(requestResponse.getResponse()), callbacks);
bHttpRequestResponse.messageType = "requestResponse";
return bHttpRequestResponse;
}
}
|
Use two values in the state for editor & frameList
This reduces confusion between what is currently rendering.
This will avoid duck type checks in the view and allow the
rendering wrapper to have a slightly different container
for each type of widget. | var mercury = require("mercury")
var FrameList = require("./views/frame-list")
var FrameEditor = require("./views/frame-editor")
var FrameData = require("./data/frames")
// Load the data
var initialFrameData = FrameData.load()
// Create the default view using the frame set
var frameList = FrameList(frames)
var state = mercury.hash({
frames: mercury.hash(initialFrameData),
editor: mercury.value(null),
frameList: mercury.value(frameList)
})
// When the data changes, save it
state.frames(frameData.save)
// Show the frame editor
frameList.onSelectFrame(function (frameId) {
var editor = FrameEditor(state.frames[frameId])
state.editor.set(editor)
state.frameList.set(null)
editor.onExit(function () {
// Restore the frame list
state.frameList.set(frameList)
state.editor.set(null)
})
})
function render(state) {
// This is a mercury partial rendered with editor.state instead
// of globalSoup.state
// The immutable internal event list is also passed in
// Event listeners are obviously not serializable, but
// they can expose their state (listener set)
return h(
state.editor ? state.editor.partial() :
state.frameList.partial()
)
}
// setup the loop and go.
mercury.app(document.body, render, state)
| var mercury = require("mercury")
var FrameList = require("./views/frame-list")
var FrameEditor = require("./views/frame-editor")
var FrameData = require("./data/frames")
// Load the data
var initialFrameData = FrameData.load()
// Create the default view using the frame set
var frameList = FrameList(frames)
var state = mercury.hash({
frames: mercury.hash(initialFrameData),
editor: mercury.value(frameList)
})
// When the data changes, save it
state.frames(frameData.save)
// Show the frame editor
frameList.onSelectFrame(function (frameId) {
var editor = FrameEditor(state.frames[frameId])
state.editor.set(editor)
editor.onExit(function () {
// Restore the frame list
state.editor.set(frameList)
})
})
function render(state) {
// This is a mercury partial rendered with editor.state instead
// of globalSoup.state
// The immutable internal event list is also passed in
// Event listeners are obviously not serializable, but
// they can expose their state (listener set)
return h(state.editor.partial())
}
// setup the loop and go.
mercury.app(document.body, render, state)
|
Update to reflect the move of all goa middlewares to the goa-middleware repo | // +build !appengine
package main
import (
"github.com/raphael/goa"
"github.com/raphael/goa-cellar/app"
"github.com/raphael/goa-cellar/controllers"
"github.com/raphael/goa-cellar/js"
"github.com/raphael/goa-cellar/schema"
"github.com/raphael/goa-cellar/swagger"
"github.com/raphael/goa-middleware/middleware"
)
func main() {
// Create goa service
service := goa.New("cellar")
// Setup basic middleware
service.Use(middleware.RequestID())
service.Use(middleware.LogRequest())
service.Use(middleware.Recover())
// Mount account controller onto service
ac := controllers.NewAccount(service)
app.MountAccountController(service, ac)
// Mount bottle controller onto service
bc := controllers.NewBottle(service)
app.MountBottleController(service, bc)
// Mount Swagger Spec controller onto service
swagger.MountController(service)
// Mount JSON Schema controller onto service
schema.MountController(service)
// Mount JavaScript example
js.MountController(service)
// Run service
service.ListenAndServe(":8080")
}
| // +build !appengine
package main
import (
"github.com/raphael/goa"
"github.com/raphael/goa-cellar/app"
"github.com/raphael/goa-cellar/controllers"
"github.com/raphael/goa-cellar/js"
"github.com/raphael/goa-cellar/schema"
"github.com/raphael/goa-cellar/swagger"
)
func main() {
// Create goa service
service := goa.New("cellar")
// Setup basic middleware
service.Use(goa.RequestID())
service.Use(goa.LogRequest())
service.Use(goa.Recover())
// Mount account controller onto service
ac := controllers.NewAccount(service)
app.MountAccountController(service, ac)
// Mount bottle controller onto service
bc := controllers.NewBottle(service)
app.MountBottleController(service, bc)
// Mount Swagger Spec controller onto service
swagger.MountController(service)
// Mount JSON Schema controller onto service
schema.MountController(service)
// Mount JavaScript example
js.MountController(service)
// Run service
service.ListenAndServe(":8080")
}
|
Remove auto include of numpy namespace. | """\
SciPy --- A scientific computing package for Python
===================================================
You can support the development of SciPy by purchasing documentation
at
http://www.trelgol.com
It is being distributed for a fee for a limited time to try and raise
money for development.
Documentation is also available in the docstrings.
Available subpackages
---------------------
"""
import os, sys
SCIPY_IMPORT_VERBOSE = int(os.environ.get('SCIPY_IMPORT_VERBOSE','0'))
try:
import pkg_resources # activate namespace packages (manipulates __path__)
except ImportError:
pass
import numpy._import_tools as _ni
pkgload = _ni.PackageLoader()
del _ni
from numpy.testing import ScipyTest
test = ScipyTest('scipy').test
__all__.append('test')
from version import version as __version__
from numpy import __version__ as __numpy_version__
__all__.append('__version__')
__all__.append('__numpy_version__')
from __config__ import show as show_config
pkgload(verbose=SCIPY_IMPORT_VERBOSE,postpone=True)
| """\
SciPy --- A scientific computing package for Python
===================================================
You can support the development of SciPy by purchasing documentation
at
http://www.trelgol.com
It is being distributed for a fee for a limited time to try and raise
money for development.
Documentation is also available in the docstrings.
Available subpackages
---------------------
"""
import os, sys
SCIPY_IMPORT_VERBOSE = int(os.environ.get('SCIPY_IMPORT_VERBOSE','0'))
try:
import pkg_resources # activate namespace packages (manipulates __path__)
except ImportError:
pass
import numpy._import_tools as _ni
pkgload = _ni.PackageLoader()
del _ni
from numpy import *
del fft, ifft, info
import numpy
__all__.extend(filter(lambda x: x not in ['fft','ifft','info'], numpy.__all__))
del numpy
from numpy.testing import ScipyTest
test = ScipyTest('scipy').test
__all__.append('test')
from version import version as __version__
from numpy import __version__ as __numpy_version__
__all__.append('__version__')
__all__.append('__numpy_version__')
from __config__ import show as show_config
pkgload(verbose=SCIPY_IMPORT_VERBOSE,postpone=True)
|
Return empty array when findAll returns undefined from DB | 'use strict';
var SQliteAdapter = require('services/sqlite_adapter');
var Container = function() {
SQliteAdapter.call(this, 'containers');
this.schemaAttrs = ['id', 'container_name'];
};
Container.prototype = Object.create(SQliteAdapter.prototype);
Container.prototype.find = function(attrs) {
attrs = attrs || {};
if(this.validateAttrs.call(this, attrs)) {
var selection = this.prepareSelection(attrs);
return this.execute('SELECT * FROM ' + this.tableName + ' ' + selection).then(function(container) {
return container;
}).catch(function(err) {
console.log(err.stack);
});
}
};
Container.prototype.findAll = function() {
return this.execute('SELECT * FROM ' + this.tableName).then(function(containers) {
return containers || [];
}).catch(function(err) {
console.log(err.stack);
});
};
var ContainerFactory = (function() {
var instance;
function createInstance() {
var container = new Container();
return container;
}
return {
getInstance: function () {
if (!instance) {
instance = createInstance();
}
return instance;
}
};
})();
module.exports = ContainerFactory;
| 'use strict';
var SQliteAdapter = require('services/sqlite_adapter');
var Container = function() {
SQliteAdapter.call(this, 'containers');
this.schemaAttrs = ['id', 'container_name'];
};
Container.prototype = Object.create(SQliteAdapter.prototype);
Container.prototype.find = function(attrs) {
attrs = attrs || {};
if(this.validateAttrs.call(this, attrs)) {
var selection = this.prepareSelection(attrs);
return this.execute('SELECT * FROM ' + this.tableName + ' ' + selection).then(function(container) {
return container;
}).catch(function(err) {
console.log(err.stack);
});
}
};
Container.prototype.findAll = function() {
return this.execute('SELECT * FROM ' + this.tableName).then(function(containers) {
return containers;
}).catch(function(err) {
console.log(err.stack);
});
};
var ContainerFactory = (function() {
var instance;
function createInstance() {
var container = new Container();
return container;
}
return {
getInstance: function () {
if (!instance) {
instance = createInstance();
}
return instance;
}
};
})();
module.exports = ContainerFactory;
|
Add 'images' object to the client. | var apiUrls = require('./lib/utils/apis.js');
exports.createClient = function(options) {
var options = {
accessToken: options.accessToken,
apiUrls: apiUrls
};
return {
constants : require('./lib/utils/constants.js'),
contacts : require('./lib/contacts/').create(options),
favorites : require('./lib/favorites/').create(options),
folders : require('./lib/folders/').create(options),
groups : require('./lib/groups/').create(options),
home : require('./lib/home/').create(options),
images : require('./lib/images/').create(options),
reports : require('./lib/reports/').create(options),
search : require('./lib/search/').create(options),
server : require('./lib/server/').create(options),
sheets : require('./lib/sheets/').create(options),
sights : require('./lib/sights/').create(options),
templates : require('./lib/templates/').create(options),
users : require('./lib/users/').create(options),
webhooks : require('./lib/webhooks/').create(options),
workspaces : require('./lib/workspaces/').create(options)
};
};
| var apiUrls = require('./lib/utils/apis.js');
exports.createClient = function(options) {
var options = {
accessToken: options.accessToken,
apiUrls: apiUrls
};
return {
constants : require('./lib/utils/constants.js'),
contacts : require('./lib/contacts/').create(options),
favorites : require('./lib/favorites/').create(options),
folders : require('./lib/folders/').create(options),
groups : require('./lib/groups/').create(options),
home : require('./lib/home/').create(options),
reports : require('./lib/reports/').create(options),
search : require('./lib/search/').create(options),
server : require('./lib/server/').create(options),
sheets : require('./lib/sheets/').create(options),
sights : require('./lib/sights/').create(options),
templates : require('./lib/templates/').create(options),
users : require('./lib/users/').create(options),
webhooks : require('./lib/webhooks/').create(options),
workspaces : require('./lib/workspaces/').create(options)
};
};
|
Add filter to replace multiple spaces with only one space in textual attributes | <?php
namespace common\models;
use Yii;
/**
* This is the model class for table "course".
*
* @property integer $id
* @property string $name
*/
class Course extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'course';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['name'], 'required'],
[['name'], 'string', 'max' => 255],
[['name'], 'trim'],
[['name'], 'unique'],
['name', 'filter', 'filter' => function ($value) {
return preg_replace('!\s+!', ' ', $value);
}],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'name' => Yii::t('app', 'Course Name'),
];
}
}
| <?php
namespace common\models;
use Yii;
/**
* This is the model class for table "course".
*
* @property integer $id
* @property string $name
*/
class Course extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'course';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['name'], 'required'],
[['name'], 'string', 'max' => 255],
[['name'], 'trim'],
[['name'], 'unique'],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'name' => Yii::t('app', 'Course Name'),
];
}
}
|
Change prod url to https | import json
MAINJS_PATH = 'js/common.js'
MANIFEST_PATH = 'manifest.json'
DEV_URL = 'http://localhost:8000'
PROD_URL = 'https://eyebrowse.csail.mit.edu'
def rewriteBaseUrl():
with open(MAINJS_PATH, 'r+') as f:
text = f.read()
text = text.replace(DEV_URL, PROD_URL)
f.seek(0)
f.write(text)
f.truncate()
def rewriteManifest():
with open(MANIFEST_PATH, 'r+') as f:
data = json.load(f)
version = data['version'].split('.')
version[2] = str(int(version[2]) + 1)
version = '.'.join(version)
data['version'] = version
f.seek(0)
json.dump(data, f, indent=4, sort_keys=True)
f.truncate()
print version
def main():
''''
rewrite main.js to replace the baseUrl and update manifest.json to have a new manifest
'''
rewriteBaseUrl()
rewriteManifest()
if __name__ == '__main__':
main()
| import json
MAINJS_PATH = 'js/common.js'
MANIFEST_PATH = 'manifest.json'
DEV_URL = 'http://localhost:8000'
PROD_URL = 'http://eyebrowse.csail.mit.edu'
def rewriteBaseUrl():
with open(MAINJS_PATH, 'r+') as f:
text = f.read()
text = text.replace(DEV_URL, PROD_URL)
f.seek(0)
f.write(text)
f.truncate()
def rewriteManifest():
with open(MANIFEST_PATH, 'r+') as f:
data = json.load(f)
version = data['version'].split('.')
version[2] = str(int(version[2]) + 1)
version = '.'.join(version)
data['version'] = version
f.seek(0)
json.dump(data, f, indent=4, sort_keys=True)
f.truncate()
print version
def main():
''''
rewrite main.js to replace the baseUrl and update manifest.json to have a new manifest
'''
rewriteBaseUrl()
rewriteManifest()
if __name__ == '__main__':
main()
|
Check the token before returning the profiles export template | <?php
namespace Backend\Modules\Profiles\Actions;
use Backend\Core\Engine\Base\ActionAdd as BackendBaseActionAdd;
/**
* This is the add-action, it will display a form to add a new profile.
*/
class ExportTemplate extends BackendBaseActionAdd
{
public function execute(): void
{
$this->checkToken();
// define path
$path = BACKEND_CACHE_PATH . '/Profiles/import_template.csv';
// define required fields
$fields = [
'email',
'display_name',
'password',
];
// define file
$file = new \SpoonFileCSV();
// download the file
$file->arrayToFile($path, [], $fields, null, ',', '"', true);
}
}
| <?php
namespace Backend\Modules\Profiles\Actions;
use Backend\Core\Engine\Base\ActionAdd as BackendBaseActionAdd;
/**
* This is the add-action, it will display a form to add a new profile.
*/
class ExportTemplate extends BackendBaseActionAdd
{
public function execute(): void
{
// define path
$path = BACKEND_CACHE_PATH . '/Profiles/import_template.csv';
// define required fields
$fields = [
'email',
'display_name',
'password',
];
// define file
$file = new \SpoonFileCSV();
// download the file
$file->arrayToFile($path, [], $fields, null, ',', '"', true);
}
}
|
Change pause hotkey to P | 'use strict';
Darwinator.Boot = function() {};
Darwinator.Boot.prototype = {
preload: function () {
this.load.image('preloader', 'assets/preloader.gif');
},
create: function () {
this.game.input.maxPointers = 1;
// Toggle pause with space
var key = this.game.input.keyboard.addKey(Phaser.Keyboard.P);
key.onDown.add(this.togglePause, this);
// this.game.stage.disableVisibilityChange = true;
if (this.game.device.desktop) {
this.game.stage.scale.pageAlignHorizontally = true;
} else {
this.game.stage.scaleMode = Phaser.StageScaleMode.SHOW_ALL;
this.game.stage.scale.minWidth = 480;
this.game.stage.scale.minHeight = 260;
this.game.stage.scale.maxWidth = 640;
this.game.stage.scale.maxHeight = 480;
this.game.stage.scale.forceLandscape = true;
this.game.stage.scale.pageAlignHorizontally = true;
this.game.stage.scale.setScreenSize(true);
}
this.game.state.start('preloader');
},
togglePause: function() {
this.game.paused = !this.game.paused;
}
};
| 'use strict';
Darwinator.Boot = function() {};
Darwinator.Boot.prototype = {
preload: function () {
this.load.image('preloader', 'assets/preloader.gif');
},
create: function () {
this.game.input.maxPointers = 1;
// Toggle pause with space
var key = this.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
key.onDown.add(this.togglePause, this);
// this.game.stage.disableVisibilityChange = true;
if (this.game.device.desktop) {
this.game.stage.scale.pageAlignHorizontally = true;
} else {
this.game.stage.scaleMode = Phaser.StageScaleMode.SHOW_ALL;
this.game.stage.scale.minWidth = 480;
this.game.stage.scale.minHeight = 260;
this.game.stage.scale.maxWidth = 640;
this.game.stage.scale.maxHeight = 480;
this.game.stage.scale.forceLandscape = true;
this.game.stage.scale.pageAlignHorizontally = true;
this.game.stage.scale.setScreenSize(true);
}
this.game.state.start('preloader');
},
togglePause: function() {
this.game.paused = !this.game.paused;
}
};
|
Add entries for SRP key exchange algorithms | package org.bouncycastle.crypto.tls;
import java.io.IOException;
/**
* A generic class for ciphersuites in TLS 1.0.
*/
public abstract class TlsCipherSuite
{
protected static final short KE_RSA = 1;
protected static final short KE_RSA_EXPORT = 2;
protected static final short KE_DHE_DSS = 3;
protected static final short KE_DHE_DSS_EXPORT = 4;
protected static final short KE_DHE_RSA = 5;
protected static final short KE_DHE_RSA_EXPORT = 6;
protected static final short KE_DH_DSS = 7;
protected static final short KE_DH_RSA = 8;
protected static final short KE_DH_anon = 9;
protected static final short KE_SRP = 10;
protected static final short KE_SRP_RSA = 11;
protected static final short KE_SRP_DSS = 12;
protected abstract void init(byte[] ms, byte[] cr, byte[] sr);
protected abstract byte[] encodePlaintext(short type, byte[] plaintext, int offset, int len);
protected abstract byte[] decodeCiphertext(short type, byte[] plaintext, int offset, int len, TlsProtocolHandler handler) throws IOException;
protected abstract short getKeyExchangeAlgorithm();
}
| package org.bouncycastle.crypto.tls;
import java.io.IOException;
/**
* A generic class for ciphersuites in TLS 1.0.
*/
public abstract class TlsCipherSuite
{
protected static final short KE_RSA = 1;
protected static final short KE_RSA_EXPORT = 2;
protected static final short KE_DHE_DSS = 3;
protected static final short KE_DHE_DSS_EXPORT = 4;
protected static final short KE_DHE_RSA = 5;
protected static final short KE_DHE_RSA_EXPORT = 6;
protected static final short KE_DH_DSS = 7;
protected static final short KE_DH_RSA = 8;
protected static final short KE_DH_anon = 9;
protected abstract void init(byte[] ms, byte[] cr, byte[] sr);
protected abstract byte[] encodePlaintext(short type, byte[] plaintext, int offset, int len);
protected abstract byte[] decodeCiphertext(short type, byte[] plaintext, int offset, int len, TlsProtocolHandler handler) throws IOException;
protected abstract short getKeyExchangeAlgorithm();
}
|
Change port from 7700 to 80 | import express from "express"
import graphqlHTTP from "express-graphql"
import { graphqlExpress, graphiqlExpress } from "graphql-server-express"
import bodyParser from "body-parser"
import mongoose, { Schema } from "mongoose"
import schema from "./graphql"
import Item from "./db/item"
// Constants
const HTTP_PORT = 80
let currentApp = null
const app = express()
mongoose.Promise = global.Promise
mongoose.connect("mongodb://localhost:27017/runescape", {
useMongoClient: true
})
app.use(
"/graphql",
bodyParser.json({
limit: "15mb"
}),
graphqlExpress(() => ({
schema
}))
)
app.use(
"/graphiql",
graphiqlExpress({
endpointURL: "/graphql"
})
)
app.listen(HTTP_PORT, () => {
console.log(`GraphQL-server listening on port ${HTTP_PORT}.`)
})
if (module.hot) {
module.hot.accept(["./server", "./graphql"], () => {
server.removeListener("request", currentApp)
server.on("request", app)
currentApp = app
})
}
export { app, HTTP_PORT }
| import express from "express"
import graphqlHTTP from "express-graphql"
import { graphqlExpress, graphiqlExpress } from "graphql-server-express"
import bodyParser from "body-parser"
import mongoose, { Schema } from "mongoose"
import schema from "./graphql"
import Item from "./db/item"
// Constants
const HTTP_PORT = 7700
let currentApp = null
const app = express()
mongoose.Promise = global.Promise
mongoose.connect("mongodb://localhost:27017/runescape", {
useMongoClient: true
})
app.use(
"/graphql",
bodyParser.json({
limit: "15mb"
}),
graphqlExpress(() => ({
schema
}))
)
app.use(
"/graphiql",
graphiqlExpress({
endpointURL: "/graphql"
})
)
app.listen(HTTP_PORT, () => {
console.log(`GraphQL-server listening on port ${HTTP_PORT}.`)
})
if (module.hot) {
module.hot.accept(["./server", "./graphql"], () => {
server.removeListener("request", currentApp)
server.on("request", app)
currentApp = app
})
}
export { app, HTTP_PORT }
|
Remove unneeded `pass` in except block. | from setuptools import setup, find_packages
try:
from pyqt_distutils.build_ui import build_ui
cmdclass={'build_ui': build_ui}
except ImportError:
cmdclass={}
setup(
name='gauges',
version='0.1',
description='PyQt5 + Autobahn/Twisted version of Gauges Crossbar demo',
url='http://github.com/estan/gauges',
author='Elvis Stansvik',
license='License :: OSI Approved :: MIT License',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Topic :: Communications',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
],
packages=find_packages(),
install_requires=[
'autobahn',
'twisted',
'pyOpenSSL',
'service_identity',
'qt5reactor-fork',
],
entry_points={
'gui_scripts': [
'gauges-qt=gauges.gauges_qt:main'
],
},
cmdclass=cmdclass
)
| from setuptools import setup, find_packages
try:
from pyqt_distutils.build_ui import build_ui
cmdclass={'build_ui': build_ui}
except ImportError:
cmdclass={}
pass
setup(
name='gauges',
version='0.1',
description='PyQt5 + Autobahn/Twisted version of Gauges Crossbar demo',
url='http://github.com/estan/gauges',
author='Elvis Stansvik',
license='License :: OSI Approved :: MIT License',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Topic :: Communications',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
],
packages=find_packages(),
install_requires=[
'autobahn',
'twisted',
'pyOpenSSL',
'service_identity',
'qt5reactor-fork',
],
entry_points={
'gui_scripts': [
'gauges-qt=gauges.gauges_qt:main'
],
},
cmdclass=cmdclass
)
|
Fix error redirect login page | 'use strict'
const Hash = use('Hash');
const Admin = use('App/Model/Admin');
class AdminLoginController {
* index (request, response) {
const admin = yield request.session.get('admin');
if (null !=admin){
return response.redirect('/ninja/user');
}
const view = yield response.view('backend/Login.html');
return response.send(view)
}
* login (request, response) {
const all = request.all();
const email = all.email;
const password = all.password;
const admin = yield Admin.where('email', email).first();
const isSame = yield Hash.verify(password, admin.password);
if (isSame) {
var adminStatus = {
'login_at' : new Date,
'email' : admin.email
}
yield request.session.put('admin', adminStatus);
return response.json({status: 'ok'});
}
return response.json({status: 'INVALID_LOGIN'});
}
* logout(request, response){
yield request.session.forget('admin');
return response.redirect('/admin/login');
}
}
module.exports = AdminLoginController
| 'use strict'
const Hash = use('Hash');
const Admin = use('App/Model/Admin');
class AdminLoginController {
* index (request, response) {
const view = yield response.view('backend/Login.html');
return response.send(view)
}
* login (request, response) {
const all = request.all();
const email = all.email;
const password = all.password;
const admin = yield Admin.where('email', email).first();
const isSame = yield Hash.verify(password, admin.password);
if (isSame) {
var adminStatus = {
'login_at' : new Date,
'email' : admin.email
}
yield request.session.put('admin', adminStatus);
return response.json({status: 'ok'});
}
return response.json({status: 'INVALID_LOGIN'});
}
* logout(request, response){
yield request.session.forget('admin');
return response.redirect('/admin/login');
}
}
module.exports = AdminLoginController
|
Add new channel name for test. | import os, os.path
import ConfigParser
package = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
import slack
class TestSlack(object):
def setup(self):
self.set_up_config()
self.set_up_slack()
def set_up_config(self):
search_paths = [os.path.expanduser('~/.slack'), '/etc/slack']
self.config = ConfigParser.ConfigParser()
self.config.read(search_paths)
if self.config.has_section('Slack'):
self.access_token = self.config.get('Slack', 'token')
elif 'SLACK_TOKEN' in os.environ:
self.access_token = os.environ['SLACK_TOKEN']
else:
print('Authorization token not detected! The token is pulled from '\
'~/.slack, /etc/slack, or the environment variable SLACK_TOKEN.')
self.test_channel = self.config.get('Slack', 'test-channel')
self.test_channel_name = self.config.get('Slack', 'test-channel-name')
def set_up_slack(self):
self.slack = slack.Slack(self.access_token)
| import os, os.path
import ConfigParser
package = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
import slack
class TestSlack(object):
def setup(self):
self.set_up_config()
self.set_up_slack()
def set_up_config(self):
search_paths = [os.path.expanduser('~/.slack'), '/etc/slack']
self.config = ConfigParser.ConfigParser()
self.config.read(search_paths)
if self.config.has_section('Slack'):
self.access_token = self.config.get('Slack', 'token')
elif 'SLACK_TOKEN' in os.environ:
self.access_token = os.environ['SLACK_TOKEN']
else:
print('Authorization token not detected! The token is pulled from '\
'~/.slack, /etc/slack, or the environment variable SLACK_TOKEN.')
self.test_channel = self.config.get('Slack', 'test-channel')
def set_up_slack(self):
self.slack = slack.Slack(self.access_token)
|
Fix - run all tests, not only those for saving status directive. | describe('Saving status indicator directive', function() {
var $rootScope, $scope, el, $compile;
var statusClasses = ['pending', 'success', 'failed'];
beforeEach(module('codebrag.common.directives'));
beforeEach(inject(function (_$rootScope_, _$compile_) {
$compile = _$compile_;
$rootScope = _$rootScope_;
$scope = $rootScope.$new();
el = angular.element('<span saving-status="status"></span>');
$compile(el)($scope);
}));
it('should be empty with no status-related class on start', function() {
expect(el.text()).toBe('');
statusClasses.forEach(function(clazz) {
expect(el.hasClass(clazz)).toBeFalsy();
})
});
it('should show pending with class pending when saving in progress', function() {
$scope.status = 'pending';
$scope.$apply();
expect(el.text()).toBe('Saving...');
expect(el.hasClass($scope.status)).toBeTruthy();
});
it('should show success with class success when saving was ok', function() {
$scope.status = 'success';
$scope.$apply();
expect(el.text()).toBe('Saved');
expect(el.hasClass($scope.status)).toBeTruthy();
});
}); | ddescribe('Dynamic favicon directive', function() {
var $rootScope, $scope, el, $compile;
var statusClasses = ['pending', 'success', 'failed'];
beforeEach(module('codebrag.common.directives'));
beforeEach(inject(function (_$rootScope_, _$compile_) {
$compile = _$compile_;
$rootScope = _$rootScope_;
$scope = $rootScope.$new();
el = angular.element('<span saving-status="status"></span>');
$compile(el)($scope);
}));
it('should be empty with no status-related class on start', function() {
expect(el.text()).toBe('');
statusClasses.forEach(function(clazz) {
expect(el.hasClass(clazz)).toBeFalsy();
})
});
it('should show pending with class pending when saving in progress', function() {
$scope.status = 'pending';
$scope.$apply();
expect(el.text()).toBe('Saving...');
expect(el.hasClass($scope.status)).toBeTruthy();
});
it('should show success with class success when saving was ok', function() {
$scope.status = 'success';
$scope.$apply();
expect(el.text()).toBe('Saved');
expect(el.hasClass($scope.status)).toBeTruthy();
});
}); |
Fix a bug in getScript utility.
- Should not extract script from deploy section. | import fs from 'fs';
import path from 'path';
import yaml from 'js-yaml';
const scriptCache = {};
function getCacheOrFile(key, fn) {
if (scriptCache[key]) {
return scriptCache[key];
}
const value = fn();
scriptCache[key] = value;
return value;
}
const travisCommands = [
// Reference: http://docs.travis-ci.com/user/customizing-the-build/#The-Build-Lifecycle
'before_install',
'install',
'before_script',
'script',
'after_success or after_failure',
'before_deploy',
'after_deploy',
'after_script',
];
function concat(array, item) {
return array.concat(item);
}
function getObjectValues(object) {
return Object.keys(object).map(key => object[key]);
}
export default function getScripts(filepath, content = null) {
return getCacheOrFile(filepath, () => {
const basename = path.basename(filepath);
const fileContent = content !== null ? content : fs.readFileSync(filepath, 'utf-8');
if (basename === 'package.json') {
return getObjectValues(JSON.parse(fileContent).scripts || {});
} else if (basename === '.travis.yml') {
const metadata = yaml.safeLoad(content) || {};
return travisCommands.map(cmd => metadata[cmd] || []).reduce(concat, []);
}
return [];
});
}
| import fs from 'fs';
import path from 'path';
import yaml from 'js-yaml';
const scriptCache = {};
function getCacheOrFile(key, fn) {
if (scriptCache[key]) {
return scriptCache[key];
}
const value = fn();
scriptCache[key] = value;
return value;
}
const travisCommands = [
// Reference: http://docs.travis-ci.com/user/customizing-the-build/#The-Build-Lifecycle
'before_install',
'install',
'before_script',
'script',
'after_success or after_failure',
'before_deploy',
'deploy',
'after_deploy',
'after_script',
];
function concat(array, item) {
return array.concat(item);
}
function getObjectValues(object) {
return Object.keys(object).map(key => object[key]);
}
export default function getScripts(filepath, content = null) {
return getCacheOrFile(filepath, () => {
const basename = path.basename(filepath);
const fileContent = content !== null ? content : fs.readFileSync(filepath, 'utf-8');
if (basename === 'package.json') {
return getObjectValues(JSON.parse(fileContent).scripts || {});
} else if (basename === '.travis.yml') {
const metadata = yaml.safeLoad(content) || {};
return travisCommands.map(cmd => metadata[cmd] || []).reduce(concat, []);
}
return [];
});
}
|
Refactor ciscospark Migrate Avatar to packages
use default SparkMock
issue #62 Migrate Avatar | /**!
*
* Copyright (c) 2015-2016 Cisco Systems, Inc. See LICENSE file.
*/
import {assert} from '@ciscospark/test-helper-chai';
import Avatar from '../../';
import MockSpark from '@ciscospark/test-helper-mock-spark';
describe(`Services`, () => {
describe(`Avatar`, () => {
describe(`AvatarUrlBatcher`, () => {
let batcher;
let spark;
beforeEach(() => {
spark = new MockSpark({
children: {
avatar: Avatar
}
});
console.warn('spark: <' + JSON.stringify(spark) + '>');
batcher = spark.avatar.batcher;
});
describe(`#fingerprintRequest(item)`, () => {
it(`returns 'uuid - size'`, () => {
assert.equal(batcher.fingerprintRequest({uuid: `uuid1`, size: 80}), `uuid1 - 80`);
});
});
});
});
});
| /**!
*
* Copyright (c) 2015-2016 Cisco Systems, Inc. See LICENSE file.
*/
import {assert} from '@ciscospark/test-helper-chai';
import Avatar, {config} from '../../';
// import '@ciscospark/test-helper-sinon';
import {MockSpark} from '@ciscospark/test-helper-mock-spark';
describe(`Services`, () => {
describe(`Avatar`, () => {
describe(`AvatarUrlBatcher`, () => {
let batcher;
let spark;
beforeEach(() => {
spark = new MockSpark({
children: {
avatar: Avatar
}
});
spark.config.avatar = config.avatar;
batcher = spark.avatar.batcher;
console.warn(JSON.stringify(spark, null, `\t`));
});
describe(`#fingerprintRequest(item)`, () => {
it(`returns 'uuid - size'`, () => {
assert.equal(batcher.fingerprintRequest({uuid: `uuid1`, size: 80}), `uuid1 - 80`);
});
});
});
});
});
|
Add ref to ligiermirror CLU | #!/usr/bin/env python
# coding=utf-8
# vim: ts=4 sw=4 et
"""
=============
Ligier Mirror
=============
Subscribes to given tag(s) and sends them to another Ligier.
This script is also available as a command line utility in km3pipe, which can
be accessed by the command ``ligiermirror``.
"""
# Author: Tamas Gal <tgal@km3net.de>
# License: MIT
from __future__ import division
import socket
from km3pipe import Pipeline, Module
from km3pipe.io import CHPump
class LigierSender(Module):
def configure(self):
self.ligier = self.get("ligier") or "127.0.0.1"
self.port = self.get("port") or 5553
self.socket = socket.socket()
self.client = self.socket.connect((self.ligier, self.port))
def process(self, blob):
self.socket.send(blob["CHPrefix"].data + blob["CHData"])
def finish(self):
self.socket.close()
pipe = Pipeline()
pipe.attach(CHPump, host='192.168.0.121',
port=5553,
tags='IO_EVT, IO_SUM, IO_TSL',
timeout=60 * 60 * 24 * 7,
max_queue=2000)
pipe.attach(LigierSender)
pipe.drain()
| #!/usr/bin/env python
# coding=utf-8
# vim: ts=4 sw=4 et
"""
=============
Ligier Mirror
=============
Subscribes to given tag(s) and sends them to another Ligier.
"""
# Author: Tamas Gal <tgal@km3net.de>
# License: MIT
from __future__ import division
import socket
from km3pipe import Pipeline, Module
from km3pipe.io import CHPump
class LigierSender(Module):
def configure(self):
self.ligier = self.get("ligier") or "127.0.0.1"
self.port = self.get("port") or 5553
self.socket = socket.socket()
self.client = self.socket.connect((self.ligier, self.port))
def process(self, blob):
self.socket.send(blob["CHPrefix"].data + blob["CHData"])
def finish(self):
self.socket.close()
pipe = Pipeline()
pipe.attach(CHPump, host='192.168.0.121',
port=5553,
tags='IO_EVT, IO_SUM, IO_TSL',
timeout=60 * 60 * 24 * 7,
max_queue=2000)
pipe.attach(LigierSender)
pipe.drain()
|
Fix small bug in EvenOdd counter flowlet | package DependencyRandomNumber;
import com.continuuity.api.data.*;
import com.continuuity.api.flow.flowlet.*;
import com.continuuity.api.flow.flowlet.builders.*;
public class EvenOddCounter extends AbstractComputeFlowlet {
@Override
public void configure(StreamsConfigurator configurator) {
TupleSchema in = new TupleSchemaBuilder().
add("randomNumber", Long.class).
create();
configurator.getDefaultTupleInputStream().setSchema(in);
}
@Override
public void process(Tuple tuple, TupleContext tupleContext,
OutputCollector outputCollector) {
if (Common.debug)
System.out.println(this.getClass().getSimpleName() +
": Received tuple " + tuple);
// count the number of odd or even numbers
long randomNumber = ((Long)tuple.get("randomNumber")).longValue();
boolean isEven = (randomNumber % 2) == 0;
// generate an increment operation
Increment increment;
if (isEven) increment = new Increment("even".getBytes(), 1);
else increment = new Increment("odd".getBytes(), 1);
// emit the increment operation
outputCollector.emit(increment);
}
}
| package DependencyRandomNumber;
import com.continuuity.api.data.*;
import com.continuuity.api.flow.flowlet.*;
import com.continuuity.api.flow.flowlet.builders.*;
public class EvenOddCounter extends AbstractComputeFlowlet {
@Override
public void configure(StreamsConfigurator configurator) {
TupleSchema in = new TupleSchemaBuilder().
add("randomNumber", Long.class).
create();
configurator.getDefaultTupleInputStream().setSchema(in);
}
@Override
public void process(Tuple tuple, TupleContext tupleContext,
OutputCollector outputCollector) {
if (Common.debug)
System.out.println(this.getClass().getSimpleName() +
": Received tuple " + tuple);
// count the number of odd or even numbers
long randomNumber = tuple.get("randomNumber");
boolean isEven = (randomNumber % 2) == 0;
// generate an increment operation
Increment increment;
if (isEven) increment = new Increment("even".getBytes(), 1);
else increment = new Increment("odd".getBytes(), 1);
// emit the increment operation
outputCollector.emit(increment);
}
}
|
[feedback] Save overlay node to global scope | let optionsOverlayNode = document.getElementById('overlay');
let optionsSaveBtn = document.getElementById('save');
let optionsStatus = document.getElementById('status');
// Saves options to chrome.storage
function save_options() {
chrome.storage.sync.set({
enableOverlay: optionsOverlayNode.checked
}, () => {
// Update status to let user know options were saved.
optionsStatus.textContent = 'Options saved.';
setTimeout(() => {
optionsStatus.textContent = '';
}, 750);
});
}
// Restores select box and checkbox state using the preferences
// stored in chrome.storage.
function restore_options() {
chrome.storage.sync.get({
enableOverlay: false
}, ({enableOverlay}) => {
optionsOverlayNode.checked = enableOverlay;
});
}
document.addEventListener('DOMContentLoaded', restore_options);
optionsSaveBtn.addEventListener('click', save_options); | // Saves options to chrome.storage
function save_options() {
chrome.storage.sync.set({
enableOverlay: document.getElementById('overlay').checked
}, () => {
// Update status to let user know options were saved.
const status = document.getElementById('status');
status.textContent = 'Options saved.';
setTimeout(() => {
status.textContent = '';
}, 750);
});
}
// Restores select box and checkbox state using the preferences
// stored in chrome.storage.
function restore_options() {
chrome.storage.sync.get({
enableOverlay: false
}, ({enableOverlay}) => {
document.getElementById('overlay').checked = enableOverlay;
});
}
document.addEventListener('DOMContentLoaded', restore_options);
document.getElementById('save').addEventListener('click',
save_options); |
Update userId validation message to say 'userId' instead of 'feedSlug' | var errors = require('./errors');
var validRe = /^[\w-]+$/;
function validateFeedId(feedId) {
/*
* Validate that the feedId matches the spec user:1
*/
var parts = feedId.split(':');
if (parts.length !== 2) {
throw new errors.FeedError('Invalid feedId, expected something like user:1 got ' + feedId);
}
var feedSlug = parts[0];
var userId = parts[1];
validateFeedSlug(feedSlug);
validateUserId(userId);
return feedId;
}
exports.validateFeedId = validateFeedId;
function validateFeedSlug(feedSlug) {
/*
* Validate that the feedSlug matches \w
*/
var valid = validRe.test(feedSlug);
if (!valid) {
throw new errors.FeedError('Invalid feedSlug, please use letters, numbers or _ got: ' + feedSlug);
}
return feedSlug;
}
exports.validateFeedSlug = validateFeedSlug;
function validateUserId(userId) {
/*
* Validate the userId matches \w
*/
var valid = validRe.test(userId);
if (!valid) {
throw new errors.FeedError('Invalid userId, please use letters, numbers or _ got: ' + userId);
}
return userId;
}
exports.validateUserId = validateUserId;
function rfc3986(str) {
return str.replace(/[!'()*]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16).toUpperCase();
});
}
exports.rfc3986 = rfc3986;
| var errors = require('./errors');
var validRe = /^[\w-]+$/;
function validateFeedId(feedId) {
/*
* Validate that the feedId matches the spec user:1
*/
var parts = feedId.split(':');
if (parts.length !== 2) {
throw new errors.FeedError('Invalid feedId, expected something like user:1 got ' + feedId);
}
var feedSlug = parts[0];
var userId = parts[1];
validateFeedSlug(feedSlug);
validateUserId(userId);
return feedId;
}
exports.validateFeedId = validateFeedId;
function validateFeedSlug(feedSlug) {
/*
* Validate that the feedSlug matches \w
*/
var valid = validRe.test(feedSlug);
if (!valid) {
throw new errors.FeedError('Invalid feedSlug, please use letters, numbers or _ got: ' + feedSlug);
}
return feedSlug;
}
exports.validateFeedSlug = validateFeedSlug;
function validateUserId(userId) {
/*
* Validate the userId matches \w
*/
var valid = validRe.test(userId);
if (!valid) {
throw new errors.FeedError('Invalid feedSlug, please use letters, numbers or _ got: ' + userId);
}
return userId;
}
exports.validateUserId = validateUserId;
function rfc3986(str) {
return str.replace(/[!'()*]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16).toUpperCase();
});
}
exports.rfc3986 = rfc3986;
|
Rename the python package to barn. | from setuptools import setup, find_packages
setup(
name='barn',
version='0.0.1',
description="Store a set of files and metadata in an organized way",
long_description="",
classifiers=[
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"Operating System :: OS Independent",
"Programming Language :: Python",
],
keywords='',
author='Friedrich Lindenberg',
author_email='friedrich@pudo.org',
url='http://pudo.org',
license='MIT',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
namespace_packages=[],
include_package_data=True,
zip_safe=False,
install_requires=[
"Werkzeug>=0.9.6",
"lockfile>=0.9.1",
"python-slugify>=0.0.6"
],
entry_points={},
tests_require=[]
)
| import os
from setuptools import setup, find_packages
setup(
name='docstash',
version='0.2.2',
description="Store a set of documents and metadata in an organized way",
long_description="",
classifiers=[
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"Operating System :: OS Independent",
"Programming Language :: Python",
],
keywords='',
author='Friedrich Lindenberg',
author_email='friedrich@pudo.org',
url='http://pudo.org',
license='MIT',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
namespace_packages=[],
include_package_data=True,
zip_safe=False,
install_requires=[
"PyYAML>=3.11",
"Werkzeug>=0.9.6",
"lockfile>=0.9.1"
],
entry_points={},
tests_require=[]
)
|
Add test of async compare | const {assert} = require('./common');
const Passwords = require('../passwords');
describe('Passwords', () => {
it('should be able to generate and compare hashes', async () => {
const pass = 'apple';
const passFake = 'orange';
const passHash = await Passwords.hash(pass);
const passHashSync = Passwords.hashSync(pass);
const passFakeHashSync = Passwords.hashSync(passFake);
assert(Passwords.compareSync(pass, passHash),
'hash should compare correctly to original password');
const compareAsync = await Passwords.compare(pass, passHash);
assert(compareAsync,
'hash should async compare correctly to original password');
assert(Passwords.compareSync(pass, passHashSync),
'hashSync should compare correctly to original password');
assert(!Passwords.compareSync(passFake, passHash),
'hash should not match fake password');
assert(!Passwords.compareSync(pass, passFakeHashSync),
'fake hash sync should not match original password');
});
})
| const {assert} = require('./common');
const Passwords = require('../passwords');
describe('Passwords', () => {
it('should be able to generate and compare hashes', async () => {
const pass = 'apple';
const passFake = 'orange';
const passHash = await Passwords.hash(pass);
const passHashSync = Passwords.hashSync(pass);
const passFakeHashSync = Passwords.hashSync(passFake);
assert(Passwords.compareSync(pass, passHash),
'hash should compare correctly to original password');
assert(Passwords.compareSync(pass, passHashSync),
'hashSync should compare correctly to original password');
assert(!Passwords.compareSync(passFake, passHash),
'hash should not match fake password');
assert(!Passwords.compareSync(pass, passFakeHashSync),
'fake hash sync should not match original password');
});
})
|
Change mob menu icon when auto-closing nav menu from a selected nav item | var bindEvents = function() {
smoothScroll.init();
document.querySelector('.mobile-menu-toggle').addEventListener('click', function(event) {
event.preventDefault();
document.getElementById('nav-list').classList.toggle('show');
this.classList.toggle('close'); // toggle icons of mobile icon (.mobile-menu-toggle)
});
var nav_links = document.querySelectorAll('nav ul li');
for (var i = 0; i < nav_links.length; i++) {
nav_links[i].addEventListener('click', function(event) {
var other_active = document.querySelector('.active');
if (other_active && other_active != this) {
other_active.classList.toggle('active');
}
this.classList.toggle('active');
if (window.innerWidth < 600) {
document.querySelector('.mobile-menu-toggle').classList.toggle('close');
document.getElementById('nav-list').classList.toggle('show');
}
});
}
}
window.onload = function() {
bindEvents();
} | var bindEvents = function() {
smoothScroll.init();
document.querySelector('.mobile-menu-toggle').addEventListener('click', function(event) {
event.preventDefault();
document.getElementById('nav-list').classList.toggle('show');
this.classList.toggle('close'); // toggle icons of mobile icon (.mobile-menu-toggle)
});
var nav_links = document.querySelectorAll('nav ul li');
for (var i = 0; i < nav_links.length; i++) {
nav_links[i].addEventListener('click', function(event) {
var other_active = document.querySelector('.active');
if (other_active && other_active != this) {
other_active.classList.toggle('active');
}
this.classList.toggle('active');
if (window.innerWidth < 600) {
document.getElementById('nav-list').classList.toggle('show');
}
});
}
}
window.onload = function() {
bindEvents();
} |
Call RelaxNgWriter as a temporary hack. | package com.thaiopensource.xml.dtd.app;
import java.io.IOException;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import com.thaiopensource.xml.out.CharRepertoire;
import com.thaiopensource.xml.out.XmlWriter;
import com.thaiopensource.xml.util.EncodingMap;
import com.thaiopensource.xml.dtd.om.DtdParser;
import com.thaiopensource.xml.dtd.om.Dtd;
import com.thaiopensource.xml.dtd.parse.DtdParserImpl;
public class Driver {
public static void main (String args[]) throws IOException {
DtdParser dtdParser = new DtdParserImpl();
Dtd dtd = dtdParser.parse(args[0], new FileEntityManager());
new RelaxNgWriter(null).writeDtd(dtd);
String enc = EncodingMap.getJavaName(dtd.getEncoding());
BufferedWriter w = new BufferedWriter(new OutputStreamWriter(System.out,
enc));
CharRepertoire cr = CharRepertoire.getInstance(enc);
new SchemaWriter(new XmlWriter(w, cr)).writeDtd(dtd);
w.flush();
}
}
| package com.thaiopensource.xml.dtd.app;
import java.io.IOException;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import com.thaiopensource.xml.out.CharRepertoire;
import com.thaiopensource.xml.out.XmlWriter;
import com.thaiopensource.xml.util.EncodingMap;
import com.thaiopensource.xml.dtd.om.DtdParser;
import com.thaiopensource.xml.dtd.om.Dtd;
import com.thaiopensource.xml.dtd.parse.DtdParserImpl;
public class Driver {
public static void main (String args[]) throws IOException {
DtdParser dtdParser = new DtdParserImpl();
Dtd dtd = dtdParser.parse(args[0], new FileEntityManager());
String enc = EncodingMap.getJavaName(dtd.getEncoding());
BufferedWriter w = new BufferedWriter(new OutputStreamWriter(System.out,
enc));
CharRepertoire cr = CharRepertoire.getInstance(enc);
new SchemaWriter(new XmlWriter(w, cr)).writeDtd(dtd);
w.flush();
}
}
|
Fix computed value in demo | Bureaucracy.start.cols = [
{
_id: 'name',
name: "Name",
type: String
},
{
_id: 'date',
name: "Travel Date",
type: Date
},
{
_id: 'age',
name: "Age",
type: Number
},
{
_id: 'things',
name: "Things",
type: Array,
value: function(row, col) {
var xs = row[col._id];
return xs.length;
}
},
{
_id: 'location',
name: "Location",
type: Location
}
];
Bureaucracy.start.rows = [
{
_id: 'edgar',
name: "Edgar",
age: 77,
things: ["filing-cabinet"],
location: "DC",
date: "2015-02-01"
},
{
_id: 'dale',
name: "Dale",
age: 55,
things: ["microcassette recorder"],
location: "WA",
date: "2015-02-11"
},
{
_id: 'clarice',
name: "Clarice",
age: 52,
things: ["dresser", "cabinet"],
location: "OH",
date: "2015-01-30"
}
];
| Bureaucracy.start.cols = [
{
_id: 'name',
name: "Name",
type: String
},
{
_id: 'date',
name: "Travel Date",
type: Date
},
{
_id: 'age',
name: "Age",
type: Number
},
{
_id: 'things',
name: "Things",
type: Array,
value: function(xs) {
return xs.length;
}
},
{
_id: 'location',
name: "Location",
type: Location
}
];
Bureaucracy.start.rows = [
{
_id: 'edgar',
name: "Edgar",
age: 77,
things: ["filing-cabinet"],
location: "DC",
date: "2015-02-01"
},
{
_id: 'dale',
name: "Dale",
age: 55,
things: ["microcassette recorder"],
location: "WA",
date: "2015-02-11"
},
{
_id: 'clarice',
name: "Clarice",
age: 52,
things: ["dresser", "cabinet"],
location: "OH",
date: "2015-01-30"
}
];
|
Allow double return to execute query
If there’s a double return the text will end with “\n”. Closes #5. | from prompt_toolkit.buffer import Buffer
from prompt_toolkit.filters import Condition
class CypherBuffer(Buffer):
def __init__(self, *args, **kwargs):
@Condition
def is_multiline():
text = self.document.text
return not self.user_wants_out(text)
super(self.__class__, self).__init__(*args, is_multiline=is_multiline, **kwargs)
def user_wants_out(self, text):
return any(
[
text.endswith(";"),
text.endswith("\n"),
text == "quit",
text == "exit",
]
) | from prompt_toolkit.buffer import Buffer
from prompt_toolkit.filters import Condition
class CypherBuffer(Buffer):
def __init__(self, *args, **kwargs):
@Condition
def is_multiline():
text = self.document.text
return not self.user_wants_out(text)
super(self.__class__, self).__init__(*args, is_multiline=is_multiline, **kwargs)
def user_wants_out(self, text):
return any(
[
text.endswith(";"),
text == "quit",
text == "exit"
]
) |
Return MediaObject class instead of string
__toString method on object returns embed URL as before so no usage
changes required | <?php
namespace Joe1992w\LaravelMediaEmbed\Services;
use MediaEmbed\MediaEmbed;
class LaravelMediaEmbed
{
public function parse($url = null, $whitelist = [], $params = [], $attributes = []) {
$MediaEmbed = new MediaEmbed();
$MediaObject = $MediaEmbed->parseUrl($url);
if ($MediaObject)
{
if(is_array($params))
{
$MediaObject->setParam($params);
}
if(is_array($params))
{
$MediaObject->setAttribute($attributes);
}
if (!empty($whitelist))
{
if(!in_array($MediaObject->name(), $whitelist))
{
return false;
}
}
return $MediaObject;
}
return false;
}
}
| <?php
namespace Joe1992w\LaravelMediaEmbed\Services;
use MediaEmbed\MediaEmbed;
class LaravelMediaEmbed
{
public function parse($url = null, $whitelist = [], $params = [], $attributes = []) {
$MediaEmbed = new MediaEmbed();
$MediaObject = $MediaEmbed->parseUrl($url);
if ($MediaObject)
{
if(is_array($params))
{
$MediaObject->setParam($params);
}
if(is_array($params))
{
$MediaObject->setAttribute($attributes);
}
if (!empty($whitelist))
{
if(!in_array($MediaObject->name(), $whitelist))
{
return false;
}
}
return $MediaObject->getEmbedCode();
}
return false;
}
}
|
Fix up the dump options for Control.Zoom | /*
Control.Zoom.debug.js
This is wrapping the L.Control.Zoom class with .debug
(c) 2013, Aaron Racicot, Z-Pulley Inc.
*/
'use strict';
var ControlZoomDebug = L.Class.extend({
// The name of the class being wrapped with a debug
_className: "L.Control.Zoom",
_controlZoom: null,
_map: null,
initialize: function(controlZoom) {
this._map = controlZoom._map;
this._controlZoom = controlZoom;
},
dumpOptions: function() {
for (var key in this._controlZoom.options) {
console.log(key + " - " + this._controlZoom.options[key]);
}
return Object.keys(this._controlZoom.options).length;
}
});
// This is the generic hook into the testing system for this
// object type.
module.exports = function() {
L.Control.Zoom.addInitHook(function () {
L.debug.add(this);
this.debug = new ControlZoomDebug(this);
});
return [{className:"L.Control.Zoom",classRef:L.Control.Zoom}];
};
| /*
Control.Zoom.debug.js
This is wrapping the L.Control.Zoom class with .debug
(c) 2013, Aaron Racicot, Z-Pulley Inc.
*/
'use strict';
var ControlZoomDebug = L.Class.extend({
// The name of the class being wrapped with a debug
_className: "L.Control.Zoom",
_controlZoom: null,
_map: null,
initialize: function(controlZoom) {
this._map = controlZoom._map;
this._controlZoom = controlZoom;
},
dumpOptions: function() {
for (var key in this.options) {
console.log(key + " - " + this.options[key]);
}
return Object.keys(this.options).length;
}
});
// This is the generic hook into the testing system for this
// object type.
module.exports = function() {
L.Control.Zoom.addInitHook(function () {
L.debug.add(this);
this.debug = new ControlZoomDebug(this);
});
return [{className:"L.Control.Zoom",classRef:L.Control.Zoom}];
};
|
Fix null reference in figure referencing. | define(["showdown/showdown", "showdown/extensions/table"], function() {
return ["$parse", "$compile", function($parse, $compile) {
return {
restrict: 'A',
priority: 0,
link: function(scope, element, attrs) {
var pageId = scope.page ? scope.page.id : "";
Showdown.extensions.refs = function(converter) {
return [{
type: "lang",
regex: '(~D)?\\\\ref{([^}]*)}(~D)?',
replace: '<span isaac-figure-ref="' + pageId + '|$2"></span>',
}];
};
var converter = new Showdown.converter({
extensions: ["table", "refs"],
});
var parsed = $parse(attrs.bindMarkdown|| element.html());
var markdown = (parsed(scope) || "").toString();
var converted = converter.makeHtml(markdown);
element.html($compile(converted)(scope));
}
};
}];
}); | define(["showdown/showdown", "showdown/extensions/table"], function() {
return ["$parse", "$compile", function($parse, $compile) {
return {
restrict: 'A',
priority: 0,
link: function(scope, element, attrs) {
Showdown.extensions.refs = function(converter) {
return [{
type: "lang",
regex: '(~D)?\\\\ref{([^}]*)}(~D)?',
replace: '<span isaac-figure-ref="' + scope.page.id + '|$2"></span>',
}];
};
var converter = new Showdown.converter({
extensions: ["table", "refs"],
});
var parsed = $parse(attrs.bindMarkdown|| element.html());
var markdown = (parsed(scope) || "").toString();
var converted = converter.makeHtml(markdown);
element.html($compile(converted)(scope));
}
};
}];
}); |
Add PyPI classifiers and additional metadata. | #!/usr/bin/env python
import sys
import os
from setuptools import setup, find_packages
from version import VERSION
assert sys.version_info >= (2, 6), 'We only support Python 2.6+'
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'asana'))
setup(
name='asana',
version=VERSION,
description='Asana API client',
license='MIT',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4'
],
install_requires=[
'requests~=2.9.1',
'requests_oauthlib~=0.6.1',
'six~=1.10.0'
],
author='Asana, Inc',
# author_email='',
url='http://github.com/asana/python-asana',
packages=find_packages(exclude=('tests',)),
keywords='asana',
zip_safe=True,
test_suite='tests')
| #!/usr/bin/env python
import sys
import os
from setuptools import setup, find_packages
assert sys.version_info >= (2, 6), 'We only support Python 2.6+'
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'asana'))
from version import VERSION
setup(name='asana',
version=VERSION,
description='Asana API client',
# license='',
install_requires=[
'requests~=2.9.1',
'requests_oauthlib~=0.6.1',
'six~=1.10.0'
],
author='Asana, Inc',
# author_email='',
url='http://github.com/asana/python-asana',
packages = find_packages(),
keywords= 'asana',
zip_safe = True,
test_suite='tests')
|
Add check for no tasks | import datetime
import time
from .. import emails
from ..database import get_sql_connection
from ..models import Account, Session as SqlSession
__description__ = 'Send out summary emails.'
def send_out_emails():
session = SqlSession()
today = datetime.date.today()
accounts = session.query(Account) \
.filter(Account.receive_summary_email == True)
for account in accounts:
try:
email = emails.Summary(account, today)
except RuntimeError: # no tasks
continue
with emails.Mailer() as mailer:
mailer.send(email)
def command(args):
get_sql_connection()
if args.forever:
while True:
tomorrow = datetime.datetime.utcnow() + datetime.timedelta(days=1)
tomorrow = tomorrow.replace(hour=4, minute=0)
diff = tomorrow - datetime.datetime.utcnow()
time.sleep(diff.total_seconds())
send_out_emails()
else:
send_out_emails()
def add_subparser(subparsers):
parser = subparsers.add_parser('send-summary-emails', help=__description__)
parser.add_argument('--forever', action='store_true')
parser.set_defaults(func=command)
| import datetime
import time
from .. import emails
from ..database import get_sql_connection
from ..models import Account, Session as SqlSession
__description__ = 'Send out summary emails.'
def send_out_emails():
session = SqlSession()
today = datetime.date.today()
accounts = session.query(Account) \
.filter(Account.receive_summary_email == True)
for account in accounts:
email = emails.Summary(account, today)
with emails.Mailer() as mailer:
mailer.send(email)
def command(args):
get_sql_connection()
if args.forever:
while True:
tomorrow = datetime.datetime.utcnow() + datetime.timedelta(days=1)
tomorrow = tomorrow.replace(hour=4, minute=0)
diff = tomorrow - datetime.datetime.utcnow()
time.sleep(diff.total_seconds())
send_out_emails()
else:
send_out_emails()
def add_subparser(subparsers):
parser = subparsers.add_parser('send-summary-emails', help=__description__)
parser.add_argument('--forever', action='store_true')
parser.set_defaults(func=command)
|
Fix crashing bug: Compare Libya | import { createSelector } from 'reselect';
import isEmpty from 'lodash/isEmpty';
import {
parseSelectedLocations,
getSelectedLocationsFilter,
addSelectedNameToLocations
} from 'selectors/compare';
// values from search
const getSelectedLocations = state => state.selectedLocations || null;
const getContentOverviewData = state => state.ndcContentOverviewData || null;
const getCountriesData = state => state.countriesData || null;
const parseLocations = parseSelectedLocations(getSelectedLocations);
export const getLocationsFilter = getSelectedLocationsFilter(
getSelectedLocations
);
export const addNameToLocations = addSelectedNameToLocations(
getCountriesData,
parseLocations
);
export const getSummaryText = createSelector(
[addNameToLocations, getContentOverviewData],
(selectedLocations, data) => {
if (!selectedLocations || !data || isEmpty(data)) return null;
return selectedLocations.map(l => {
const d = data[l.iso_code3];
const text =
d && d.values && d.values.find(v => v.slug === 'indc_summary');
return { ...l, text: text && text.value };
});
}
);
export default {
getSummaryText,
getLocationsFilter
};
| import { createSelector } from 'reselect';
import isEmpty from 'lodash/isEmpty';
import {
parseSelectedLocations,
getSelectedLocationsFilter,
addSelectedNameToLocations
} from 'selectors/compare';
// values from search
const getSelectedLocations = state => state.selectedLocations || null;
const getContentOverviewData = state => state.ndcContentOverviewData || null;
const getCountriesData = state => state.countriesData || null;
const parseLocations = parseSelectedLocations(getSelectedLocations);
export const getLocationsFilter = getSelectedLocationsFilter(
getSelectedLocations
);
export const addNameToLocations = addSelectedNameToLocations(
getCountriesData,
parseLocations
);
export const getSummaryText = createSelector(
[addNameToLocations, getContentOverviewData],
(selectedLocations, data) => {
if (!selectedLocations || !data || isEmpty(data)) return null;
return selectedLocations.map(l => {
const d = data[l.iso_code3];
const text =
d && d.values && d.values.find(v => v.slug === 'indc_summary').value;
return { ...l, text };
});
}
);
export default {
getSummaryText,
getLocationsFilter
};
|
FIx broken links in Javadoc | package com.mapzen.android;
import com.mapzen.tangram.MapController;
/**
* This is the main class of the Mapzen Android API and is the entry point for all methods related
* to the map. You cannot instantiate a {@link MapzenMap} object directly. Rather you must obtain
* one from {@link MapFragment#getMapAsync(OnMapReadyCallback)} or
* {@link MapView#getMapAsync(OnMapReadyCallback)}.
*/
public class MapzenMap {
private final MapController mapController;
/**
* Creates a new map based on the given {@link MapController}.
*/
MapzenMap(MapController mapController) {
this.mapController = mapController;
}
/**
* Provides access to the underlying Tangram {@link MapController}.
*/
public MapController getMapController() {
return mapController;
}
}
| package com.mapzen.android;
import com.mapzen.tangram.MapController;
/**
* This is the main class of the Mapzen Android API and is the entry point for all methods related
* to the map. You cannot instantiate a {@link MapzenMap} object directly. Rather you must obtain
* one from {@link MapFragment#getMapAsync(MapView.OnMapReadyCallback)} or
* {@link MapView#getMapAsync(MapView.OnMapReadyCallback)}.
*/
public class MapzenMap {
private final MapController mapController;
/**
* Creates a new map based on the given {@link MapController}.
*/
MapzenMap(MapController mapController) {
this.mapController = mapController;
}
/**
* Provides access to the underlying Tangram {@link MapController}.
*/
public MapController getMapController() {
return mapController;
}
}
|
Use importlib instead of exec (exec was pretty ugly) | #!/usr/bin/python3
import argparse
import sys
from mawslib.manager import Manager
import importlib
configfile="cloudconfig.yaml"
parser = argparse.ArgumentParser(
#add_help=False,
description='AWS Manager',
usage='''maws [<options>] <command> <subcommand> [<args>]
For help:
maws help
maws <command> help
maws <command> <subcommand> help
''')
parser.add_argument('command', help='Command to run',
choices = ['help', 'ec2', 'sdb', 'route53', 'r53', 'rds',
'cloudformation', 'cfn' ])
parser.add_argument('--config',
help='alternate config file to use (default: cloudconfig.yaml)',
action="store")
# parse_args defaults to [1:] for args, but you need to
# exclude the rest of the args too, or validation will fail
args, subargs = parser.parse_known_args()
if hasattr(args, "config"): configfile = args.config
mgr = Manager(configfile)
mgr.showname()
if args.command == "cfn": args.command = "cloudformation"
if args.command == "r53": args.command = "route53"
cli_mod = importlib.import_module("cli.%s_cli" % args.command)
cli_mod.processCommand(mgr, subargs)
| #!/usr/bin/python3
import argparse
import sys
from mawslib.manager import Manager
configfile="cloudconfig.yaml"
parser = argparse.ArgumentParser(
#add_help=False,
description='AWS Manager',
usage='''maws [<options>] <command> <subcommand> [<args>]
For help:
maws help
maws <command> help
maws <command> <subcommand> help
''')
parser.add_argument('command', help='Command to run',
choices = ['help', 'ec2', 'sdb', 'route53', 'r53', 'rds',
'cloudformation', 'cfn' ])
parser.add_argument('--config',
help='alternate config file to use (default: cloudconfig.yaml)',
action="store")
# parse_args defaults to [1:] for args, but you need to
# exclude the rest of the args too, or validation will fail
args, subargs = parser.parse_known_args()
if hasattr(args, "config"): configfile = args.config
mgr = Manager(configfile)
mgr.showname()
if args.command == "cfn": args.command = "cloudformation"
if args.command == "r53": args.command = "route53"
exec("from cli.%s_cli import processCommand" % args.command)
processCommand(mgr, subargs)
|
IFS-9490: Complete project setup header updated | package org.innovateuk.ifs.project.internal;
public enum ProjectSetupStage {
PROJECT_DETAILS("Project details", 1),
PROJECT_TEAM("Project team", 2),
DOCUMENTS("Documents", 3),
MONITORING_OFFICER("MO", 4),
BANK_DETAILS("Bank details", 5),
FINANCE_CHECKS("Finance checks", 6),
SPEND_PROFILE("Spend profile", 7), //Some competitions don't have this stage. They automatically approve the spend profile.
GRANT_OFFER_LETTER("GOL", 8),
PROJECT_SETUP_COMPLETE("Complete project setup", 9);
private int priority;
private String shortName;
ProjectSetupStage(String shortName, int priority) {
this.shortName = shortName;
this.priority = priority;
}
public int getPriority() {
return priority;
}
public String getShortName() {
return shortName;
}
}
| package org.innovateuk.ifs.project.internal;
public enum ProjectSetupStage {
PROJECT_DETAILS("Project details", 1),
PROJECT_TEAM("Project team", 2),
DOCUMENTS("Documents", 3),
MONITORING_OFFICER("MO", 4),
BANK_DETAILS("Bank details", 5),
FINANCE_CHECKS("Finance checks", 6),
SPEND_PROFILE("Spend profile", 7), //Some competitions don't have this stage. They automatically approve the spend profile.
GRANT_OFFER_LETTER("GOL", 8),
PROJECT_SETUP_COMPLETE("Project setup complete", 9);
private int priority;
private String shortName;
ProjectSetupStage(String shortName, int priority) {
this.shortName = shortName;
this.priority = priority;
}
public int getPriority() {
return priority;
}
public String getShortName() {
return shortName;
}
}
|
Fix path to global node_modules on Windows | /*!
* global-prefix <https://github.com/jonschlinkert/global-prefix>
*
* Copyright (c) 2015 Jon Schlinkert.
* Licensed under the MIT license.
*/
'use strict';
/**
* This is the code used internally by npm to
* resolve the global prefix.
*/
var isWindows = require('is-windows');
var path = require('path');
var prefix;
if (process.env.PREFIX) {
prefix = process.env.PREFIX;
} else if (isWindows === true || isWindows()) {
// c:\node\node.exe --> prefix=c:\node\
prefix = process.env.APPDATA
? path.join(process.env.APPDATA, 'npm')
: path.dirname(process.execPath);
} else {
// /usr/local/bin/node --> prefix=/usr/local
prefix = path.dirname(path.dirname(process.execPath));
// destdir only is respected on Unix
if (process.env.DESTDIR) {
prefix = path.join(process.env.DESTDIR, prefix);
}
}
module.exports = prefix;
| /*!
* global-prefix <https://github.com/jonschlinkert/global-prefix>
*
* Copyright (c) 2015 Jon Schlinkert.
* Licensed under the MIT license.
*/
'use strict';
/**
* This is the code used internally by npm to
* resolve the global prefix.
*/
var isWindows = require('is-windows');
var path = require('path');
var prefix;
if (process.env.PREFIX) {
prefix = process.env.PREFIX;
} else if (isWindows === true || isWindows()) {
// c:\node\node.exe --> prefix=c:\node\
prefix = path.dirname(process.execPath);
} else {
// /usr/local/bin/node --> prefix=/usr/local
prefix = path.dirname(path.dirname(process.execPath));
// destdir only is respected on Unix
if (process.env.DESTDIR) {
prefix = path.join(process.env.DESTDIR, prefix);
}
}
module.exports = prefix;
|
Update test to assert metric | import pytest
import mock
from datadog_checks.checks import AgentCheck
from datadog_checks.ping import PingCheck
from datadog_checks.errors import CheckException
def mock_exec_ping():
return """FAKEPING 127.0.0.1 (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.093 ms
--- 127.0.0.1 ping statistics ---
1 packets transmitted, 1 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 0.093/0.093/0.093/0.000 ms"""
def test_check(aggregator, instance):
c = PingCheck('ping', {}, {})
# empty instance
instance = {}
with pytest.raises(CheckException):
c.check(instance)
# only name
with pytest.raises(CheckException):
c.check({'name': 'Datadog'})
test_check
# good check
instance = {
'host': '127.0.0.1',
'name': "Localhost"
}
with mock.patch.object(c, "_exec_ping", return_value=mock_exec_ping()):
c.check(instance)
aggregator.assert_service_check('network.ping.can_connect', AgentCheck.OK)
aggregator.assert_metric('network.ping.can_connect', value=1)
| import pytest
import mock
from datadog_checks.checks import AgentCheck
from datadog_checks.ping import PingCheck
from datadog_checks.errors import CheckException
def mock_exec_ping():
return """FAKEPING 127.0.0.1 (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.093 ms
--- 127.0.0.1 ping statistics ---
1 packets transmitted, 1 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 0.093/0.093/0.093/0.000 ms"""
def test_check(aggregator, instance):
c = PingCheck('ping', {}, {})
# empty instance
instance = {}
with pytest.raises(CheckException):
c.check(instance)
# only name
with pytest.raises(CheckException):
c.check({'name': 'Datadog'})
test_check
# good check
instance = {
'host': '127.0.0.1',
'name': "Localhost"
}
with mock.patch.object(c, "_exec_ping", return_value=mock_exec_ping()):
c.check(instance)
aggregator.assert_service_check('network.ping.can_connect', AgentCheck.OK)
|
Add "Ok" button to about dialog | package de.cketti.holocolorpicker.demo;
import com.actionbarsherlock.app.SherlockDialogFragment;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
/**
* Show an "About" dialog
*/
public class AboutDialogFragment extends SherlockDialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.label_about);
builder.setPositiveButton(android.R.string.ok, null);
View view = LayoutInflater.from(getActivity()).inflate(R.layout.about_dialog, null);
TextView about = (TextView) view.findViewById(R.id.about_text);
about.setText(Html.fromHtml(getString(R.string.about_text)));
about.setMovementMethod(LinkMovementMethod.getInstance());
builder.setView(view);
return builder.create();
}
}
| package de.cketti.holocolorpicker.demo;
import com.actionbarsherlock.app.SherlockDialogFragment;
import android.app.Dialog;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* Show an "About" dialog
*/
public class AboutDialogFragment extends SherlockDialogFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.about_dialog, null);
TextView about = (TextView) view.findViewById(R.id.about_text);
about.setText(Html.fromHtml(getString(R.string.about_text)));
about.setMovementMethod(LinkMovementMethod.getInstance());
Dialog dialog = getDialog();
dialog.setTitle(R.string.label_about);
return view;
}
}
|
Set component callbacks to null to prevent unexpected method invocations. | package eu.luminis.devcon.rest;
import org.apache.felix.dm.DependencyActivatorBase;
import org.apache.felix.dm.DependencyManager;
import org.osgi.framework.BundleContext;
import eu.luminis.devcon.RocketLauncher;
public class Activator extends DependencyActivatorBase {
@Override
public void init(BundleContext arg0, DependencyManager manager)
throws Exception {
manager.add(createComponent()
.setInterface(Object.class.getName(), null)
.setImplementation(RocketLauncherRest.class)
.setCallbacks(null, null, null, null)
.add(createServiceDependency().setService(RocketLauncher.class).setRequired(true))
);
}
@Override
public void destroy(BundleContext arg0, DependencyManager arg1)
throws Exception {
// TODO Auto-generated method stub
}
}
| package eu.luminis.devcon.rest;
import org.apache.felix.dm.DependencyActivatorBase;
import org.apache.felix.dm.DependencyManager;
import org.osgi.framework.BundleContext;
import eu.luminis.devcon.RocketLauncher;
public class Activator extends DependencyActivatorBase {
@Override
public void init(BundleContext arg0, DependencyManager manager)
throws Exception {
manager.add(createComponent()
.setInterface(Object.class.getName(), null)
.setImplementation(RocketLauncherRest.class)
.add(createServiceDependency().setService(RocketLauncher.class).setRequired(true))
);
}
@Override
public void destroy(BundleContext arg0, DependencyManager arg1)
throws Exception {
// TODO Auto-generated method stub
}
}
|
Create session if one doesn't exist | from lightning import Lightning
def viztype(VizType):
def plotter(self, *args, **kwargs):
if not hasattr(self, 'session'):
self.create_session()
viz = VizType.baseplot(self.session, VizType._name, *args, **kwargs)
self.session.visualizations.append(viz)
return viz
if not hasattr(VizType,'_func'):
func = VizType._name
else:
func = VizType._func
setattr(Lightning, func, plotter)
return VizType
def imgtype(ImgType):
def plotter(self, *args, **kwargs):
img = ImgType.baseimage(self.session, ImgType._name, *args, **kwargs)
self.session.visualizations.append(img)
return img
if not hasattr(ImgType, '_func'):
func = ImgType._name
else:
func = ImgType._func
setattr(Lightning, func, plotter)
return ImgType | from lightning import Lightning
def viztype(VizType):
def plotter(self, *args, **kwargs):
viz = VizType.baseplot(self.session, VizType._name, *args, **kwargs)
self.session.visualizations.append(viz)
return viz
if not hasattr(VizType,'_func'):
func = VizType._name
else:
func = VizType._func
setattr(Lightning, func, plotter)
return VizType
def imgtype(ImgType):
def plotter(self, *args, **kwargs):
img = ImgType.baseimage(self.session, ImgType._name, *args, **kwargs)
self.session.visualizations.append(img)
return img
if not hasattr(ImgType, '_func'):
func = ImgType._name
else:
func = ImgType._func
setattr(Lightning, func, plotter)
return ImgType |
Use production settings by default; Display settings version in use | # Project Settings - Settings that don't exist in settings.py that you want to
# add (e.g. USE_THOUSAND_SEPARATOR, GRAPPELLI_ADMIN_TITLE, CELERYBEAT_SCHEDULER,
# CELERYD_PREFETCH_MULTIPLIER, etc.)
#USE_THOUSAND_SEPARATOR = True
#GRAPPELLI_ADMIN_TITLE = ''
#import djcelery
#djcelery.setup_loader()
#CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler'
#CELERYD_PREFETCH_MULTIPLIER = 1
import os
import sys
version = 'PRODUCTION'
color = '[1;92m' # Bold High Intensity Green + Underline
if 'PRODUCTION' in os.environ and os.environ['PRODUCTION'].lower() in [True, 'y', 'yes', '1',]:
from local_settings import *
elif 'runserver' in sys.argv:
version = 'DEVELOPMENT'
color = '[1;93m' # Bold High Intensity Yellow + Underline
from local_settings import *
else:
from local_settings import *
print '\n{star} \x1b{color}{version}\x1b[0m {star}\n'.format(color=color,
star='\xE2\x98\x85',
version=version)
| # Project Settings - Settings that don't exist in settings.py that you want to
# add (e.g. USE_THOUSAND_SEPARATOR, GRAPPELLI_ADMIN_TITLE, CELERYBEAT_SCHEDULER,
# CELERYD_PREFETCH_MULTIPLIER, etc.)
#USE_THOUSAND_SEPARATOR = True
#GRAPPELLI_ADMIN_TITLE = ''
#import djcelery
#djcelery.setup_loader()
#CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler'
#CELERYD_PREFETCH_MULTIPLIER = 1
import os
import sys
if 'PRODUCTION' in os.environ and os.environ['PRODUCTION'].lower() in [True, 'y', 'yes', '1',]:
from production_settings import *
elif 'runserver' in sys.argv:
from local_settings import *
else:
from production_settings import *
|
Remove long description as causing pip error | from setuptools import setup, find_packages
setup(
name = "django-disposable-email-checker",
version = "0.1.1",
packages = find_packages(),
author = "Aaron Bassett",
author_email = "me@aaronbassett.com",
description = "Python class for use with Django to detect Disposable Emails",
license = "MIT License",
keywords = "django email disposable validation",
url = "https://github.com/aaronbassett/DisposableEmailChecker",
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 2 :: Only',
'Framework :: Django'
]
) | from setuptools import setup, find_packages
with open('README.rst') as f:
readme = f.read()
setup(
name = "django-disposable-email-checker",
version = "0.1.1",
packages = find_packages(),
package_data = {
# If any package contains *.txt or *.rst files, include them:
'': ['*.txt', '*.rst'],
},
author = "Aaron Bassett",
author_email = "me@aaronbassett.com",
description = "Python class for use with Django to detect Disposable Emails",
long_description=readme,
license = "MIT License",
keywords = "django email disposable validation",
url = "https://github.com/aaronbassett/DisposableEmailChecker",
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 2 :: Only',
'Framework :: Django'
]
) |
Patch for using DB Rider with MS SQL Server
Added IDENTITY_INSERT SeedStrategy to avoid following error:
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Cannot insert explicit value for identity column in table 'xxxxx' when IDENTITY_INSERT is set to OFF. | package com.github.database.rider.core.api.dataset;
/**
* Created by pestano on 23/07/15.
*/
import org.dbunit.operation.*;
/**
Same as arquillian persistence: https://docs.jboss.org/author/display/ARQ/Persistence
Data insert strategies
DBUnit, and hence Arquillian Persistence Extension, provides following strategies for inserting data
INSERT
Performs insert of the data defined in provided data sets. This is the default strategy.
CLEAN_INSERT
Performs insert of the data defined in provided data sets, after removal of all data present in the tables (DELETE_ALL invoked by DBUnit before INSERT).
REFRESH
During this operation existing rows are updated and new ones are inserted. Entries already existing in the database which are not defined in the provided data set are not affected.
UPDATE
This strategy updates existing rows using data provided in the datasets. If dataset contain a row which is not present in the database (identified by its primary key) then exception is thrown.
*/
public enum SeedStrategy {
CLEAN_INSERT(DatabaseOperation.CLEAN_INSERT),
TRUNCATE_INSERT(new CompositeOperation(DatabaseOperation.TRUNCATE_TABLE, DatabaseOperation.INSERT)),
INSERT(DatabaseOperation.INSERT),
REFRESH(DatabaseOperation.REFRESH),
UPDATE(DatabaseOperation.UPDATE),
IDENTITY_INSERT(InsertIdentityOperation.CLEAN_INSERT);
private final DatabaseOperation operation;
SeedStrategy(DatabaseOperation operation) {
this.operation = operation;
}
public DatabaseOperation getOperation() {
return operation;
}
}
| package com.github.database.rider.core.api.dataset;
/**
* Created by pestano on 23/07/15.
*/
import org.dbunit.operation.*;
/**
Same as arquillian persistence: https://docs.jboss.org/author/display/ARQ/Persistence
Data insert strategies
DBUnit, and hence Arquillian Persistence Extension, provides following strategies for inserting data
INSERT
Performs insert of the data defined in provided data sets. This is the default strategy.
CLEAN_INSERT
Performs insert of the data defined in provided data sets, after removal of all data present in the tables (DELETE_ALL invoked by DBUnit before INSERT).
REFRESH
During this operation existing rows are updated and new ones are inserted. Entries already existing in the database which are not defined in the provided data set are not affected.
UPDATE
This strategy updates existing rows using data provided in the datasets. If dataset contain a row which is not present in the database (identified by its primary key) then exception is thrown.
*/
public enum SeedStrategy {
CLEAN_INSERT(DatabaseOperation.CLEAN_INSERT),
TRUNCATE_INSERT(new CompositeOperation(DatabaseOperation.TRUNCATE_TABLE, DatabaseOperation.INSERT)),
INSERT(DatabaseOperation.INSERT),
REFRESH(DatabaseOperation.REFRESH),
UPDATE(DatabaseOperation.UPDATE);
private final DatabaseOperation operation;
SeedStrategy(DatabaseOperation operation) {
this.operation = operation;
}
public DatabaseOperation getOperation() {
return operation;
}
}
|
Change sybase skip test to check for more restrictive vv creds
This should let the report-writing test that uses the axafvv query
run as jeanconn user, but skip for other users. | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import tempfile
import os
import shutil
import pytest
from .. import report
try:
import Ska.DBI
with Ska.DBI.DBI(server='sqlsao', dbi='sybase', user='jeanconn', database='axafvv') as db:
HAS_SYBASE_ACCESS = True
except:
HAS_SYBASE_ACCESS = False
HAS_SC_ARCHIVE = os.path.exists(report.starcheck.FILES['data_root'])
@pytest.mark.skipif('not HAS_SYBASE_ACCESS', reason='Report test requires Sybase VV access')
@pytest.mark.skipif('not HAS_SC_ARCHIVE', reason='Report test requires mica starcheck archive')
def test_write_reports():
"""
Make a report and database
"""
tempdir = tempfile.mkdtemp()
# Get a temporary file, but then delete it, because report.py will only
# make a new table if the supplied file doesn't exist
fh, fn = tempfile.mkstemp(dir=tempdir, suffix='.db3')
os.unlink(fn)
report.REPORT_ROOT = tempdir
report.REPORT_SERVER = fn
for obsid in [20001, 15175, 54778]:
report.main(obsid)
os.unlink(fn)
shutil.rmtree(tempdir)
| # Licensed under a 3-clause BSD style license - see LICENSE.rst
import tempfile
import os
import shutil
import pytest
from .. import report
try:
import Ska.DBI
with Ska.DBI.DBI(server='sqlsao', dbi='sybase', user='aca_ops', database='axafocat') as db:
HAS_SYBASE_ACCESS = True
except:
HAS_SYBASE_ACCESS = False
HAS_SC_ARCHIVE = os.path.exists(report.starcheck.FILES['data_root'])
@pytest.mark.skipif('not HAS_SYBASE_ACCESS', reason='Report test requires Sybase/OCAT access')
@pytest.mark.skipif('not HAS_SC_ARCHIVE', reason='Report test requires mica starcheck archive')
def test_write_reports():
"""
Make a report and database
"""
tempdir = tempfile.mkdtemp()
# Get a temporary file, but then delete it, because report.py will only
# make a new table if the supplied file doesn't exist
fh, fn = tempfile.mkstemp(dir=tempdir, suffix='.db3')
os.unlink(fn)
report.REPORT_ROOT = tempdir
report.REPORT_SERVER = fn
for obsid in [20001, 15175, 54778]:
report.main(obsid)
os.unlink(fn)
shutil.rmtree(tempdir)
|
Correct position of comment :) | import re
from redis import Redis
import json
from datetime import datetime
def is_valid_chatroom(chatroom):
return re.match('[A-Za-z_\\d]+$', chatroom) is not None
def get_redis():
return Redis()
def get_conversation(chatroom):
if chatroom is None or len(chatroom) == 0:
return None
storage = get_redis()
return [
json.loads(m)
for m in storage.lrange('notifexample:' + chatroom, 0, -1)
]
def send_message(chatroom, user_id, name, message):
if '<script>' in message:
message += '-- Not this time DefConFags'
storage = get_redis()
now = datetime.now()
created_on = now.strftime('%Y-%m-%d %H:%M:%S')
# if chatroom doesn't exist create it!
storage.rpush(
'notifexample:' + chatroom,
json.dumps({
'author': name,
'userID': user_id,
'message': message,
'createdOn': created_on
})
)
| import re
from redis import Redis
import json
from datetime import datetime
def is_valid_chatroom(chatroom):
return re.match('[A-Za-z_\\d]+$', chatroom) is not None
def get_redis():
return Redis()
def get_conversation(chatroom):
if chatroom is None or len(chatroom) == 0:
return None
# if chatroom doesn't exist create it!
storage = get_redis()
return [
json.loads(m)
for m in storage.lrange('notifexample:' + chatroom, 0, -1)
]
def send_message(chatroom, user_id, name, message):
if '<script>' in message:
message += '-- Not this time DefConFags'
storage = get_redis()
now = datetime.now()
created_on = now.strftime('%Y-%m-%d %H:%M:%S')
storage.rpush(
'notifexample:' + chatroom,
json.dumps({
'author': name,
'userID': user_id,
'message': message,
'createdOn': created_on
})
)
|
Revert "Review ex11 and ex12"
This reverts commit e5fe21acd40e9ebeae548e906747702783058d06. | # Upper is ex11, lower part is ex 12
# Both print out are same, but ex11 needs 8 lines,
# ex 12 just need it for 4 lines.
print "How old are you?", #Becasue can't use print and value in same line
age = raw_input() # That's why need two lines to do so.
print "How tall are you?",
height = raw_input()
print "How much do you weigh?",
weight = raw_input()
print "So, you're %r, old, %r tall and %r heavy." % (
age, height, weight)
#---------------------- this is ex11.py
# let's compare!!
age = raw_input % ("How old are you? ") # when typed raw_input() the (), which are
height = raw_input % ("How tall are you? ") #similiar with " %s %s" % (x, y)
weight = raw_input("How much do you weight? ") # that's why the () can put the prompt.
print "So, you're %r old, %r tall and %r heavy." % (age, height, weight)
# as teacher said print and raw_input can't put @ the same line.
# if want to use print and raw_input need to use 2 line!!
# otherwise need to make it like the ex12.py age = raw_input("How old are you? ")
| # Upper is ex11, lower part is ex 12
# Both print out are same, but ex11 needs 8 lines,
# ex 12 just need it for 4 lines.
print "How old are you?", # Becasue can't use print and value in same line
age = raw_input() # That's why need two lines to do so.
print "How tall are you?",
height = raw_input()
print "How much do you weigh?",
weight = raw_input()
print "So, you're %r, old, %r tall and %r heavy." % (age, height, weight)
#---------------------- this is ex11.py
# let's compare!!
age = raw_input("How old are you? ") # when typed raw_input() the (), which are
height = raw_input("How tall are you? ") #similiar with " %s %s" % (x, y)
weight = raw_input("How much do you weight? ") # that's why the () can put the prompt.
print "So, you're %r old, %r tall and %r heavy." % (age, height, weight)
# as teacher said print and raw_input can't put @ the same line.
# if want to use print and raw_input need to use 2 line!!
# otherwise need to make it like the ex12.py age = raw_input("How old are you? ")
# -------
# The difference btw ex11 and ex12 is the use of prompt string as an
# argument for `raw_input` function
prompt_string = "How old are you? "
print prompt_string
age = raw_input()
# vs
age = raw_input(prompt_string)
|
Add @NonNull to message parameter of overridden method log | /*
* Copyright 2017 Martin Kamp Jensen
*
* 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.github.mkjensen.tv.util;
import android.support.annotation.NonNull;
import com.crashlytics.android.Crashlytics;
import timber.log.Timber;
public class CrashlyticsTimberTree extends Timber.Tree {
private static final String PRIORITY_KEY = "priority";
private static final String TAG_KEY = "tag";
private static final String MESSAGE_KEY = "message";
@Override
protected void log(int priority, String tag, @NonNull String message, Throwable throwable) {
if (priority < android.util.Log.WARN) {
return;
}
Crashlytics.setInt(PRIORITY_KEY, priority);
Crashlytics.setString(TAG_KEY, tag);
Crashlytics.setString(MESSAGE_KEY, message);
if (throwable == null) {
Crashlytics.logException(new Exception(message));
} else {
Crashlytics.logException(throwable);
}
}
}
| /*
* Copyright 2017 Martin Kamp Jensen
*
* 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.github.mkjensen.tv.util;
import com.crashlytics.android.Crashlytics;
import timber.log.Timber;
public class CrashlyticsTimberTree extends Timber.Tree {
private static final String PRIORITY_KEY = "priority";
private static final String TAG_KEY = "tag";
private static final String MESSAGE_KEY = "message";
@Override
protected void log(int priority, String tag, String message, Throwable throwable) {
if (priority < android.util.Log.WARN) {
return;
}
Crashlytics.setInt(PRIORITY_KEY, priority);
Crashlytics.setString(TAG_KEY, tag);
Crashlytics.setString(MESSAGE_KEY, message);
if (throwable == null) {
Crashlytics.logException(new Exception(message));
} else {
Crashlytics.logException(throwable);
}
}
}
|
Make AccessibilityTextView inherit from AppCompatTextView | /*
* Copyright (C) 2013 The Android Open Source Project
*
* 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.wdullaer.materialdatetimepicker;
import android.content.Context;
import android.util.AttributeSet;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.Button;
/**
* Fake Button class, used so TextViews can announce themselves as Buttons, for accessibility.
*/
public class AccessibleTextView extends androidx.appcompat.widget.AppCompatTextView {
public AccessibleTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
super.onInitializeAccessibilityEvent(event);
event.setClassName(Button.class.getName());
}
@Override
public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
super.onInitializeAccessibilityNodeInfo(info);
info.setClassName(Button.class.getName());
}
}
| /*
* Copyright (C) 2013 The Android Open Source Project
*
* 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.wdullaer.materialdatetimepicker;
import android.content.Context;
import android.util.AttributeSet;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.Button;
import android.widget.TextView;
/**
* Fake Button class, used so TextViews can announce themselves as Buttons, for accessibility.
*/
public class AccessibleTextView extends TextView {
public AccessibleTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
super.onInitializeAccessibilityEvent(event);
event.setClassName(Button.class.getName());
}
@Override
public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
super.onInitializeAccessibilityNodeInfo(info);
info.setClassName(Button.class.getName());
}
}
|
Add runc to usable executor options!
Signed-off-by: Eric Myhre <2346ad27d7568ba9896f1b7da6b5991251debdf2@exultant.us> | package executordispatch
import (
"path/filepath"
"polydawn.net/repeatr/def"
"polydawn.net/repeatr/executor"
"polydawn.net/repeatr/executor/chroot"
"polydawn.net/repeatr/executor/nsinit"
"polydawn.net/repeatr/executor/null"
"polydawn.net/repeatr/executor/runc"
)
// TODO: This should not require a global string -> class map :|
// Should attempt to reflect-find, trying main package name first.
// Will make simpler to use extended transports, etc.
func Get(desire string) executor.Executor {
var executor executor.Executor
switch desire {
case "null":
executor = &null.Executor{}
case "nsinit":
executor = &nsinit.Executor{}
case "chroot":
executor = &chroot.Executor{}
case "runc":
executor = &runc.Executor{}
default:
panic(def.ValidationError.New("No such executor %s", desire))
}
// Set the base path to operate from
executor.Configure(filepath.Join(def.Base(), "executor", desire))
return executor
}
| package executordispatch
import (
"path/filepath"
"polydawn.net/repeatr/def"
"polydawn.net/repeatr/executor"
"polydawn.net/repeatr/executor/chroot"
"polydawn.net/repeatr/executor/nsinit"
"polydawn.net/repeatr/executor/null"
)
// TODO: This should not require a global string -> class map :|
// Should attempt to reflect-find, trying main package name first.
// Will make simpler to use extended transports, etc.
func Get(desire string) executor.Executor {
var executor executor.Executor
switch desire {
case "null":
executor = &null.Executor{}
case "nsinit":
executor = &nsinit.Executor{}
case "chroot":
executor = &chroot.Executor{}
default:
panic(def.ValidationError.New("No such executor %s", desire))
}
// Set the base path to operate from
executor.Configure(filepath.Join(def.Base(), "executor", desire))
return executor
}
|
Hide the fact that we're using a ctor for side effects | package rxbroadcast;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.hamcrest.CoreMatchers;
import org.junit.Assert;
import org.junit.Test;
@SuppressWarnings({"checkstyle:MagicNumber"})
public final class VectorTimestampTest {
@Test
public final void equalsContract() {
EqualsVerifier.forClass(VectorTimestamp.class)
.withCachedHashCode("hashCode", "computeHashCode", new VectorTimestamp(
new Sender[]{new Sender(new byte[] {42}), new Sender(new byte[]{43})}, new long[]{1, 2}
))
.verify();
}
@Test(expected = IllegalArgumentException.class)
public final void timestampMustHaveEqualLengthFields() {
final VectorTimestamp t = new VectorTimestamp(new Sender[0], new long[]{3, 4});
Assert.assertThat(t, CoreMatchers.notNullValue());
}
}
| package rxbroadcast;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.Test;
@SuppressWarnings({"checkstyle:MagicNumber"})
public final class VectorTimestampTest {
@Test
public final void equalsContract() {
EqualsVerifier.forClass(VectorTimestamp.class)
.withCachedHashCode("hashCode", "computeHashCode", new VectorTimestamp(
new Sender[]{new Sender(new byte[] {42}), new Sender(new byte[]{43})}, new long[]{1, 2}
))
.verify();
}
@Test(expected = IllegalArgumentException.class)
public final void timestampMustHaveEqualLengthFields() {
new VectorTimestamp(new Sender[0], new long[]{3, 4});
}
}
|
Use print as a function and tweak output text | import numpy as np
from Chandra.Time import DateTime
import plot_aimpoint
# Get 99th percential absolute pointing radius
plot_aimpoint.opt = plot_aimpoint.get_opt()
asols = plot_aimpoint.get_asol()
# Last six months of data
asols = asols[asols['time'] > DateTime(-183).secs]
# center of box of range of data
mid_dy = (np.max(asols['dy']) + np.min(asols['dy'])) / 2.
mid_dz = (np.max(asols['dz']) + np.min(asols['dz'])) / 2.
# radius of each delta in mm (asol dy dz in mm)
dr = np.sqrt((asols['dy'] - mid_dy) ** 2 + (asols['dz'] - mid_dz) ** 2)
dr_99 = np.percentile(dr, 99)
dr_99_arcsec = dr_99 * 20
print("99th percentile radius of 6-month data is {} arcsec".format(dr_99_arcsec))
| import numpy as np
from Chandra.Time import DateTime
import plot_aimpoint
# Get 99th percential absolute pointing radius
plot_aimpoint.opt = plot_aimpoint.get_opt()
asols = plot_aimpoint.get_asol()
# Last six months of data
asols = asols[asols['time'] > DateTime(-183).secs]
# center of box of range of data
mid_dy = (np.max(asols['dy']) + np.min(asols['dy'])) / 2.
mid_dz = (np.max(asols['dz']) + np.min(asols['dz'])) / 2.
# radius of each delta in mm (asol dy dz in mm)
dr = np.sqrt((asols['dy'] - mid_dy) ** 2 + (asols['dz'] - mid_dz) ** 2)
dr_99 = np.percentile(dr, 99)
dr_99_arcsec = dr_99 * 20
print "99th percentile radius of 6m data is {} arcsec".format(dr_99_arcsec)
|
Increment minor version after ArcGIS fix and improved tests and docs | import subprocess
import sys
from setuptools import Command, setup
class RunTests(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
errno = subprocess.call([sys.executable, '-m', 'unittest', 'gis_metadata.tests.tests'])
raise SystemExit(errno)
with open('README.md') as readme:
long_description = readme.read()
setup(
name='gis-metadata-parser',
description='Parser for GIS metadata standards including FGDC and ISO-19115',
long_description=long_description,
long_description_content_type='text/markdown',
keywords='arcgis,fgdc,iso,ISO-19115,ISO-19139,gis,metadata,parser,xml,gis_metadata,gis_metadata_parser',
version='1.2.4',
packages=[
'gis_metadata', 'gis_metadata.tests'
],
install_requires=[
'frozendict>=1.2', 'parserutils>=1.1', 'six>=1.9.0'
],
tests_require=['mock'],
url='https://github.com/consbio/gis-metadata-parser',
license='BSD',
cmdclass={'test': RunTests}
)
| import subprocess
import sys
from setuptools import Command, setup
class RunTests(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
errno = subprocess.call([sys.executable, '-m', 'unittest', 'gis_metadata.tests.tests'])
raise SystemExit(errno)
with open('README.md') as readme:
long_description = readme.read()
setup(
name='gis-metadata-parser',
description='Parser for GIS metadata standards including FGDC and ISO-19115',
long_description=long_description,
long_description_content_type='text/markdown',
keywords='arcgis,fgdc,iso,ISO-19115,ISO-19139,gis,metadata,parser,xml,gis_metadata,gis_metadata_parser',
version='1.2.3',
packages=[
'gis_metadata', 'gis_metadata.tests'
],
install_requires=[
'frozendict>=1.2', 'parserutils>=1.1', 'six>=1.9.0'
],
tests_require=['mock'],
url='https://github.com/consbio/gis-metadata-parser',
license='BSD',
cmdclass={'test': RunTests}
)
|
Add setup and teardown code | package com.grayben.riskExtractor.htmlScorer.partScorers.tagScorers;
import org.jsoup.parser.Tag;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.*;
/**
* Created by beng on 22/12/2015.
*/
@RunWith(MockitoJUnitRunner.class)
public class TagSegmentationScorerTest extends MapScorerTest<Tag> {
TagSegmentationScorer tagSegmentationScorerSUT;
@Mock public Tag tagToBeScoredMock;
@Before
public void setUp() throws Exception {
this.tagSegmentationScorerSUT
= new TagSegmentationScorer(
TagSegmentationScorer.defaultMap()
);
super.setMapScorerSUT(this.tagSegmentationScorerSUT);
super.setUp();
}
@After
public void tearDown() throws Exception {
super.tearDown();
}
@Override
@Test
public void test_ScoreReturnsInteger_WhenArgumentIsNotEmpty() throws Exception {
}
@Override
@Test
public void test_ScoreGivesExpectedResult_WhenSimpleInput() throws Exception {
}
@Override
@Test
public void test_InitThrowsNullPointerException_WhenMapParamIsNull() throws Exception {
}
} | package com.grayben.riskExtractor.htmlScorer.partScorers.tagScorers;
import org.jsoup.parser.Tag;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.*;
/**
* Created by beng on 22/12/2015.
*/
@RunWith(MockitoJUnitRunner.class)
public class TagSegmentationScorerTest extends MapScorerTest<Tag> {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Override
@Test
public void test_ScoreReturnsInteger_WhenArgumentIsNotEmpty() throws Exception {
}
@Override
@Test
public void test_ScoreGivesExpectedResult_WhenSimpleInput() throws Exception {
}
@Override
@Test
public void test_InitThrowsNullPointerException_WhenMapParamIsNull() throws Exception {
}
} |
FIX ember docs generation if the component parameter is missing (for whatever reason) | /* eslint-disable no-underscore-dangle */
/* global window */
export const setJSONDoc = jsondoc => {
window.__EMBER_GENERATED_DOC_JSON__ = jsondoc;
};
export const getJSONDoc = () => {
return window.__EMBER_GENERATED_DOC_JSON__;
};
export const extractProps = componentName => {
const json = getJSONDoc();
const componentDoc = json.included.find(doc => doc.attributes.name === componentName);
const rows = componentDoc.attributes.arguments.map(prop => {
return {
name: prop.name,
type: prop.type,
required: prop.tags.length ? prop.tags.some(tag => tag.name === 'required') : false,
defaultValue: prop.defaultValue,
description: prop.description,
};
});
return { rows };
};
export const extractComponentDescription = componentName => {
const json = getJSONDoc();
const componentDoc = json.included.find(doc => doc.attributes.name === componentName);
if (!componentDoc) {
return '';
}
return componentDoc.attributes.description;
};
| /* eslint-disable no-underscore-dangle */
/* global window */
export const setJSONDoc = jsondoc => {
window.__EMBER_GENERATED_DOC_JSON__ = jsondoc;
};
export const getJSONDoc = () => {
return window.__EMBER_GENERATED_DOC_JSON__;
};
export const extractProps = componentName => {
const json = getJSONDoc();
const componentDoc = json.included.find(doc => doc.attributes.name === componentName);
const rows = componentDoc.attributes.arguments.map(prop => {
return {
name: prop.name,
type: prop.type,
required: prop.tags.length ? prop.tags.some(tag => tag.name === 'required') : false,
defaultValue: prop.defaultValue,
description: prop.description,
};
});
return { rows };
};
export const extractComponentDescription = componentName => {
const json = getJSONDoc();
const componentDoc = json.included.find(doc => doc.attributes.name === componentName);
return componentDoc.attributes.description;
};
|
Add `export` to emitted lines | #!/usr/bin/env python
import collections
import sys
import jprops
def do_replacements(s, mappings):
for old, new in mappings.items():
s = s.replace(old, new)
return s
def key_transform(key):
key = do_replacements(key, {'.': '_',
':': '_',
'-': '_'})
return key.upper()
def value_transform(value):
return do_replacements(value, {"\n": "\\n",
"'": """'"'"'"""})
def jprops2bash(fh, key_transform=key_transform, value_transform=value_transform):
props_dict = jprops.load_properties(fh, collections.OrderedDict)
for key, value in props_dict.items():
key = key_transform(key)
value = value_transform(value)
yield """export {key}='{value}'""".format(key=key, value=value)
def main():
for line in jprops2bash(sys.stdin):
print(line)
if __name__ == '__main__':
sys.exit(main())
| #!/usr/bin/env python
import collections
import sys
import jprops
def do_replacements(s, mappings):
for old, new in mappings.items():
s = s.replace(old, new)
return s
def key_transform(key):
key = do_replacements(key, {'.': '_',
':': '_',
'-': '_'})
return key.upper()
def value_transform(value):
return do_replacements(value, {"\n": "\\n",
"'": """'"'"'"""})
def jprops2bash(fh, key_transform=key_transform, value_transform=value_transform):
props_dict = jprops.load_properties(fh, collections.OrderedDict)
for key, value in props_dict.items():
key = key_transform(key)
value = value_transform(value)
yield """{key}='{value}'""".format(key=key, value=value)
def main():
for line in jprops2bash(sys.stdin):
print(line)
if __name__ == '__main__':
sys.exit(main())
|
Update a version number from trunk r9016 | # -*- coding: utf-8 -*-
__version__ = '$Id$'
import family
# The Wikia Search family
# user-config.py: usernames['wikia']['wikia'] = 'User name'
class Family(family.Family):
def __init__(self):
family.Family.__init__(self)
self.name = u'wikia'
self.langs = {
u'wikia': None,
}
def hostname(self, code):
return u'www.wikia.com'
def version(self, code):
return "1.16.2"
def scriptpath(self, code):
return ''
def apipath(self, code):
return '/api.php'
| # -*- coding: utf-8 -*-
__version__ = '$Id$'
import family
# The Wikia Search family
# user-config.py: usernames['wikia']['wikia'] = 'User name'
class Family(family.Family):
def __init__(self):
family.Family.__init__(self)
self.name = u'wikia'
self.langs = {
u'wikia': None,
}
def hostname(self, code):
return u'www.wikia.com'
def version(self, code):
return "1.15.1"
def scriptpath(self, code):
return ''
def apipath(self, code):
return '/api.php'
|
REmove unused imports and fields. | package com.openxc.remote.sources;
import com.openxc.remote.sources.SourceCallback;
/**
* The BaseVehicleDataSource contains functions common to all vehicle data
* sources.
*/
public class BaseVehicleDataSource implements VehicleDataSource {
private SourceCallback mCallback;
public BaseVehicleDataSource() { }
/**
* Construct a new instance and set the callback.
*
* @param callback An object implementing the
* SourceCallback interface that should receive data from this
* source.
*/
public BaseVehicleDataSource(SourceCallback callback) {
setCallback(callback);
}
public void setCallback(SourceCallback callback) {
mCallback = callback;
}
public void stop() {
// do nothing by default
}
protected void handleMessage(String name, Object value) {
handleMessage(name, value, null);
}
protected void handleMessage(String name, Object value, Object event) {
if(mCallback != null) {
mCallback.receive(name, value, event);
}
}
protected SourceCallback getCallback() {
return mCallback;
}
}
| package com.openxc.remote.sources;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.util.Log;
import com.openxc.remote.sources.SourceCallback;
/**
* The BaseVehicleDataSource contains functions common to all vehicle data
* sources.
*/
public class BaseVehicleDataSource implements VehicleDataSource {
private static final String TAG = "BaseVehicleDataSource";
private static final String RECEIVE_METHOD_NAME = "receive";
private SourceCallback mCallback;
public BaseVehicleDataSource() { }
/**
* Construct a new instance and set the callback.
*
* @param callback An object implementing the
* SourceCallback interface that should receive data from this
* source.
*/
public BaseVehicleDataSource(SourceCallback callback) {
setCallback(callback);
}
public void setCallback(SourceCallback callback) {
mCallback = callback;
}
public void stop() {
// do nothing by default
}
protected void handleMessage(String name, Object value) {
handleMessage(name, value, null);
}
protected void handleMessage(String name, Object value, Object event) {
if(mCallback != null) {
mCallback.receive(name, value, event);
}
}
protected SourceCallback getCallback() {
return mCallback;
}
}
|
Change dname of key test | from ev3.ev3dev import Key
import unittest
from util import get_input
class TestKey(unittest.TestCase):
def test_key(self):
d = Key()
get_input('Test keyboard. Hold Up key')
print(d.up)
get_input('Test keyboard. Release Up key')
print(d.up)
get_input('Test keyboard. Hold Down key')
print(d.down)
get_input('Test keyboard. Release Down key')
print(d.down)
get_input('Test keyboard. Hold Left key')
print(d.left)
get_input('Test keyboard. Release Left key')
print(d.left)
get_input('Test keyboard. Hold Right key')
print(d.right)
get_input('Test keyboard. Release Right key')
print(d.right)
get_input('Test keyboard. Hold Backspace key')
print(d.backspace)
get_input('Test keyboard. Release Backspace key')
print(d.backspace)
get_input('Test keyboard. Hold Enter key')
print(d.enter)
get_input('Test keyboard. Release Enter key')
print(d.enter)
if __name__ == '__main__':
unittest.main()
| from ev3.ev3dev import Key
import unittest
from util import get_input
import time
class TestTone(unittest.TestCase):
def test_tone(self):
d = Key()
get_input('Test keyboard. Hold Up key')
print(d.up)
get_input('Test keyboard. Release Up key')
print(d.up)
get_input('Test keyboard. Hold Down key')
print(d.down)
get_input('Test keyboard. Release Down key')
print(d.down)
get_input('Test keyboard. Hold Left key')
print(d.left)
get_input('Test keyboard. Release Left key')
print(d.left)
get_input('Test keyboard. Hold Right key')
print(d.right)
get_input('Test keyboard. Release Right key')
print(d.right)
get_input('Test keyboard. Hold Backspace key')
print(d.backspace)
get_input('Test keyboard. Release Backspace key')
print(d.backspace)
get_input('Test keyboard. Hold Enter key')
print(d.enter)
get_input('Test keyboard. Release Enter key')
print(d.enter)
if __name__ == '__main__':
unittest.main()
|
[Polymer] Change browserSync to use port 4200 | var gulp = require('gulp');
var browserSync = require('browser-sync');
var vulcanize = require('gulp-vulcanize');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
gulp.task('copy', function () {
return gulp.src('./app/index.html', {base: './app/'})
.pipe(gulp.dest('./dist/'));
});
gulp.task('compress', function () {
return gulp.src('./app/bower_components/webcomponentsjs/webcomponents-lite.min.js')
.pipe(uglify({mangle: true}))
.pipe(concat('_polymer.js'))
.pipe(gulp.dest('./dist/'));
});
gulp.task('vulcanize', function () {
return gulp.src('app/elements/my-app.html')
.pipe(vulcanize({
stripComments: true,
inlineCss: true,
inlineScripts: true
}))
.pipe(concat('_polymer.html'))
.pipe(gulp.dest('./dist/'));
});
gulp.task('build', ['copy', 'compress', 'vulcanize']);
gulp.task('serve', ['build'], function () {
browserSync.init({
server: './dist',
port: 4200
});
gulp.watch('app/elements/**/*.html', ['vulcanize']);
gulp.watch('app/index.html', ['copy']);
gulp.watch('dist/*.html').on('change', browserSync.reload);
});
| var gulp = require('gulp');
var browserSync = require('browser-sync');
var vulcanize = require('gulp-vulcanize');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
gulp.task('copy', function () {
return gulp.src('./app/index.html', {base: './app/'})
.pipe(gulp.dest('./dist/'));
});
gulp.task('compress', function () {
return gulp.src('./app/bower_components/webcomponentsjs/webcomponents-lite.min.js')
.pipe(uglify({mangle: true}))
.pipe(concat('_polymer.js'))
.pipe(gulp.dest('./dist/'));
});
gulp.task('vulcanize', function () {
return gulp.src('app/elements/my-app.html')
.pipe(vulcanize({
stripComments: true,
inlineCss: true,
inlineScripts: true
}))
.pipe(concat('_polymer.html'))
.pipe(gulp.dest('./dist/'));
});
gulp.task('build', ['copy', 'compress', 'vulcanize']);
gulp.task('serve', ['build'], function () {
browserSync.init({
server: './dist'
});
gulp.watch('app/elements/**/*.html', ['vulcanize']);
gulp.watch('app/index.html', ['copy']);
gulp.watch('dist/*.html').on('change', browserSync.reload);
});
|
Remove sleep from page retrieval | <?php
class GalleryController extends BaseController {
public $return_data = [
'per_page' => 10
];
public function getIndex()
{
$this->return_data['entries'] = Entry::where('approved', true)->take($this->return_data['per_page'])->get();
return View::make('gallery', $this->return_data);
}
public function getPage($Page)
{
$entries = Entry::where('approved', true)
->skip($this->return_data['per_page'] * $Page)
->take($this->return_data['per_page'])
->get();
$this->return_data['page'] = $Page;
$this->return_data['html'] = '';
foreach($entries as $entry)
{
$this->return_data['html'] = $this->return_data['html'] . View::make('partials.gallery.entry', ['entry' => $entry])->render();
}
return Response::json($this->return_data);
}
}
| <?php
class GalleryController extends BaseController {
public $return_data = [
'per_page' => 10
];
public function getIndex()
{
$this->return_data['entries'] = Entry::where('approved', true)->take($this->return_data['per_page'])->get();
return View::make('gallery', $this->return_data);
}
public function getPage($Page)
{
sleep(25);
$entries = Entry::where('approved', true)
->skip($this->return_data['per_page'] * $Page)
->take($this->return_data['per_page'])
->get();
$this->return_data['page'] = $Page;
$this->return_data['html'] = '';
foreach($entries as $entry)
{
$this->return_data['html'] = $this->return_data['html'] . View::make('partials.gallery.entry', ['entry' => $entry])->render();
}
return Response::json($this->return_data);
}
}
|
Cover more font extensions for CORS from static media
We were missing woff2, but this should just future proof us if more are
added. | """
sentry.web.frontend.generic
~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from django.views.generic import TemplateView as BaseTemplateView
from sentry.web.helpers import render_to_response
def static_media(request, **kwargs):
"""
Serve static files below a given point in the directory structure.
"""
from django.contrib.staticfiles.views import serve
module = kwargs.get('module')
path = kwargs.get('path', '')
version = kwargs.get('version')
if module:
path = '%s/%s' % (module, path)
response = serve(request, path, insecure=True)
# We need CORS for font files
if path.endswith(('.js' '.ttf', '.ttc', '.otf', '.eot', '.woff', '.woff2')):
response['Access-Control-Allow-Origin'] = '*'
# If we have a version, we can cache it FOREVER
if version is not None:
response['Cache-Control'] = 'max-age=315360000'
return response
class TemplateView(BaseTemplateView):
def render_to_response(self, context, **response_kwargs):
return render_to_response(
request=self.request,
template=self.get_template_names(),
context=context,
**response_kwargs
)
| """
sentry.web.frontend.generic
~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from django.views.generic import TemplateView as BaseTemplateView
from sentry.web.helpers import render_to_response
def static_media(request, **kwargs):
"""
Serve static files below a given point in the directory structure.
"""
from django.contrib.staticfiles.views import serve
module = kwargs.get('module')
path = kwargs.get('path', '')
version = kwargs.get('version')
if module:
path = '%s/%s' % (module, path)
response = serve(request, path, insecure=True)
# We need CORS for font files
if path.endswith(('.eot', '.ttf', '.woff', '.js')):
response['Access-Control-Allow-Origin'] = '*'
# If we have a version, we can cache it FOREVER
if version is not None:
response['Cache-Control'] = 'max-age=315360000'
return response
class TemplateView(BaseTemplateView):
def render_to_response(self, context, **response_kwargs):
return render_to_response(
request=self.request,
template=self.get_template_names(),
context=context,
**response_kwargs
)
|
Test: Call loadConfig method in beforeEach so test can check if called | import {Configure} from '../src/configure';
class HttpStub {
get(url) {
}
}
class EventStub {
}
describe('the main configure.js singleton', () => {
var config;
var mockedHttp;
var mockedEvent;
beforeEach(() => {
mockedHttp = new HttpStub();
mockedEvent = new EventStub();
config = new Configure(mockedHttp, mockedEvent);
spyOn(config, 'loadConfig');
config.loadConfig();
});
describe('Basic tests', () => {
it('default directory value should be set', (done) => {
expect(config.directory).toEqual('config');
done();
});
it('default config file value should be set', (done) => {
expect(config.config).toEqual('application.json');
done();
});
it('default config object should be empty', (done) => {
expect(config.obj).toBeDefined();
done();
});
it('loadConfig method should have been called', (done) => {
expect(config.loadConfig).toHaveBeenCalled();
done();
});
});
});
| import {Configure} from '../src/configure';
class HttpStub {
get(url) {
}
}
class EventStub {
}
describe('the main configure.js singleton', () => {
var config;
var mockedHttp;
var mockedEvent;
beforeEach(() => {
mockedHttp = new HttpStub();
mockedEvent = new EventStub();
config = new Configure(mockedHttp, mockedEvent);
spyOn(config, 'loadConfig');
});
describe('Basic tests', () => {
it('default directory value should be set', (done) => {
expect(config.directory).toEqual('config');
done();
});
it('default config file value should be set', (done) => {
expect(config.config).toEqual('application.json');
done();
});
it('default config object should be empty', (done) => {
expect(config.obj).toBeDefined();
done();
});
it('loadConfig method should have been called', (done) => {
expect(config.loadConfig).toHaveBeenCalled();
done();
});
});
});
|
Purge harvestjobs older than retention policy before cleanup | /**
* Delete references to deleted datasets
*/
var updated = 0;
var nbDays = config.HARVEST_JOBS_RETENTION_DAYS;
var minDate = new Date(ISODate().getTime() - 1000 * 60 * 60 * 24 * nbDays);
// Delete jobs older then minDate
var result = db.harvest_job.deleteMany({'created': {'$lt': minDate}});
print(`Deleted ${result.deletedCount} HarvestJobs according to retention policy (${config.HARVEST_JOBS_RETENTION_DAYS} days)`);
// Match all HarvestJob.items.dataset not found in dataset collection
const pipeline = [
{$unwind: '$items'}, // One row by item
{$group: {_id: null, datasetId: {$addToSet: '$items.dataset'}}}, // Distinct Dataset IDs
{$unwind: '$datasetId'}, // One row by ID
{$lookup: {from: 'dataset', localField: 'datasetId', foreignField: '_id', as: 'dataset'}}, // Join
{$match: {'dataset': [] }} // Only keep IDs without match
];
const index = {'items.dataset': 1};
db.harvest_job.createIndex(index);
db.harvest_job.aggregate(pipeline).forEach(row => {
const result = db.harvest_job.update(
{'items.dataset': row.datasetId},
{'$set': {'items.$.dataset': null}},
{multi: true}
);
updated += result.nModified;
});
db.harvest_job.dropIndex(index);
print(`Updated ${updated} HarvestJob.items.dataset broken references.`);
| /**
* Delete references to deleted datasets
*/
var updated = 0;
// Match all HarvestJob.items.dataset not found in dataset collection
const pipeline = [
{$unwind: '$items'}, // One row by item
{$group: {_id: null, datasetId: {$addToSet: '$items.dataset'}}}, // Distinct Dataset IDs
{$unwind: '$datasetId'}, // One row by ID
{$lookup: {from: 'dataset', localField: 'datasetId', foreignField: '_id', as: 'dataset'}}, // Join
{$match: {'dataset': [] }} // Only keep IDs without match
];
const index = {'items.dataset': 1};
db.harvest_job.createIndex(index);
db.harvest_job.aggregate(pipeline).forEach(row => {
const result = db.harvest_job.update(
{'items.dataset': row.datasetId},
{'$set': {'items.$.dataset': null}},
{multi: true}
);
updated += result.nModified;
});
db.harvest_job.dropIndex(index);
print(`Updated ${updated} HarvestJob.items.dataset broken references.`);
|
Add 'npm bin' to uglifyjs command. | #!/usr/bin/env node
var colors = require('colors'),
exec = require('child_process').exec,
pkg = require('../package.json'),
preamble = '/*!\n' +
' * RadioRadio ' + pkg.version + '\n' +
' *\n' +
' * ' + pkg.description + '\n' +
' *\n' +
' * Source code available at: ' + pkg.homepage + '\n' +
' *\n' +
' * (c) 2015-present ' + pkg.author.name + ' (' + pkg.author.url + ')\n' +
' *\n' +
' * RadioRadio may be freely distributed under the ' + pkg.license + ' license.\n' +
' */\n';
exec('$(npm bin)/uglifyjs src/radioradio.js --beautify "indent-level=2" --preamble "' + preamble + '" --output dist/radioradio.js');
exec('$(npm bin)/uglifyjs src/radioradio.js --compress --mangle --preamble "' + preamble + '" --output dist/radioradio.min.js');
console.log(colors.green('RadioRadio %s built successfully!'), pkg.version); | #!/usr/bin/env node
var colors = require('colors'),
exec = require('child_process').exec,
pkg = require('../package.json'),
preamble = '/*!\n' +
' * RadioRadio ' + pkg.version + '\n' +
' *\n' +
' * ' + pkg.description + '\n' +
' *\n' +
' * Source code available at: ' + pkg.homepage + '\n' +
' *\n' +
' * (c) 2015-present ' + pkg.author.name + ' (' + pkg.author.url + ')\n' +
' *\n' +
' * RadioRadio may be freely distributed under the ' + pkg.license + ' license.\n' +
' */\n';
exec('uglifyjs src/radioradio.js --beautify "indent-level=2" --preamble "' + preamble + '" --output dist/radioradio.js');
exec('uglifyjs src/radioradio.js --compress --mangle --preamble "' + preamble + '" --output dist/radioradio.min.js');
console.log(colors.green('RadioRadio %s built successfully!'), pkg.version); |
Change order of initial app render and router activation. | "use strict";
var View = require("./view");
var Router = require("./router");
var util = require("substance-util");
var _ = require("underscore");
// Substance.Application
// ==========================================================================
//
// Application abstraction suggesting strict MVC
var Application = function(config) {
View.call(this);
this.config = config;
};
Application.Prototype = function() {
// Init router
// ----------
this.initRouter = function() {
this.router = new Router();
_.each(this.config.routes, function(route) {
this.router.route(route.route, route.name, _.bind(this.controller[route.command], this.controller));
}, this);
Router.history.start();
};
// Start Application
// ----------
//
this.start = function() {
// First setup the top level view
this.$el = $('body');
this.el = this.$el[0];
this.render();
// Now the normal app lifecycle can begin
// Because app state changes require the main view to be present
// Triggers an initial app state change according to url hash fragment
this.initRouter();
};
};
// Setup prototype chain
Application.Prototype.prototype = View.prototype;
Application.prototype = new Application.Prototype();
module.exports = Application;
| "use strict";
var View = require("./view");
var Router = require("./router");
var util = require("substance-util");
var _ = require("underscore");
// Substance.Application
// ==========================================================================
//
// Application abstraction suggesting strict MVC
var Application = function(config) {
View.call(this);
this.config = config;
};
Application.Prototype = function() {
// Init router
// ----------
this.initRouter = function() {
this.router = new Router();
_.each(this.config.routes, function(route) {
this.router.route(route.route, route.name, _.bind(this.controller[route.command], this.controller));
}, this);
Router.history.start();
};
// Start Application
// ----------
//
this.start = function() {
this.initRouter();
this.$el = $('body');
this.el = this.$el[0];
this.render();
};
};
// Setup prototype chain
Application.Prototype.prototype = View.prototype;
Application.prototype = new Application.Prototype();
module.exports = Application;
|
Fix test to cater for packages leaked into venv | import json
import os
from pathlib import Path
from venv import EnvBuilder
from tests.lib import PipTestEnvironment, TestData
def test_python_interpreter(
script: PipTestEnvironment,
tmpdir: Path,
shared_data: TestData,
) -> None:
env_path = os.fspath(tmpdir / "venv")
env = EnvBuilder(with_pip=False)
env.create(env_path)
result = script.pip("--python", env_path, "list", "--format=json")
before = json.loads(result.stdout)
# Ideally we would assert that before==[], but there's a problem in CI
# that means this isn't true. See https://github.com/pypa/pip/pull/11326
# for details.
script.pip(
"--python",
env_path,
"install",
"-f",
shared_data.find_links,
"--no-index",
"simplewheel==1.0",
)
result = script.pip("--python", env_path, "list", "--format=json")
installed = json.loads(result.stdout)
assert {"name": "simplewheel", "version": "1.0"} in installed
script.pip("--python", env_path, "uninstall", "simplewheel", "--yes")
result = script.pip("--python", env_path, "list", "--format=json")
assert json.loads(result.stdout) == before
| import json
import os
from pathlib import Path
from venv import EnvBuilder
from tests.lib import PipTestEnvironment, TestData
def test_python_interpreter(
script: PipTestEnvironment,
tmpdir: Path,
shared_data: TestData,
) -> None:
env_path = os.fsdecode(tmpdir / "venv")
env = EnvBuilder(with_pip=False)
env.create(env_path)
result = script.pip("--python", env_path, "list", "--format=json")
assert json.loads(result.stdout) == []
script.pip(
"--python",
env_path,
"install",
"-f",
shared_data.find_links,
"--no-index",
"simplewheel==1.0",
)
result = script.pip("--python", env_path, "list", "--format=json")
assert json.loads(result.stdout) == [{"name": "simplewheel", "version": "1.0"}]
script.pip("--python", env_path, "uninstall", "simplewheel", "--yes")
result = script.pip("--python", env_path, "list", "--format=json")
assert json.loads(result.stdout) == []
|
Add variables for easy configiration and customisation. | var upnp = require("peer-upnp");
var http = require("http");
var server = http.createServer();
var PORT = 8080;
var name="IOT-DEVICE";
var model="IoT Device";
var modelUrl="";
var version="1.00";
var serial="12345678";
var address="";
// Start server on port 8080.
server.listen(PORT);
// Create a UPnP Peer.
var peer = upnp.createPeer({
prefix: "/upnp",
server: server
}).on("ready",function(peer){
console.log("ready");
// Advertise device after peer is ready
device.advertise();
}).on("close",function(peer){
console.log("closed");
}).start();
// Create a Basic device.
var device = peer.createDevice({
autoAdvertise: true,
productName: "IoT Reference Platform",
domain: "schemas-upnp-org",
type: "Basic",
version: "1",
friendlyName: name,
manufacturer: "Intel",
manufacturerURL: "http://www.intel.com/content/www/us/en/homepage.html",
modelName: model,
modelDescription: "Intel IoT Device",
modelNumber: version,
modelURL: modelUrl,
serialNumber: serial,
presentationURL: address
});
| var upnp = require("peer-upnp");
var http = require("http");
var server = http.createServer();
var PORT = 8080;
// start server on port 8080.
server.listen(PORT);
// Create a UPnP Peer.
var peer = upnp.createPeer({
prefix: "/upnp",
server: server
}).on("ready",function(peer){
console.log("ready");
// advertise device after peer is ready
device.advertise();
}).on("close",function(peer){
console.log("closed");
}).start();
// Create a Basic device.
var device = peer.createDevice({
autoAdvertise: true,
uuid: "",
productName: "IoT Reference Platform",
productVersion: "1.04",
domain: "schemas-upnp-org",
type: "Basic",
version: "1",
friendlyName: "IOTRP-DEVICE",
manufacturer: "Intel",
manufacturerURL: "http://www.intel.com/content/www/us/en/homepage.html",
modelName: "Edison",
modelDescription: "Intel IoT Device",
modelNumber: "Edison",
modelURL: "",
serialNumber: "",
UPC: ""
});
|
Make http request with a default timeout
If no timeout specified a connection can hang forever | package collector
import (
"fullerite/metric"
"time"
"net/http"
)
type errorHandler func(error)
type responseHandler func(*http.Response) []metric.Metric
type baseHTTPCollector struct {
baseCollector
rspHandler responseHandler
errHandler errorHandler
endpoint string
}
// Collect first queries the config'd endpoint and then passes the results to the handler functions
func (base baseHTTPCollector) Collect() {
base.log.Info("Starting to collect metrics from ", base.endpoint)
metrics := base.makeRequest()
if metrics != nil {
for _, m := range metrics {
base.Channel() <- m
}
base.log.Info("Collected and sent ", len(metrics), " metrics")
} else {
base.log.Info("Sent no metrics because we didn't get any from the response")
}
}
// makeRequest is what is responsible for actually doing the HTTP GET
func (base baseHTTPCollector) makeRequest() []metric.Metric {
if base.endpoint == "" {
base.log.Warn("Ignoring attempt to make request because no endpoint provided")
return []metric.Metric{}
}
client := http.Client{
Timeout: time.Duration(2) * time.Second,
}
rsp, err := client.Get(base.endpoint)
if err != nil {
base.errHandler(err)
return nil
}
return base.rspHandler(rsp)
}
| package collector
import (
"fullerite/metric"
"net/http"
)
type errorHandler func(error)
type responseHandler func(*http.Response) []metric.Metric
type baseHTTPCollector struct {
baseCollector
rspHandler responseHandler
errHandler errorHandler
endpoint string
}
// Collect first queries the config'd endpoint and then passes the results to the handler functions
func (base baseHTTPCollector) Collect() {
base.log.Info("Starting to collect metrics from ", base.endpoint)
metrics := base.makeRequest()
if metrics != nil {
for _, m := range metrics {
base.Channel() <- m
}
base.log.Info("Collected and sent ", len(metrics), " metrics")
} else {
base.log.Info("Sent no metrics because we didn't get any from the response")
}
}
// makeRequest is what is responsible for actually doing the HTTP GET
func (base baseHTTPCollector) makeRequest() []metric.Metric {
if base.endpoint == "" {
base.log.Warn("Ignoring attempt to make request because no endpoint provided")
return []metric.Metric{}
}
rsp, err := http.Get(base.endpoint)
if err != nil {
base.errHandler(err)
return nil
}
return base.rspHandler(rsp)
}
|
Add dot for the list of allowed group names. r=jonasfj
MacOSX indeed has group names with dots. The particular case I found was
com.apple.sharepoint.group.1. | package nativeengine
import schematypes "github.com/taskcluster/go-schematypes"
type config struct {
Groups []string `json:"groups,omitempty"`
}
var configSchema = schematypes.Object{
MetaData: schematypes.MetaData{
Title: "Native Engine Config",
Description: "Configuration for the native engine, this engines creates " +
"a system user-account per task, and deletes user-account when task " +
"is completed.",
},
Properties: schematypes.Properties{
"groups": schematypes.Array{
MetaData: schematypes.MetaData{
Title: "Group Memberships",
Description: "List of system user-groups that the temporary " +
"task-users should be be granted membership of.",
},
Items: schematypes.String{
MetaData: schematypes.MetaData{
Title: "Group Name",
Description: "Name of a user-group that task-users should be assigned",
},
Pattern: "^[a-zA-Z0-9_.-]+$",
},
},
},
Required: []string{},
}
| package nativeengine
import schematypes "github.com/taskcluster/go-schematypes"
type config struct {
Groups []string `json:"groups,omitempty"`
}
var configSchema = schematypes.Object{
MetaData: schematypes.MetaData{
Title: "Native Engine Config",
Description: "Configuration for the native engine, this engines creates " +
"a system user-account per task, and deletes user-account when task " +
"is completed.",
},
Properties: schematypes.Properties{
"groups": schematypes.Array{
MetaData: schematypes.MetaData{
Title: "Group Memberships",
Description: "List of system user-groups that the temporary " +
"task-users should be be granted membership of.",
},
Items: schematypes.String{
MetaData: schematypes.MetaData{
Title: "Group Name",
Description: "Name of a user-group that task-users should be assigned",
},
Pattern: "^[a-zA-Z0-9_-]+$",
},
},
},
Required: []string{},
}
|
Add the required group when creating the token. Clarify the description text.
git-svn-id: d0e296eae3c99886147898d36662a67893ae90b2@4019 653ae4dd-d31e-0410-96ef-6bf7bf53c507 | <?php
class SimplePrivatePosts extends Plugin
{
public function action_plugin_activation()
{
ACL::create_token('private', 'Permission to read posts marked as "private"', 'Private Posts');
// Deny the anonymous group access to the private token, if the group hasn't been removed (why would you remove it ??)
$anon = UserGroup::get('anonymous');
if ( false != $anon ) {
$anon->deny('private');
}
}
public function action_plugin_deactivation( $plugin_file )
{
if ( Plugins::id_from_file(__FILE__) == Plugins::id_from_file($plugin_file) ) {
ACL::destroy_token('private');
}
}
public function action_form_publish($form, $post)
{
if ( $post->content_type == Post::type('entry') ) {
$form->settings->append('checkbox', 'private_post', 'null:null', _t('Private Post'), 'tabcontrol_checkbox');
if ( $post->has_tokens('private') ) {
$form->private_post->value = true;
}
}
}
public function action_publish_post($post, $form)
{
if ( $post->content_type == Post::type('entry') ) {
if ( $form->private_post->value == true ) {
$post->add_tokens('private');
}
else {
$post->remove_tokens('private');
}
}
}
}
?>
| <?php
class SimplePrivatePosts extends Plugin
{
public function action_plugin_activation()
{
ACL::create_token('private', 'Permissions on posts marked as "private"');
// Deny the anonymous group access to the private token, if the group hasn't been removed (why would you remove it ??)
$anon = UserGroup::get('anonymous');
if ( false != $anon ) {
$anon->deny('private');
}
}
public function action_plugin_deactivation( $plugin_file )
{
if ( Plugins::id_from_file(__FILE__) == Plugins::id_from_file($plugin_file) ) {
ACL::destroy_token('private');
}
}
public function action_form_publish($form, $post)
{
if ( $post->content_type == Post::type('entry') ) {
$form->settings->append('checkbox', 'private_post', 'null:null', _t('Private Post'), 'tabcontrol_checkbox');
if ( $post->has_tokens('private') ) {
$form->private_post->value = true;
}
}
}
public function action_publish_post($post, $form)
{
if ( $post->content_type == Post::type('entry') ) {
if ( $form->private_post->value == true ) {
$post->add_tokens('private');
}
else {
$post->remove_tokens('private');
}
}
}
}
?> |
Put the script loading in test in a try/catch because it was causing an error in certain cases with Opera. | var loadScripts = function(js_files, onComplete){
var len = js_files.length;
var head = document.getElementsByTagName('head')[0];
function loadScript(index){
if (index >= len){
onComplete();
return;
}
try {
testOk = js_files[index].test();
} catch (e) {
// with certain browsers like opera the above test can fail
// because of undefined variables...
testOk = true;
}
if (testOk) {
var s = document.createElement('script');
s.src = js_files[index].src;
s.type = 'text/javascript';
head.appendChild(s);
s.onload = function(){
loadScript(index+1);
}
} else {
loadScript(index+1);
}
}
loadScript(0);
}
| var loadScripts = function(js_files, onComplete){
var len = js_files.length;
var head = document.getElementsByTagName('head')[0];
function loadScript(index){
if (index >= len){
onComplete();
return;
}
if (js_files[index].test()){
// console.log('Loading ' + js_files[index].src);
var s = document.createElement('script');
s.src = js_files[index].src;
s.type = 'text/javascript';
head.appendChild(s);
s.onload = function(){
loadScript(index+1);
}
}
else{
loadScript(index+1);
}
}
loadScript(0);
}
|
Fix indention error - thought that was fixed before my last push | import subprocess
def _eintr_retry_call(func, *args):
while True:
try:
return func(*args)
except OSError, e:
if e.errno == errno.EINTR:
continue
raise
def ct_query(filename):
cmd = 'ctags -n -u --fields=+K -f -'
args = cmd.split()
args.append(filename)
proc = subprocess.Popen(args, stdout=subprocess.PIPE)
(out_data, err_data) = _eintr_retry_call(proc.communicate)
out_data = out_data.split('\n')
res = []
for line in out_data:
if (line == ''):
break
line = line.split('\t')
num = line[2].split(';', 1)[0]
line = [line[0], num, line[3]]
res.append(line)
return res
| import subprocess
def _eintr_retry_call(func, *args):
while True:
try:
return func(*args)
except OSError, e:
if e.errno == errno.EINTR:
continue
raise
def ct_query(filename):
cmd = 'ctags -n -u --fields=+K -f -'
args = cmd.split()
args.append(filename)
proc = subprocess.Popen(args, stdout=subprocess.PIPE)
(out_data, err_data) = _eintr_retry_call(proc.communicate)
out_data = out_data.split('\n')
res = []
for line in out_data:
if (line == ''):
break
line = line.split('\t')
num = line[2].split(';', 1)[0]
line = [line[0], num, line[3]]
res.append(line)
return res
|
Raise error upon dataflow cycle detection. | import {error} from 'vega-util';
/**
* Assigns a rank to an operator. Ranks are assigned in increasing order
* by incrementing an internal rank counter.
* @param {Operator} op - The operator to assign a rank.
*/
export function rank(op) {
op.rank = ++this._rank;
}
/**
* Re-ranks an operator and all downstream target dependencies. This
* is necessary when upstream depencies of higher rank are added to
* a target operator.
* @param {Operator} op - The operator to re-rank.
*/
export function rerank(op) {
var queue = [op],
cur, list, i;
while (queue.length) {
this.rank(cur = queue.pop());
if (list = cur._targets) {
for (i=list.length; --i >= 0;) {
queue.push(cur = list[i]);
if (cur === op) error('Cycle detected in dataflow graph.');
}
}
}
}
| /**
* Assigns a rank to an operator. Ranks are assigned in increasing order
* by incrementing an internal rank counter.
* @param {Operator} op - The operator to assign a rank.
*/
export function rank(op) {
op.rank = ++this._rank;
}
/**
* Re-ranks an operator and all downstream target dependencies. This
* is necessary when upstream depencies of higher rank are added to
* a target operator.
* @param {Operator} op - The operator to re-rank.
*/
export function rerank(op) {
var queue = [op],
cur, list, i;
while (queue.length) {
this.rank(cur = queue.pop());
if (list = cur._targets) {
for (i=list.length; --i >= 0;) {
queue.push(cur = list[i]);
if (cur === op) this.error('Cycle detected in dataflow graph.');
}
}
}
}
|
Implement meta by using the bconf package (separate repository). | package index
import (
"bconf"
)
type Index struct {
br *blob_reader
Docs map[uint32][]byte
Attrs map[string][]IbDoc
Meta bconf.Bconf
header string
}
func Open(name string) (*Index, error) {
var in Index
var err error
in.br, err = open_blob_reader(name)
if err != nil {
return nil, err
}
in.Docs = make(map[uint32][]byte)
for _, d := range in.br.get_documents() {
in.Docs[d.Doc.Id] = in.br.get_document_data(&d)
}
in.Attrs = make(map[string][]IbDoc)
for _, a := range in.br.get_invattrs() {
in.Attrs[in.br.get_attr_name(&a)] = in.br.get_attr_docs(&a)
}
in.Meta.LoadJson(in.br.get_meta())
in.Header() // Pre-cache the header to avoid race conditions.
return &in, nil
}
func (in Index) Header() string {
if in.header == "" {
in.Meta.GetNode("attr", "order").ForeachSorted(func(k, v string) {
if in.header != "" {
in.header += "\t"
}
in.header += v
})
}
return in.header
}
func (in Index) Close() {
in.br.close()
}
| package index
type Index struct {
br *blob_reader
Docs map[uint32][]byte
Attrs map[string][]IbDoc
}
func Open(name string) (*Index, error) {
var in Index
var err error
in.br, err = open_blob_reader(name)
if err != nil {
return nil, err
}
in.Docs = make(map[uint32][]byte)
for _, d := range in.br.get_documents() {
in.Docs[d.Doc.Id] = in.br.get_document_data(&d)
}
in.Attrs = make(map[string][]IbDoc)
for _, a := range in.br.get_invattrs() {
in.Attrs[in.br.get_attr_name(&a)] = in.br.get_attr_docs(&a)
}
return &in, nil
}
func (in *Index) Close() {
in.br.close()
}
|
Change permissions for user search | <?php
namespace App\Policies;
use App\User;
use App\APIUser;
use Illuminate\Auth\Access\HandlesAuthorization;
use Illuminate\Http\Request;
class APIUserPolicy
{
use HandlesAuthorization;
public function view_in_admin(User $user) {
if ($user->site_admin) {
return true;
}
}
// Policy used for search -- available to all users.
public function get_all(User $user)
{
return true;
}
public function get(User $user, APIUser $api_user)
{
if ($user->site_admin) {
return true;
}
}
public function create(User $user)
{
if ($user->site_admin) {
return true;
}
}
public function update(User $user, APIUser $api_user)
{
if ($user->site_admin) {
return true;
}
}
public function delete(User $user, APIUser $api_user)
{
if ($user->site_admin) {
return true;
}
}
}
| <?php
namespace App\Policies;
use App\User;
use App\APIUser;
use Illuminate\Auth\Access\HandlesAuthorization;
use Illuminate\Http\Request;
class APIUserPolicy
{
use HandlesAuthorization;
public function view_in_admin(User $user) {
if ($user->site_admin) {
return true;
}
}
public function get_all(User $user)
{
if ($user->site_admin) {
return true;
}
}
public function get(User $user, APIUser $api_user)
{
if ($user->site_admin) {
return true;
}
}
public function create(User $user)
{
if ($user->site_admin) {
return true;
}
}
public function update(User $user, APIUser $api_user)
{
if ($user->site_admin) {
return true;
}
}
public function delete(User $user, APIUser $api_user)
{
if ($user->site_admin) {
return true;
}
}
}
|
Print number of terms loaded to Airtable. | import fire
import json
import sys
from source import VocabularyCom
from airtable import Airtable
class CLI:
class source:
"""Import word lists from various sources"""
def vocabulary_com(self, list_url, pretty=False):
result = VocabularyCom().collect(list_url)
if pretty:
print json.dumps(result, indent=4, sort_keys=True)
else:
json.dump(result, sys.stdout)
class airtable:
"""Sync lists to Airtable"""
def load(self, list_url, endpoint, key):
words = VocabularyCom().collect(list_url)
self._load(words, endpoint, key)
def load_from_stdin(self, endpoint, key):
words = json.load(sys.stdin)
self._load(words, endpoint, key)
def _load(self, words, endpoint, key):
airtable = Airtable(endpoint, key)
airtable.load(words)
print 'Loaded %d terms to Airtable.' % len(words)
if __name__ == '__main__':
fire.Fire(CLI)
| import fire
import json
import sys
from source import VocabularyCom
from airtable import Airtable
class CLI:
class source:
"""Import word lists from various sources"""
def vocabulary_com(self, list_url, pretty=False):
result = VocabularyCom().collect(list_url)
if pretty:
print json.dumps(result, indent=4, sort_keys=True)
else:
json.dump(result, sys.stdout)
class airtable:
"""Sync lists to Airtable"""
def load(self, list_url, endpoint, key):
airtable = Airtable(endpoint, key)
words = VocabularyCom().collect(list_url)
airtable.load(words)
print 'List loaded to Airtable.'
def load_from_stdin(self, endpoint, key):
words = json.load(sys.stdin)
airtable = Airtable(endpoint, key)
airtable.load(words)
print 'List loaded to Airtable.'
if __name__ == '__main__':
fire.Fire(CLI)
|
Remove the param to filter inactive advisers | const { get } = require('lodash')
const config = require('../../../config')
const { authorisedRequest } = require('../../lib/authorised-request')
function getAdvisers (token) {
return authorisedRequest(token, `${config.apiRoot}/adviser/?limit=100000&offset=0`)
.then(response => {
const results = response.results.filter(adviser => get(adviser, 'name', '').trim().length)
return {
results,
count: results.length,
}
})
}
function getAdviser (token, id) {
return authorisedRequest(token, `${config.apiRoot}/adviser/${id}/`)
}
async function fetchAdviserSearchResults (token, params) {
const url = `${config.apiRoot}/adviser/?autocomplete=${params.term}`
const adviserResults = await authorisedRequest(token, { url })
return adviserResults.results
}
module.exports = {
getAdvisers,
getAdviser,
fetchAdviserSearchResults,
}
| const { get } = require('lodash')
const config = require('../../../config')
const { authorisedRequest } = require('../../lib/authorised-request')
function getAdvisers (token) {
return authorisedRequest(token, `${config.apiRoot}/adviser/?limit=100000&offset=0`)
.then(response => {
const results = response.results.filter(adviser => get(adviser, 'name', '').trim().length)
return {
results,
count: results.length,
}
})
}
function getAdviser (token, id) {
return authorisedRequest(token, `${config.apiRoot}/adviser/${id}/`)
}
async function fetchAdviserSearchResults (token, params) {
const url = `${config.apiRoot}/adviser/?autocomplete=${params.term}&is_active=${params.is_active}`
const adviserResults = await authorisedRequest(token, { url })
return adviserResults.results
}
module.exports = {
getAdvisers,
getAdviser,
fetchAdviserSearchResults,
}
|
Test content type for JSON API | import json
from unittest import TestCase
from usb import create_application
from usb.models import db
class APITestCase(TestCase):
def setUp(self):
self.app = create_application('config/test.py')
self.client = self.app.test_client()
db.app = self.app
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
def test_redirect_from_index_namespace(self):
pass
def test_redirect_from_links_namespace(self):
pass
def test_create_short_link(self):
pass
def test_update_short_link(self):
pass
def test_get_list_of_short_links(self):
pass
def test_get_list_of_short_links_empty_db(self):
response = self.client.get('/links')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.headers['Content-Type'], 'application/json')
data = json.loads(response.data)
self.assertEqual(data, {})
| import json
from unittest import TestCase
from usb import create_application
from usb.models import db
class APITestCase(TestCase):
def setUp(self):
self.app = create_application('config/test.py')
self.client = self.app.test_client()
db.app = self.app
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
def test_redirect_from_index_namespace(self):
pass
def test_redirect_from_links_namespace(self):
pass
def test_create_short_link(self):
pass
def test_update_short_link(self):
pass
def test_get_list_of_short_links(self):
pass
def test_get_list_of_short_links_empty_db(self):
response = self.client.get('/links')
self.assertEqual(response.status_code, 200)
data = json.loads(response.data)
self.assertEqual(data, {})
|
Fix method signature and wrong class import | <?php
/**
* This file is part of prooph/proophessor-do.
* (c) 2014-2016 prooph software GmbH <contact@prooph.de>
* (c) 2015-2016 Sascha-Oliver Prolic <saschaprolic@googlemail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Prooph\ProophessorDo\Response;
use Prooph\Psr7Middleware\Response\ResponseStrategy;
use Psr\Http\Message\ResponseInterface;
use React\Promise\Promise;
use Zend\Diactoros\Response\JsonResponse as ZendJsonResponse;
final class JsonResponse implements ResponseStrategy
{
public function fromPromise(Promise $promise): ResponseInterface
{
$json = null;
$promise->done(function ($data) use (&$json) {
$json = $data;
});
return new ZendJsonResponse($json);
}
}
| <?php
/**
* This file is part of prooph/proophessor-do.
* (c) 2014-2016 prooph software GmbH <contact@prooph.de>
* (c) 2015-2016 Sascha-Oliver Prolic <saschaprolic@googlemail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Prooph\ProophessorDo\Response;
use Prooph\Psr7Middleware\Response\ResponseStrategy;
use React\Promise\Promise;
final class JsonResponse implements ResponseStrategy
{
public function fromPromise(Promise $promise)
{
$json = null;
$promise->done(function ($data) use (&$json) {
$json = $data;
});
return new JsonResponse($json);
}
}
|
Allow func validation to throw custom errors | <?php
/*
* Copyright 2019 Jack Sleight <http://jacksleight.com/>
* This source file is subject to the MIT license that is bundled with this package in the file LICENCE.
*/
namespace Coast\Validator\Rule;
use Coast\Validator\Rule;
class Func extends Rule
{
protected $_func;
public function __construct(callable $func, $name = null)
{
$this->func($func);
$this->name($name);
}
public function func($func = null)
{
if (func_num_args() > 0) {
if ($func instanceof \Closure) {
$func = $func->bindTo($this);
}
$this->_func = $func;
return $this;
}
return $this->_func;
}
protected function _validate($value, $context = null)
{
if (call_user_func($this->_func, $value, $context) === false) {
$this->error();
}
}
}
| <?php
/*
* Copyright 2019 Jack Sleight <http://jacksleight.com/>
* This source file is subject to the MIT license that is bundled with this package in the file LICENCE.
*/
namespace Coast\Validator\Rule;
use Coast\Validator\Rule;
class Func extends Rule
{
protected $_func;
public function __construct(callable $func, $name = null)
{
$this->func($func);
$this->name($name);
}
public function func($func = null)
{
if (func_num_args() > 0) {
$this->_func = $func;
return $this;
}
return $this->_func;
}
protected function _validate($value, $context = null)
{
if (!call_user_func($this->_func, $value, $context)) {
$this->error();
}
}
}
|
Fix first time execution of sample:data command test. | <?php
/**
* This file is part of The OBMS project: https://github.com/obms/obms
*
* Copyright (c) Jaime Niñoles-Manzanera Jimeno.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace AdministrationBundle\Tests;
/**
* Clase que prueba un comando de consola.
* Utiliza CommandTestCase para crear una Symfony app y tener todo disponible para ejecutar el/los
* comandos..
*/
class CommandsTest extends CommandTestCase
{
public function setUp()
{
exec('php app/console doctrine:fixtures:load --no-interaction --env=test');
}
public function testDefaultDoesNotInstall()
{
$client = self::createClient();
$output = $this->runCommand($client, 'sample:data');
$this->assertContains('Deleting sample data.. loading data.. ok', $output);
}
}
| <?php
/**
* This file is part of The OBMS project: https://github.com/obms/obms
*
* Copyright (c) Jaime Niñoles-Manzanera Jimeno.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace AdministrationBundle\Tests;
/**
* Clase que prueba un comando de consola.
* Utiliza CommandTestCase para crear una Symfony app y tener todo disponible para ejecutar el/los
* comandos..
*/
class CommandsTest extends CommandTestCase
{
public function testDefaultDoesNotInstall()
{
$client = self::createClient();
$output = $this->runCommand($client, 'sample:data');
$this->assertContains('Deleting sample data.. loading data.. ok', $output);
}
}
|
Use the utility module's extract_publication_date logic. | """Populate the `publication_date` column.
Revision ID: 17c1af634026
Revises: 3c4c29f0a791
Create Date: 2012-12-13 21:03:03.445346
"""
# revision identifiers, used by Alembic.
revision = '17c1af634026'
down_revision = '3c4c29f0a791'
import html5lib
from dateutil.parser import parse as parse_date
import pytips
from pytips.util import extract_publication_date
from pytips.models import Tip
def _update_tip(tip):
tip.publication_date = extract_publication_date(tip.rendered_html)
def _erase_publication_date(tip):
tip.publication_date = None
def upgrade():
tips = Tip.query.all()
map(_update_tip, tips)
pytips.db.session.commit()
def downgrade():
tips = Tip.query.all()
map(_erase_publication_date, tips)
pytips.db.session.commit()
| """Populate the `publication_date` column.
Revision ID: 17c1af634026
Revises: 3c4c29f0a791
Create Date: 2012-12-13 21:03:03.445346
"""
# revision identifiers, used by Alembic.
revision = '17c1af634026'
down_revision = '3c4c29f0a791'
import html5lib
from dateutil.parser import parse as parse_date
import pytips
from pytips.models import Tip
def _extract_publication_date(html):
root = html5lib.parse(html, treebuilder='lxml', namespaceHTMLElements=False)
publication_date_string = root.xpath("//a/@data-datetime")[0]
return parse_date(publication_date_string)
def _update_tip(tip):
tip.publication_date = _extract_publication_date(tip.rendered_html)
def _erase_publication_date(tip):
tip.publication_date = None
def upgrade():
tips = Tip.query.all()
map(_update_tip, tips)
pytips.db.session.commit()
def downgrade():
tips = Tip.query.all()
map(_erase_publication_date, tips)
pytips.db.session.commit()
|
Switch to ruamel_yaml from conda by default | import sys
from setuptools import setup
# See https://stackoverflow.com/questions/19534896/enforcing-python-version-in-setup-py
if sys.version_info < (3,6):
sys.exit("Sorry, Python < 3.6 is not supported by Auspex.")
setup(
name='auspex',
version='0.1',
author='auspex Developers',
package_dir={'':'src'},
packages=[
'auspex', 'auspex.instruments', 'auspex.filters', 'auspex.analysis'
],
scripts=[],
description='Automated system for python-based experiments.',
long_description=open('README.md').read(),
install_requires=[
"numpy >= 1.11.1",
"scipy >= 0.17.1",
"PyVISA >= 1.8",
"h5py >= 2.6.0",
"tqdm >= 4.7.0",
"pandas >= 0.18.1",
"networkx >= 1.11",
"matplotlib >= 2.0.0",
"ruamel_yaml >= 0.11.14",
"psutil >= 5.0.0",
"pyzmq >= 16.0.0"
]
)
| import sys
from setuptools import setup
# See https://stackoverflow.com/questions/19534896/enforcing-python-version-in-setup-py
if sys.version_info < (3,6):
sys.exit("Sorry, Python < 3.6 is not supported by Auspex.")
setup(
name='auspex',
version='0.1',
author='auspex Developers',
package_dir={'':'src'},
packages=[
'auspex', 'auspex.instruments', 'auspex.filters', 'auspex.analysis'
],
scripts=[],
description='Automated system for python-based experiments.',
long_description=open('README.md').read(),
install_requires=[
"numpy >= 1.11.1",
"scipy >= 0.17.1",
"PyVISA >= 1.8",
"h5py >= 2.6.0",
"tqdm >= 4.7.0",
"pandas >= 0.18.1",
"networkx >= 1.11",
"matplotlib >= 2.0.0",
"ruamel.yaml >= 0.15.18",
"psutil >= 5.0.0",
"pyzmq >= 16.0.0"
]
)
|
Fix bug that meant rendering debug info was v slow. | import copy
from ckan.plugins import toolkit as tk
def qa_openness_stars_resource_html(resource):
qa = resource.get('qa')
if not qa:
return '<!-- No qa info for this resource -->'
# Take a copy of the qa dict, because weirdly the renderer appears to add
# keys to it like _ and app_globals. This is bad because when it comes to
# render the debug in the footer those extra keys take about 30s to render,
# for some reason.
extra_vars = copy.deepcopy(qa)
return tk.literal(
tk.render('qa/openness_stars.html',
extra_vars=extra_vars))
def qa_openness_stars_dataset_html(dataset):
qa = dataset.get('qa')
if not qa:
return '<!-- No qa info for this dataset -->'
extra_vars = copy.deepcopy(qa)
return tk.literal(
tk.render('qa/openness_stars_brief.html',
extra_vars=extra_vars))
| from ckan.plugins import toolkit as tk
def qa_openness_stars_resource_html(resource):
qa = resource.get('qa')
if not qa:
return '<!-- No qa info for this resource -->'
extra_vars = qa
return tk.literal(
tk.render('qa/openness_stars.html',
extra_vars=extra_vars))
def qa_openness_stars_dataset_html(dataset):
qa = dataset.get('qa')
if not qa:
return '<!-- No qa info for this dataset -->'
extra_vars = qa
return tk.literal(
tk.render('qa/openness_stars_brief.html',
extra_vars=extra_vars))
|
Fix reordering due to removal of Other | '''
James D. Zoll
4/15/2013
Purpose: Defines template tags for the Leapday Recipedia application.
License: This is a public work.
'''
from django import template
register = template.Library()
@register.filter()
def good_css_name(value):
'''
Returns the lower-case hyphen-replaced display name,
which used as the css class for the good.
Keyword Arguments:
value -> Good. The good to get the css class for.
'''
return value.display_name.lower().replace(' ','-')
@register.filter()
def base_goods_ordered_set(value):
'''
Returns a set of the base goods required for an object's creation,
ordered by the desired order. In this case, that order is value low
to high, with the "Other" good on the end instead of the front.
Additionally, this attempts first to load goods from the
shim_base_ingredients attribute, which is present in some situations
where the attribute has been preloaded to prevent excessive DB IO.
Keyword Arguments:
value -> Good. The good for which to return the list of ingredients.
'''
try:
base_goods = value.shim_base_ingredients
except:
base_goods = value.base_ingredients.all()
ret = sorted(base_goods, key=lambda x: x.ingredient.value)
return ret
| '''
James D. Zoll
4/15/2013
Purpose: Defines template tags for the Leapday Recipedia application.
License: This is a public work.
'''
from django import template
register = template.Library()
@register.filter()
def good_css_name(value):
'''
Returns the lower-case hyphen-replaced display name,
which used as the css class for the good.
Keyword Arguments:
value -> Good. The good to get the css class for.
'''
return value.display_name.lower().replace(' ','-')
@register.filter()
def base_goods_ordered_set(value):
'''
Returns a set of the base goods required for an object's creation,
ordered by the desired order. In this case, that order is value low
to high, with the "Other" good on the end instead of the front.
Additionally, this attempts first to load goods from the
shim_base_ingredients attribute, which is present in some situations
where the attribute has been preloaded to prevent excessive DB IO.
Keyword Arguments:
value -> Good. The good for which to return the list of ingredients.
'''
try:
base_goods = value.shim_base_ingredients
except:
base_goods = value.base_ingredients.all()
ret = sorted(base_goods, key=lambda x: x.ingredient.value)
ret = ret[1:] + [ret[0]]
return ret
|
[Pool] Allow retrieval of a model manager with only a class name rather than a class instance | <?php
namespace HCLabs\ModelManagerBundle\Pool;
use HCLabs\ModelManagerBundle\Exception\ModelManagerNotFoundException;
use HCLabs\ModelManagerBundle\Model\Contract\ModelInterface;
use HCLabs\ModelManagerBundle\Model\Contract\ModelManagerInterface;
class ModelManagerPool
{
/** @var ModelManagerInterface[] */
protected $managers = [];
/**
* Add a model manager to the pool
*
* @param ModelManagerInterface $manager
*/
public function addManager(ModelManagerInterface $manager)
{
$this->managers[] = $manager;
}
/**
* Get manager for an entity out of the pool
*
* @param ModelInterface|string $model
* @return ModelManagerInterface
* @throws \HCLabs\ModelManagerBundle\Exception\ModelManagerNotFoundException
* @throws \RuntimeException
*/
public function getManager($model)
{
if (!is_string($model) && !$model instanceof ModelInterface) {
throw new \RuntimeException(sprintf('Model provided (\'%s\') is neither a string nor an instance of ModelInterface', $model));
}
foreach ($this->managers as $manager) {
if ($manager->supports($model)) {
return $manager;
}
}
throw new ModelManagerNotFoundException($model);
}
} | <?php
namespace HCLabs\ModelManagerBundle\Pool;
use HCLabs\ModelManagerBundle\Exception\ModelManagerNotFoundException;
use HCLabs\ModelManagerBundle\Model\Contract\ModelInterface;
use HCLabs\ModelManagerBundle\Model\Contract\ModelManagerInterface;
class ModelManagerPool
{
/** @var ModelManagerInterface[] */
protected $managers = [];
/**
* Add a model manager to the pool
*
* @param ModelManagerInterface $manager
*/
public function addManager(ModelManagerInterface $manager)
{
$this->managers[] = $manager;
}
/**
* Get manager for an entity out of the pool
*
* @param ModelInterface $model
* @return ModelManagerInterface
* @throws \HCLabs\ModelManagerBundle\Exception\ModelManagerNotFoundException
*/
public function getManager(ModelInterface $model)
{
foreach ($this->managers as $manager) {
if ($manager->supports($model)) {
return $manager;
}
}
throw new ModelManagerNotFoundException($model);
}
} |
Fix db_downgrade for "System editable object state" |
"""System editable object state
Revision ID: 5254f4f31427
Revises: 512c71e4d93b
Create Date: 2015-02-05 02:05:09.351265
"""
# revision identifiers, used by Alembic.
revision = '5254f4f31427'
down_revision = '512c71e4d93b'
import sqlalchemy as sa
from sqlalchemy.sql import table, column
from alembic import op
from ggrc.models.track_object_state import ObjectStates, ObjectStateTables
def upgrade():
for table_name in ObjectStateTables.table_names:
op.add_column(table_name, sa.Column('os_state', sa.String(length=16), nullable=True))
# Set the value into all existing records
object_table = table(table_name,
column('os_state', sa.String(length=16)))
connection = op.get_bind()
connection.execute(
object_table.update().values(
{
'os_state': ObjectStates.DRAFT
}
)
)
# Make the field not-nullable
op.alter_column(table_name, 'os_state',existing_type=sa.String(length=16),nullable=False)
def downgrade():
for table_name in ObjectStateTables.table_names:
op.drop_column(table_name, 'os_state')
|
"""System editable object state
Revision ID: 5254f4f31427
Revises: 512c71e4d93b
Create Date: 2015-02-05 02:05:09.351265
"""
# revision identifiers, used by Alembic.
revision = '5254f4f31427'
down_revision = '512c71e4d93b'
import sqlalchemy as sa
from sqlalchemy.sql import table, column
from alembic import op
from ggrc.models.track_object_state import ObjectStates, ObjectStateTables
def upgrade():
for table_name in ObjectStateTables.table_names:
op.add_column(table_name, sa.Column('os_state', sa.String(length=16), nullable=True))
# Set the value into all existing records
object_table = table(table_name,
column('os_state', sa.String(length=16)))
connection = op.get_bind()
connection.execute(
object_table.update().values(
{
'os_state': ObjectStates.DRAFT
}
)
)
# Make the field not-nullable
op.alter_column(table_name, 'os_state',existing_type=sa.String(length=16),nullable=False)
def downgrade():
for table_name in ObjectStateTables:
op.drop_column(table_name, 'os_state')
|
Fix get_pypi_packages for new requirements-parser | """Core pep438 utility functions"""
from __future__ import unicode_literals
import requests
try:
import xmlrpclib
except:
import xmlrpc.client as xmlrpclib # noqa
from xml.etree import ElementTree
from requirements import parse
def valid_package(package_name):
"""Return bool if package_name is a valid package on PyPI"""
response = requests.head('https://pypi.python.org/pypi/%s' % package_name)
if response.status_code != 404:
response.raise_for_status()
return response.status_code != 404
def get_urls(package_name):
"""Return list of URLs on package's PyPI page that would be crawled"""
response = requests.get('https://pypi.python.org/simple/%s' % package_name)
response.raise_for_status()
page = ElementTree.fromstring(response.content)
crawled_urls = {link.get('href') for link in page.findall('.//a')
if link.get('rel') in ("homepage", "download")}
return crawled_urls
def get_pypi_packages(fileobj):
"""Return all PyPI-hosted packages from file-like object"""
return [p['name'] for p in parse(fileobj) if not p['uri']]
def get_pypi_user_packages(user):
client = xmlrpclib.ServerProxy('https://pypi.python.org/pypi')
return [x[1] for x in client.user_packages(user)]
| """Core pep438 utility functions"""
from __future__ import unicode_literals
import requests
try:
import xmlrpclib
except:
import xmlrpc.client as xmlrpclib # noqa
from xml.etree import ElementTree
from requirements import parse
def valid_package(package_name):
"""Return bool if package_name is a valid package on PyPI"""
response = requests.head('https://pypi.python.org/pypi/%s' % package_name)
if response.status_code != 404:
response.raise_for_status()
return response.status_code != 404
def get_urls(package_name):
"""Return list of URLs on package's PyPI page that would be crawled"""
response = requests.get('https://pypi.python.org/simple/%s' % package_name)
response.raise_for_status()
page = ElementTree.fromstring(response.content)
crawled_urls = {link.get('href') for link in page.findall('.//a')
if link.get('rel') in ("homepage", "download")}
return crawled_urls
def get_pypi_packages(fileobj):
"""Return all PyPI-hosted packages from file-like object"""
return [p['name'] for p in parse(fileobj) if not p.get('uri')]
def get_pypi_user_packages(user):
client = xmlrpclib.ServerProxy('https://pypi.python.org/pypi')
return [x[1] for x in client.user_packages(user)]
|
Remove an extra anonymous function | var expect = require('expect.js');
var seeds = require('../seeds');
var Feature = require('../feature');
describe('Feature', function () {
before(seeds);
describe('schema', function () {
it('successfully creates a valid document');
it('fails at creating an invalid document');
});
describe('.search()', function () {
it('performs an empty search, returning all commands', function (done) {
Feature.search('', function (docs) {
expect(docs.length).to.be(7);
done();
});
});
it('performs a case-insensitive search for a command', function (done) {
Feature.search('git ADD', function (docs) {
expect(docs).to.eql([{
name: 'add files',
examples: [
{ technology: 'Git', snippets: ['git add'] },
{ technology: 'Mercurial', snippets: ['hg add'] },
{ technology: 'Subversion', snippets: ['svn add'] }
]
}]);
done();
});
});
it('discards extra hidden fields created by MongoDB');
it('performs a search for a command that does not exist', function (done) {
Feature.search('git yolo', function (docs) {
expect(docs.length).to.be(0);
done();
});
});
});
});
| var expect = require('expect.js');
var seeds = require('../seeds');
var Feature = require('../feature');
describe('Feature', function () {
before(function (done) {
seeds(done);
});
describe('schema', function () {
it('successfully creates a valid document');
it('fails at creating an invalid document');
});
describe('.search()', function () {
it('performs an empty search, returning all commands', function (done) {
Feature.search('', function (docs) {
expect(docs.length).to.be(7);
done();
});
});
it('performs a case-insensitive search for a command', function (done) {
Feature.search('git ADD', function (docs) {
expect(docs).to.eql([{
name: 'add files',
examples: [
{ technology: 'Git', snippets: ['git add'] },
{ technology: 'Mercurial', snippets: ['hg add'] },
{ technology: 'Subversion', snippets: ['svn add'] }
]
}]);
done();
});
});
it('discards extra hidden fields created by MongoDB');
it('performs a search for a command that does not exist', function (done) {
Feature.search('git yolo', function (docs) {
expect(docs.length).to.be(0);
done();
});
});
});
});
|
Update to handle users with no final grade | '''
This module will retrieve info about students registered in the course
Usage:
python user_info.py
'''
from base_edx import EdXConnection
from generate_csv_report import CSV
connection = EdXConnection('certificates_generatedcertificate', 'auth_userprofile')
collection = connection.get_access_to_collection()
documents = collection['auth_userprofile'].find()
result = []
for document in documents:
user_id = document['user_id']
try:
final_grade = collection['certificates_generatedcertificate'].find_one({'user_id' : user_id})['grade']
result.append([user_id, document['name'], final_grade, document['gender'], document['year_of_birth'], document['level_of_education'], document['country'], document['city']])
except:
# Handle users with no grades
pass
output = CSV(result, ['User ID','Username', 'Final Grade', 'Gender', 'Year of Birth', 'Level of Education', 'Country', 'City'], output_file='atoc185x_user_info.csv')
output.generate_csv()
| '''
This module will retrieve info about students registered in the course
Usage:
python user_info.py
'''
from collections import defaultdict
from base_edx import EdXConnection
from generate_csv_report import CSV
connection = EdXConnection('certificates_generatedcertificate', 'auth_userprofile')
collection = connection.get_access_to_collection()
documents = collection['auth_userprofile'].find()
result = []
for document in documents:
user_id = document['user_id']
try:
final_grade = collection['certificates_generatedcertificate'].find_one({'user_id' : user_id})['grade']
result.append([user_id, document['name'], final_grade, document['gender'], document['year_of_birth'], document['level_of_education'], document['country'], document['city']])
except:
# Handle users with no grades
pass
output = CSV(result, ['User ID','Username', 'Final Grade', 'Gender', 'Year of Birth', 'Level of Education', 'Country', 'City'], output_file='atoc185x_user_info.csv')
output.generate_csv()
|
Fix load of compiled lz4 module | import sys
import os
p1, p2 = sys.version_info[:2]
curpath = os.path.abspath( sys.argv[0] )
if os.path.islink(curpath):
curpath = os.readlink(curpath)
currentdir = os.path.dirname( curpath )
build_dir = os.path.abspath( os.path.join(currentdir, "lib-dynload", "lz4", "build") )
if not os.path.isdir(build_dir):
build_dir = os.path.abspath( os.path.join(currentdir, "..", "lib-dynload", "lz4", "build") )
if not os.path.isdir(build_dir):
build_dir = os.path.abspath( os.path.join(currentdir, "..", "..", "lib-dynload", "lz4", "build") )
dirs = os.listdir(build_dir)
for d in dirs:
if d.find("-%s.%s" % (p1, p2)) != -1 and d.find("lib.") != -1:
sys.path.insert(0, os.path.join(build_dir, d, "_lz4", "block") )
import importlib
module = importlib.import_module("_block")
compress = module.compress
decompress = module.decompress
sys.path.pop(0)
break
| import sys
import os
p1, p2 = sys.version_info[:2]
curpath = os.path.abspath( sys.argv[0] )
if os.path.islink(curpath):
curpath = os.readlink(curpath)
currentdir = os.path.dirname( curpath )
build_dir = os.path.abspath( os.path.join(currentdir, "lib-dynload", "lz4", "build") )
if not os.path.isdir(build_dir):
build_dir = os.path.abspath( os.path.join(currentdir, "..", "lib-dynload", "lz4", "build") )
if not os.path.isdir(build_dir):
build_dir = os.path.abspath( os.path.join(currentdir, "..", "..", "lib-dynload", "lz4", "build") )
dirs = os.listdir(build_dir)
for d in dirs:
if d.find("-%s.%s" % (p1, p2)) != -1 and d.find("lib.") != -1:
sys.path.insert(0, os.path.join(build_dir, d) )
import importlib
module = importlib.import_module("_lz4.block._block")
compress = module.compress
decompress = module.decompress
sys.path.pop(0)
break
|
Call 'lower()' on the input | """
instabot example
Whitelist generator: generates a list of users which
will not be unfollowed.
"""
import sys
import os
import random
sys.path.append(os.path.join(sys.path[0], '../../'))
from instabot import Bot
bot = Bot()
bot.login()
print("This script will generate whitelist.txt file with users"
"who will not be unfollowed by bot. "
"Press Y to add user to whitelist. Ctrl + C to exit.")
your_following = bot.following
already_whitelisted = bot.read_list_from_file("whitelist.txt")
rest_users = list(set(your_following) - set(already_whitelisted))
random.shuffle(rest_users)
with open("whitelist.txt", "a") as f:
for user_id in rest_users:
user_info = bot.get_user_info(user_id)
print(user_info["username"])
print(user_info["full_name"])
input_line = sys.stdin.readline().lower()
if "y" in input_line.lower():
f.write(str(user_id) + "\n")
print("ADDED.\r")
| """
instabot example
Whitelist generator: generates a list of users which
will not be unfollowed.
"""
import sys
import os
import random
sys.path.append(os.path.join(sys.path[0], '../../'))
from instabot import Bot
bot = Bot()
bot.login()
print("This script will generate whitelist.txt file with users"
"who will not be unfollowed by bot. "
"Press Y to add user to whitelist. Ctrl + C to exit.")
your_following = bot.following
already_whitelisted = bot.read_list_from_file("whitelist.txt")
rest_users = list(set(your_following) - set(already_whitelisted))
random.shuffle(rest_users)
with open("whitelist.txt", "a") as f:
for user_id in rest_users:
user_info = bot.get_user_info(user_id)
print(user_info["username"])
print(user_info["full_name"])
input_line = sys.stdin.readline().lower()
if "y" in input_line:
f.write(str(user_id) + "\n")
print("ADDED.\r")
|
Remove redundant import of tkinter. | from test import support
# Skip test if _tkinter wasn't built.
support.import_module('_tkinter')
import tkinter
from tkinter.test import runtktests
import unittest
try:
tkinter.Button()
except tkinter.TclError as msg:
# assuming tk is not available
raise unittest.SkipTest("tk not available: %s" % msg)
def test_main(enable_gui=False):
if enable_gui:
if support.use_resources is None:
support.use_resources = ['gui']
elif 'gui' not in support.use_resources:
support.use_resources.append('gui')
support.run_unittest(
*runtktests.get_tests(text=False, packages=['test_tkinter']))
if __name__ == '__main__':
test_main(enable_gui=True)
| from test import support
# Skip test if _tkinter wasn't built.
support.import_module('_tkinter')
import tkinter
from tkinter.test import runtktests
import unittest
import tkinter
try:
tkinter.Button()
except tkinter.TclError as msg:
# assuming tk is not available
raise unittest.SkipTest("tk not available: %s" % msg)
def test_main(enable_gui=False):
if enable_gui:
if support.use_resources is None:
support.use_resources = ['gui']
elif 'gui' not in support.use_resources:
support.use_resources.append('gui')
support.run_unittest(
*runtktests.get_tests(text=False, packages=['test_tkinter']))
if __name__ == '__main__':
test_main(enable_gui=True)
|
Set API to Heroku address. | angular
.module('zibble', ['angular-jwt', 'ngResource', 'ui.router'])
.constant('API', 'https://zibble-back-end.herokuapp.com')
.config(function($httpProvider){
$httpProvider.interceptors.push('AuthInterceptor');
})
.config(MainRouter);
function MainRouter($stateProvider, $urlRouterProvider, $locationProvider){
$stateProvider
.state('home', {
url : '/',
templateUrl : './views/home.html'
});
$stateProvider
.state('login', {
url : '/login',
templateUrl : './views/login.html'
});
$stateProvider
.state('signup', {
url : '/signup',
templateUrl : './views/signup.html'
});
$stateProvider
.state('logout', {
url : '/logout',
templateUrl : './views/logout.html'
});
$urlRouterProvider.otherwise('/');
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
} | angular
.module('zibble', ['angular-jwt', 'ngResource', 'ui.router'])
.constant('API', 'http://localhost:3000')
.config(function($httpProvider){
$httpProvider.interceptors.push('AuthInterceptor');
})
.config(MainRouter);
function MainRouter($stateProvider, $urlRouterProvider, $locationProvider){
$stateProvider
.state('home', {
url : '/',
templateUrl : './views/home.html'
});
$stateProvider
.state('login', {
url : '/login',
templateUrl : './views/login.html'
});
$stateProvider
.state('signup', {
url : '/signup',
templateUrl : './views/signup.html'
});
$stateProvider
.state('logout', {
url : '/logout',
templateUrl : './views/logout.html'
});
$urlRouterProvider.otherwise('/');
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.