text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Use absolute usage file path
|
#!/usr/bin/env node
require('exit-code');
var fs = require('fs');
var path = require('path');
var minimist = require('minimist');
var argv = minimist(process.argv.slice(2), {
alias: {
n: 'node',
b: 'browser',
r: 'report',
h: 'help',
v: 'version'
}
});
if (argv.help) {
logHelp();
} else if (argv.version) {
logVersion();
} else if (argv.node || argv.browser) {
var unitest = require('../');
unitest({
node: argv.node,
browser: argv.browser,
report: ensureArray(argv.report)
});
} else {
logHelp();
process.exitCode = 1;
}
function ensureArray(arg) {
return (arg && typeof arg === 'string') ? [arg] : arg;
}
function logHelp() {
fs.createReadStream(path.join(__dirname, 'bin/usage.txt'))
.pipe(process.stdout);
}
function logVersion() {
var pkg = require('../package.json');
console.log(pkg.version);
}
|
#!/usr/bin/env node
require('exit-code');
var fs = require('fs');
var minimist = require('minimist');
var argv = minimist(process.argv.slice(2), {
alias: {
n: 'node',
b: 'browser',
r: 'report',
h: 'help',
v: 'version'
}
});
if (argv.help) {
logHelp();
} else if (argv.version) {
logVersion();
} else if (argv.node || argv.browser) {
var unitest = require('../');
unitest({
node: argv.node,
browser: argv.browser,
report: ensureArray(argv.report)
});
} else {
logHelp();
process.exitCode = 1;
}
function ensureArray(arg) {
return (arg && typeof arg === 'string') ? [arg] : arg;
}
function logHelp() {
fs.createReadStream('bin/usage.txt').pipe(process.stdout);
}
function logVersion() {
var pkg = require('../package.json');
console.log(pkg.version);
}
|
Monitor temperature script as used for heating measurement
|
import time
import serial
import matplotlib.pyplot as plt
import csv
import os
import brewkettle
reload(brewkettle)
filename = time.strftime("%Y-%m-%d %H:%M") + ".csv"
path = os.path.join("data", filename)
f = open(path, "w")
csv_writer = csv.writer(f)
csv_writer.writerow(["Time [s]", "Temperature [C]"])
kettle = brewkettle.BrewKettle()
kettle.turn_pump_on()
kettle.turn_heater_on()
start = time.time()
previous = 0
while(True):
try:
now = time.time()
if (now - previous > 10):
temperature = kettle.get_temperature()
current = now - start
print "Time:\t\t" + str(current)
print "Temperature:\t" + str(temperature)
csv_writer.writerow((current, temperature))
previous = now
except KeyboardInterrupt:
f.close()
kettle.exit()
print "Done"
break
|
import time
import serial
import matplotlib.pyplot as plt
import csv
import os
import brewkettle
reload(brewkettle)
filename = time.strftime("%Y-%m-%d %H:%M") + ".csv"
path = os.path.join("data", filename)
f = open(path, "w")
csv_writer = csv.writer(f)
kettle = brewkettle.BrewKettle()
kettle.turn_pump_on()
start = time.time()
previous = start
while(True):
try:
now = time.time()
if (now - previous > 2):
temperature = kettle.get_temperature()
current = now - start
print "Time:\t\t" + str(current)
print "Temperature:\t" + str(temperature)
csv_writer.writerow((current, temperature))
previous = now
except KeyboardInterrupt:
f.close()
kettle.exit()
print "Done"
break
|
Remove QUnit UI's checkboxes from the DOM during tests to prevent false positives
Refs #373
|
/* global QUnit, expect, bootlint */
/* jshint browser: true */
/*eslint-env browser */
(function () {
'use strict';
function lintCurrentDoc() {
var lints = [];
var reporter = function (lint) {
lints.push(lint.message);
};
bootlint.lintCurrentDocument(reporter, []);
return lints;
}
QUnit.test(window.location.pathname, function (assert) {
// Remove checkboxes QUnit dynamically adds to the DOM as part of its UI
// because these checkboxes may not comply with some Bootlint checks.
$('#qunit-filter-pass, #qunit-urlconfig-noglobals, #qunit-urlconfig-notrycatch').remove();
expect(1);
var lints = Array.prototype.slice.call(document.querySelectorAll('#bootlint>li'));
var expectedLintMsgs = lints.map(function (item) {
return item.dataset.lint;
});
var actualLintMsgs = lintCurrentDoc();
assert.deepEqual(actualLintMsgs, expectedLintMsgs);
});
})();
|
/* global QUnit, expect, bootlint */
/* jshint browser: true */
/*eslint-env browser */
(function () {
'use strict';
function lintCurrentDoc() {
var lints = [];
var reporter = function (lint) {
lints.push(lint.message);
};
bootlint.lintCurrentDocument(reporter, []);
return lints;
}
QUnit.test(window.location.pathname, function (assert) {
expect(1);
var lints = Array.prototype.slice.call(document.querySelectorAll('#bootlint>li'));
var expectedLintMsgs = lints.map(function (item) {
return item.dataset.lint;
});
var actualLintMsgs = lintCurrentDoc();
assert.deepEqual(actualLintMsgs, expectedLintMsgs);
});
})();
|
Handle expired session and ajax call
|
<?php
/**
* Set the site to invite only mode, valid login credentials required
*
* @package Anqh
* @author Antti Qvickström
* @copyright (c) 2009 Antti Qvickström
* @license http://www.opensource.org/licenses/mit-license.php MIT license
*/
class invite_hook {
/**
* Adds invite only check to the routing event
*/
public function __construct() {
// Hook only if enabled in config
if (Kohana::config('site.inviteonly')) {
// Stop execution if ajax, ie. expired session and trying to do ajax call
if (request::is_ajax()) {
exit;
}
Event::add('system.routing', array($this, 'login'));
}
}
/**
* Show invite only page if enabled
*/
public function login() {
$uri = new URI();
// Redirect to invite page if not logged or signing in
if (!in_array($uri->string(), array('invite', 'sign/in')) && strpos($uri->string(), 'sign/up') !== 0 && !Visitor::instance()->logged_in()) {
url::redirect('invite');
}
}
}
new invite_hook();
|
<?php
/**
* Set the site to invite only mode, valid login credentials required
*
* @package Anqh
* @author Antti Qvickström
* @copyright (c) 2009 Antti Qvickström
* @license http://www.opensource.org/licenses/mit-license.php MIT license
*/
class invite_hook {
/**
* Adds invite only check to the routing event
*/
public function __construct() {
// Hook only if enabled in config
if (Kohana::config('site.inviteonly')) {
Event::add('system.routing', array($this, 'login'));
}
}
/**
* Show invite only page if enabled
*/
public function login() {
$uri = new URI();
// Redirect to invite page if not logged or signing in
if (!in_array($uri->string(), array('invite', 'sign/in')) && strpos($uri->string(), 'sign/up') !== 0 && !Visitor::instance()->logged_in()) {
url::redirect('invite');
}
}
}
new invite_hook();
|
Define generic MsgPackReceiver and re-define Receiver as a sub class of MsgPackReceiver
|
var net = require('net');
var EventEmitter = require('events').EventEmitter;
var msgpack = require('msgpack');
function MsgPackReceiver(port) {
this.port = port || undefined;
this._init();
}
MsgPackReceiver.prototype = new EventEmitter();
MsgPackReceiver.prototype._init = function() {
this._server = net.createServer(this._onConnect.bind(this));
};
MsgPackReceiver.prototype._onConnect = function(socket) {
var messageStream = new msgpack.Stream(socket);
messageStream.on('msg', this._onMessageReceive.bind(this));
};
MsgPackReceiver.prototype._onMessageReceive = function(data) {
this.emit('receive', data);
};
MsgPackReceiver.prototype.listen = function(callback) {
if (this.port) {
this._server.listen(this.port, callback);
} else {
this._server.listen((function(){
this.port = this._server.address().port;
callback();
}).bind(this));
}
};
MsgPackReceiver.prototype.close = function() {
if (this._server) {
this._server.close();
this._server = undefined;
}
this.port = undefined;
};
exports.MsgPackReceiver = MsgPackReceiver;
function Receiver(port) {
MsgPackReceiver.apply(this, arguments);
}
Receiver.prototype = Object.create(MsgPackReceiver.prototype);
Receiver.prototype._onMessageReceive = function(message) {
this.emit(message.tag, message.data);
};
exports.Receiver = Receiver;
|
var net = require('net');
var EventEmitter = require('events').EventEmitter;
var msgpack = require('msgpack');
function Receiver(port) {
this.port = port || undefined;
this._init();
}
Receiver.prototype = new EventEmitter();
Receiver.prototype._init = function() {
this._server = net.createServer(this._onConnect.bind(this));
};
Receiver.prototype._onConnect = function(socket) {
var messageStream = new msgpack.Stream(socket);
messageStream.on('msg', this._onMessageReceive.bind(this));
};
Receiver.prototype._onMessageReceive = function(message) {
this.emit(message.tag, message.data);
};
Receiver.prototype.listen = function(callback) {
if (this.port) {
this._server.listen(this.port, callback);
} else {
this._server.listen((function(){
this.port = this._server.address().port;
callback();
}).bind(this));
}
};
Receiver.prototype.close = function() {
if (this._server) {
this._server.close();
this._server = undefined;
}
this.port = undefined;
};
exports.Receiver = Receiver;
|
Allow overrides to be blank
|
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
POSITIONS = (
('HERO', 'Hero'),
('SEC_1', 'Secondary 1'),
('SEC_2', 'Secondary 2'),
('THIRD_1', 'Third 1'),
('THIRD_2', 'Third 2'),
('THIRD_3', 'Third 3'),
)
class HomepageBlock(models.Model):
limit = models.Q(app_label='shows', model='show') | models.Q(app_label='articles',
model='article') | models.Q(
app_label='events', model='event')
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, limit_choices_to=limit)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
published_at = models.DateTimeField()
position = models.CharField(max_length=12, choices=POSITIONS)
override_kicker = models.CharField(max_length=64, blank=True, default='')
override_title = models.CharField(max_length=265, blank=True, default='')
override_description = models.TextField(default='', blank=True)
override_background_color = models.CharField(max_length=64, blank=True, default='')
|
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
POSITIONS = (
('HERO', 'Hero'),
('SEC_1', 'Secondary 1'),
('SEC_2', 'Secondary 2'),
('THIRD_1', 'Third 1'),
('THIRD_2', 'Third 2'),
('THIRD_3', 'Third 3'),
)
class HomepageBlock(models.Model):
limit = models.Q(app_label='shows', model='show') | models.Q(app_label='articles',
model='article') | models.Q(
app_label='events', model='event')
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, limit_choices_to=limit)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
published_at = models.DateTimeField()
position = models.CharField(max_length=12, choices=POSITIONS)
override_kicker = models.CharField(max_length=64, default='')
override_title = models.CharField(max_length=265, default='')
override_description = models.TextField(default='')
override_background_color = models.CharField(max_length=64, default='')
|
Modify the perfect simulator to calculate dedup percentages based on file sizes (1 - data_in / data_total)
|
#!/usr/bin/env python3
import timer
import sys
import utils
def simulate():
# A set of files already in the storage
seen = set()
# The size of the all uploads combined (deduplicated or not)
total_in = 0
# The size of the data sent to the service
data_in = 0
tmr = timer.Timer()
for (i, (hsh, size)) in enumerate(utils.read_upload_stream()):
total_in += size
if hsh not in seen:
data_in += size
seen.add(hsh)
if (i + 1) % utils.REPORT_FREQUENCY == 0:
print("%s uploads, percentage %.4f, time %s, mem[%s]" % (
utils.num_fmt(i),
1 - data_in / total_in,
tmr.elapsed_str,
utils.get_mem_info()
), file=sys.stderr)
dedup_percentage = 1 - data_in / total_in
print("Simulation complete. stored=%s, uploaded=%s, dedup_percentage=%f" % (
utils.sizeof_fmt(data_in), utils.sizeof_fmt(total_in), dedup_percentage),
file=sys.stderr)
if __name__ == "__main__":
simulate()
|
#!/usr/bin/env python3
import timer
import sys
import utils
# A set of files already in the storage
seen = set()
# The total number of uploads
total_uploads = 0
# The number of files in the storage
files_in = 0
tmr = timer.Timer()
for (hsh, _) in utils.read_upload_stream():
if hsh not in seen:
files_in += 1
seen.add(hsh)
total_uploads += 1
if total_uploads % utils.REPORT_FREQUENCY == 0:
print("%s uploads, percentage %.4f, time %s, %s" % (
utils.num_fmt(total_uploads),
1 - files_in / total_uploads,
tmr.elapsed_str,
utils.get_mem_info()
), file=sys.stderr)
dedup_percentage = 1 - files_in / total_uploads
print("+++ Simulation complete. dedup_percentage=%f" % dedup_percentage,
file=sys.stderr)
|
Fix plug-in ID to match bundle's symbolic name.
|
package org.cohorte.studio.eclipse.ui.node;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
/**
* The activator class controls the plug-in life cycle
*/
public class Activator extends AbstractUIPlugin {
// The plug-in ID
public static final String PLUGIN_ID = "org.cohorte.studio.eclipse.ui.node"; //$NON-NLS-1$
// The shared instance
private static Activator plugin;
/**
* The constructor
*/
public Activator() {
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
*/
public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext context) throws Exception {
plugin = null;
super.stop(context);
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
}
|
package org.cohorte.studio.eclipse.ui.node;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
/**
* The activator class controls the plug-in life cycle
*/
public class Activator extends AbstractUIPlugin {
// The plug-in ID
public static final String PLUGIN_ID = "org.cohorte.studio.eclipse.ui.application"; //$NON-NLS-1$
// The shared instance
private static Activator plugin;
/**
* The constructor
*/
public Activator() {
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
*/
public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext context) throws Exception {
plugin = null;
super.stop(context);
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
}
|
Prepare 0.17.0 Vegas for BlackHat Arsenal
|
# -*- coding: utf-8 -*-
#
##################################################################################
#
# Copyright 2014-2017 Félix Brezo and Yaiza Rubio (i3visio, contacto@i3visio.com)
#
# OSRFramework is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##################################################################################
import osrframework.utils.logger
# Calling the logger when being imported
osrframework.utils.logger.setupLogger(loggerName="osrframework")
__version__="0.17.0"
|
# -*- coding: utf-8 -*-
#
##################################################################################
#
# Copyright 2014-2017 Félix Brezo and Yaiza Rubio (i3visio, contacto@i3visio.com)
#
# OSRFramework is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##################################################################################
import osrframework.utils.logger
# Calling the logger when being imported
osrframework.utils.logger.setupLogger(loggerName="osrframework")
__version__="0.17.0b"
|
Make Search Controller request all facets be shown
|
<?php
class SearchController extends BaseController {
protected $layout = 'layouts.master';
public function showSearchForm()
{
$this->layout->content = View::make('search');
}
public function showResults()
{
$query = Input::get('q');
$facets = array('about' => 10, 'author' => 10, 'datePublished' => 10, 'genre' => 10, 'itemType' => 10, 'inLanguage' => 10);
$options = array('facets' => $facets);
if (Input::get('startNum')){
$options['startNum'] = Input::get('startNum');
}
$response = Bib::Search($query, Session::get('accessToken'), $options);
if (is_a($response, '\Guzzle\Http\Exception\BadResponseException')) {
$this->layout->content = View::make('error', array('title' => 'Error', 'error' => $response));
} else {
$this->layout->content = View::make('search.results', array('title' => 'Search Results', 'search' => $response, 'query' => $query, 'pagination' => pagination($response)));
}
}
}
|
<?php
class SearchController extends BaseController {
protected $layout = 'layouts.master';
public function showSearchForm()
{
$this->layout->content = View::make('search');
}
public function showResults()
{
$query = Input::get('q');
$facets = array('author' => 10, 'inLanguage' => 10);
$options = array('facets' => $facets);
if (Input::get('startNum')){
$options['startNum'] = Input::get('startNum');
}
$response = Bib::Search($query, Session::get('accessToken'), $options);
if (is_a($response, '\Guzzle\Http\Exception\BadResponseException')) {
$this->layout->content = View::make('error', array('title' => 'Error', 'error' => $response));
} else {
$this->layout->content = View::make('search.results', array('title' => 'Search Results', 'search' => $response, 'query' => $query, 'pagination' => pagination($response)));
}
}
}
|
Use local port for now.
|
package ca.islandora.sync.routes;
import org.apache.camel.builder.RouteBuilder;
import org.fcrepo.camel.JmsHeaders;
import org.fcrepo.camel.RdfNamespaces;
import ca.islandora.sync.processors.DrupalNodeCreateJsonTransform;
public class DrupalNodeCreate extends RouteBuilder {
public void configure() throws Exception {
from("activemq:topic:fedora")
.routeId("fedoraIn")
.filter(header(JmsHeaders.EVENT_TYPE).contains(RdfNamespaces.REPOSITORY + "NODE_ADDED"))
.to("fcrepo:localhost:8080/fcrepo/rest")
.process(new DrupalNodeCreateJsonTransform())
.to("http4:localhost:8000/islandora/node")
.log("RESPONSE: ${headers} / ${body}")
.to("mock:result");
}
}
|
package ca.islandora.sync.routes;
import org.apache.camel.builder.RouteBuilder;
import org.fcrepo.camel.JmsHeaders;
import org.fcrepo.camel.RdfNamespaces;
import ca.islandora.sync.processors.DrupalNodeCreateJsonTransform;
public class DrupalNodeCreate extends RouteBuilder {
public void configure() throws Exception {
from("activemq:topic:fedora")
.routeId("fedoraIn")
.filter(header(JmsHeaders.EVENT_TYPE).contains(RdfNamespaces.REPOSITORY + "NODE_ADDED"))
.to("fcrepo:localhost:8080/fcrepo/rest")
.process(new DrupalNodeCreateJsonTransform())
.to("http4:localhost/islandora/node")
.log("RESPONSE: ${headers} / ${body}")
.to("mock:result");
}
}
|
BAP-3701: Package Manager Exception during installing or updating
|
<?php
namespace Oro\Bundle\SecurityBundle\Cache;
class OroDataCacheManager
{
/**
* @var array
*/
protected $cacheProviders = [];
/**
* Registers a cache provider in this manager
*
* @param object $cacheProvider
*/
public function registerCacheProvider($cacheProvider)
{
$this->cacheProviders[] = $cacheProvider;
}
/**
* Makes sure all cache providers are synchronized
* Call this method in main process if you need to get data modified in a child process
*/
public function sync()
{
foreach ($this->cacheProviders as $cacheProvider) {
if ($cacheProvider instanceof SyncCacheInterface) {
$cacheProvider->sync();
}
}
}
}
|
<?php
namespace Oro\Bundle\SecurityBundle\Cache;
class OroDataCacheManager
{
/**
* @var array
*/
protected $cacheProviders = [];
/**
* Registers a cache provider in this manager
*
* @param object $cacheProvider
*/
public function registerCacheProvider($cacheProvider)
{
$this->cacheProviders[] = $cacheProvider;
}
/**
* Makes sure all cache providers are synchronized
* Call this method in main process if you need to get data modified in a child process
*/
public function sync()
{
foreach ($this->cacheProviders as $cacheProvider) {
if ($cacheProvider instanceof SyncCacheInterface) {
$cacheProvider->sync();
var_dump($cacheProvider->getNamespace());
}
}
}
}
|
Add Octocat icon to Header
|
//@flow
import React from "react";
import { Ul, Li, Nav } from "./styled-components";
import { LinkedInIcon } from "../../../../elements/linkedin-icon";
import { OctocatIcon } from "../../../../elements/octocat-icon";
import { Highlight } from "../../../../elements/highlight";
import { Chevron } from "../../../../elements/chevron";
import theme from "../../../../global/style/mainTheme";
export const MainNav = (props: {}) => (
<Nav>
<Ul>
<Li><Highlight {...props} url="/">Projects</Highlight></Li>
<Li><Highlight {...props}>About</Highlight></Li>
<Li>
<Highlight highlightColor="transparent" {...props}>
<Chevron {...props}>Download</Chevron>
</Highlight>
</Li>
<Li><Highlight {...props}>Contact</Highlight></Li>
</Ul>
<Ul>
<Li><LinkedInIcon /></Li>
<Li><OctocatIcon /></Li>
</Ul>
</Nav>
);
|
//@flow
import React from "react";
import { Ul, Li, Nav } from "./styled-components";
import { LinkedInIcon } from "../../../../elements/linkedin-icon";
import { Highlight } from "../../../../elements/highlight";
import { Chevron } from "../../../../elements/chevron";
import theme from "../../../../global/style/mainTheme";
export const MainNav = (props: {}) => (
<Nav>
<Ul>
<Li><Highlight {...props} url="/">Projects</Highlight></Li>
<Li><Highlight {...props}>About</Highlight></Li>
<Li>
<Highlight highlightColor="transparent" {...props}>
<Chevron {...props}>Download</Chevron>
</Highlight>
</Li>
<Li><Highlight {...props}>Contact</Highlight></Li>
<Li><LinkedInIcon /></Li>
</Ul>
</Nav>
);
|
Change to code style that reflects rest of project
|
module.exports = function(grunt) {
return grunt.registerMultiTask('mkdir', 'Make directories.', function() {
var options;
options = this.options({
mode: null,
create: []
});
grunt.verbose.writeflags(options, 'Options');
return options.create.forEach(function(filepath) {
grunt.log.write('Creating "' + filepath + '"...');
try {
filepath = grunt.template.process(filepath);
grunt.file.mkdir(filepath, options.mode);
return grunt.log.ok();
} catch (e) {
grunt.log.error();
grunt.verbose.error(e);
return grunt.fail.warn('Mkdir operation failed.');
}
});
});
};
|
module.exports = function(grunt) {
return grunt.registerMultiTask('mkdir', 'Make directories.', function() {
var options;
options = this.options({
mode: null,
create: []
});
grunt.verbose.writeflags(options, 'Options');
return options.create.forEach(function(filepath) {
grunt.log.write('Creating "' + filepath + '"...');
try {
filepath = grunt.template.process( filepath );
grunt.file.mkdir(filepath, options.mode);
return grunt.log.ok();
} catch (e) {
grunt.log.error();
grunt.verbose.error(e);
return grunt.fail.warn('Mkdir operation failed.');
}
});
});
};
|
Fix ruler menu for breakpoints
Review URL: http://codereview.chromium.org/99357
|
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.debug.ui.editors;
import org.eclipse.ui.editors.text.TextEditor;
/**
* A simplistic Javascript editor which supports its own key binding scope.
*/
public class JsEditor extends TextEditor {
/** The ID of this editor as defined in plugin.xml */
public static final String EDITOR_ID =
"org.chromium.debug.ui.editors.JsEditor"; //$NON-NLS-1$
/** The ID of the editor context menu */
public static final String EDITOR_CONTEXT = EDITOR_ID + ".context"; //$NON-NLS-1$
/** The ID of the editor ruler context menu */
public static final String RULER_CONTEXT = EDITOR_ID + ".ruler"; //$NON-NLS-1$
@Override
protected void initializeEditor() {
super.initializeEditor();
setEditorContextMenuId(EDITOR_CONTEXT);
setRulerContextMenuId(RULER_CONTEXT);
}
public JsEditor() {
super();
setSourceViewerConfiguration(new JsSourceViewerConfiguration());
setKeyBindingScopes(new String[] { "org.eclipse.ui.textEditorScope", //$NON-NLS-1$
"org.chromium.debug.ui.editors.JsEditor.context" }); //$NON-NLS-1$
}
}
|
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.debug.ui.editors;
import org.eclipse.ui.editors.text.TextEditor;
/**
* A simplistic Javascript editor which supports its own key binding scope.
*/
public class JsEditor extends TextEditor {
/** The ID of this editor as defined in plugin.xml */
public static final String EDITOR_ID =
"org.chromium.debug.ui.editors.JsEditor"; //$NON-NLS-1$
/** The ID of the editor context menu */
public static final String EDITOR_CONTEXT = EDITOR_ID + ".context"; //$NON-NLS-1$
/** The ID of the editor ruler context menu */
public static final String RULER_CONTEXT = EDITOR_CONTEXT + ".ruler"; //$NON-NLS-1$
protected void initializeEditor() {
super.initializeEditor();
setEditorContextMenuId(EDITOR_CONTEXT);
setRulerContextMenuId(RULER_CONTEXT);
}
public JsEditor() {
super();
setSourceViewerConfiguration(new JsSourceViewerConfiguration());
setKeyBindingScopes(new String[] { "org.eclipse.ui.textEditorScope", //$NON-NLS-1$
"org.chromium.debug.ui.editors.JsEditor.context" }); //$NON-NLS-1$
}
}
|
Fix Rotues by RESTify Rules
|
exports.default = {
routes: function (api) {
return {
get: [
/* URIs */
{
path: '/:apiVersion/account/:accountHashID/monitor',
action: 'monitorList'
},
{
path: '/:apiVersion/account/:accountHashID/monitor/:monitorHashID',
action: 'monitorModel'
},
/* STATUS */
{
path: '/:apiVersion/Service/Status',
action: 'Status'
}
],
post: [
/* URIs */
{
path: '/:apiVersion/account/:accountHashID/monitor',
action: 'monitorModelEntry'
}
],
delete: [
/* URIs */
{
path: '/:apiVersion/account/:accountHashID/monitor',
action: 'monitorListDelete'
},
{
path: '/:apiVersion/account/:accountHashID/monitor/:monitorHashID',
action: 'monitorModelDelete'
}
]
}
}
}
|
exports.default = {
routes: function (api) {
return {
get: [
/* URIs */
{
path: '/:apiVersion/account/:accountHashId/monitor',
action: 'monitorList'
},
{
path: '/:apiVersion/account/:accountHashId/monitor/:monitorHashID',
action: 'monitorModel'
},
/* STATUS */
{
path: '/:apiVersion/Service/Status',
action: 'Status'
}
],
post: [
/* URIs */
{
path: '/:apiVersion/account/:accountHashId/monitor',
action: 'monitorModelEntry'
}
],
delete: [
/* URIs */
{
path: '/:apiVersion/account/:accountHashId/monitor',
action: 'monitorListDelete'
},
{
path: '/:apiVersion/account/:accountHashId/monitor/:monitorHashID',
action: 'monitorModelDelete'
}
]
}
}
}
|
Reformat source code according to Vaadin conventions
|
package org.vaadin.mcont.demo;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.Title;
import com.vaadin.server.VaadinRequest;
import com.vaadin.ui.Table;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
@Theme("demo")
@Title("MCont Add-on Demo")
@SuppressWarnings("serial")
public class DemoUI extends UI {
@Override
protected void init(VaadinRequest request) {
Table table = new Table();
// TODO create and set container
final VerticalLayout layout = new VerticalLayout();
layout.setStyleName("demoContentLayout");
layout.setSizeFull();
layout.addComponent(table);
setContent(layout);
}
}
|
package org.vaadin.mcont.demo;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.Title;
import com.vaadin.server.VaadinRequest;
import com.vaadin.ui.Table;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
@Theme("demo")
@Title("MCont Add-on Demo")
@SuppressWarnings("serial")
public class DemoUI extends UI
{
@Override
protected void init(VaadinRequest request) {
Table table = new Table();
// TODO create and set container
final VerticalLayout layout = new VerticalLayout();
layout.setStyleName("demoContentLayout");
layout.setSizeFull();
layout.addComponent(table);
setContent(layout);
}
}
|
Change PyPI development status from pre-alpha to beta.
|
#!/usr/bin/env python
from os.path import dirname, join
from distutils.core import setup
from colorama import VERSION
NAME = 'colorama'
def get_long_description(filename):
readme = join(dirname(__file__), filename)
return open(readme).read()
setup(
name=NAME,
version=VERSION,
description='Cross-platform colored terminal text.',
long_description=get_long_description('README.txt'),
keywords='color colour terminal text ansi windows crossplatform xplatform',
author='Jonathan Hartley',
author_email='tartley@tartley.com',
url='http://code.google.com/p/colorama/',
license='BSD',
packages=[NAME],
# see classifiers http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.5',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.1',
'Programming Language :: Python :: 3.2',
'Topic :: Terminals',
]
)
|
#!/usr/bin/env python
from os.path import dirname, join
from distutils.core import setup
from colorama import VERSION
NAME = 'colorama'
def get_long_description(filename):
readme = join(dirname(__file__), filename)
return open(readme).read()
setup(
name=NAME,
version=VERSION,
description='Cross-platform colored terminal text.',
long_description=get_long_description('README.txt'),
keywords='color colour terminal text ansi windows crossplatform xplatform',
author='Jonathan Hartley',
author_email='tartley@tartley.com',
url='http://code.google.com/p/colorama/',
license='BSD',
packages=[NAME],
# see classifiers http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.5',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.1',
'Topic :: Terminals',
]
)
|
Convert data to a string then apply the regex
|
'use strict';
/* global require */
/* global process */
var fs = require ('fs');
var path = require ('path');
var mkdirSync = function (path) {
try {
fs.mkdirSync (path);
} catch (e) {
if (e.code !== 'EEXIST') {
throw e;
}
}
};
var cwd = process.cwd ().replace (/\\/g, '/');
var suffix = '/node_modules/mai-chai';
if (cwd.endsWith (suffix)) {
var root = cwd.substr (0, cwd.length - suffix.length);
var test = path.join (root, 'test');
var files = fs.readdirSync (path.join (cwd, 'templates'));
mkdirSync (test);
mkdirSync (path.join (root, 'src'));
mkdirSync (path.join (root, 'src.test'));
var regex = /\r\n/g;
var newline = '\n';
if (process.platform === 'win32') {
regex = /[^\r]\n/g;
newline = '\r\n';
}
files.forEach (function (file) {
var data = fs.readFileSync (path.join (cwd, 'templates', file));
if (file.substr (0, 2) === '--') {
var name = file.substr (2, file.length - 2);
fs.writeFileSync (path.join (root, name), data.toString ().replace (regex, newline));
} else {
fs.writeFileSync (path.join (test, file), data.toString ().replace (regex, newline));
}
});
}
|
'use strict';
/* global require */
/* global process */
var fs = require ('fs');
var path = require ('path');
var mkdirSync = function (path) {
try {
fs.mkdirSync (path);
} catch (e) {
if (e.code !== 'EEXIST') {
throw e;
}
}
};
var cwd = process.cwd ().replace (/\\/g, '/');
var suffix = '/node_modules/mai-chai';
if (cwd.endsWith (suffix)) {
var root = cwd.substr (0, cwd.length - suffix.length);
var test = path.join (root, 'test');
var files = fs.readdirSync (path.join (cwd, 'templates'));
mkdirSync (test);
mkdirSync (path.join (root, 'src'));
mkdirSync (path.join (root, 'src.test'));
var regex = /\r\n/g;
var newline = '\n';
if (process.platform === 'win32') {
regex = /[^\r]\n/g;
newline = '\r\n';
}
files.forEach (function (file) {
var data = fs.readFileSync (path.join (cwd, 'templates', file));
if (file.substr (0, 2) === '--') {
var name = file.substr (2, file.length - 2);
fs.writeFileSync (path.join (root, name), data.replace (regex, newline));
} else {
fs.writeFileSync (path.join (test, file), data.replace (regex, newline));
}
});
}
|
Add correct namespace to webservice and add project id to querydata
|
<?php
namespace fennecweb\ajax\details;
class ProjectsTest extends \PHPUnit_Framework_TestCase
{
const NICKNAME = 'detailsProjectsTestUser';
const USERID = 'detailsProjectsTestUser';
const PROVIDER = 'detailsProjectsTestUser';
public function testExecute()
{
//Test if the selected project contains the correct information
$_SESSION['user'] = array(
'nickname' => ProjectsTest::NICKNAME,
'id' => ProjectsTest::USERID,
'provider' => ProjectsTest::PROVIDER,
'token' => 'detailsProjectTestUserToken'
);
list($service) = \fennecweb\WebService::factory('details/Projects');
$results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION, 'id' => 'table_1')));
$expected = array(
'table_1'
);
$this->assertArraySubset($expected, $results);
}
}
|
<?php
namespace fennecweb\ajax\details;
class ProjectsTest extends \PHPUnit_Framework_TestCase
{
const NICKNAME = 'detailsProjectsTestUser';
const USERID = 'detailsProjectsTestUser';
const PROVIDER = 'detailsProjectsTestUser';
public function testExecute()
{
//Test if the selected project contains the correct information
$_SESSION['user'] = array(
'nickname' => ProjectsTest::NICKNAME,
'id' => ProjectsTest::USERID,
'provider' => ProjectsTest::PROVIDER,
'token' => 'detailsProjectTestUserToken'
);
list($service) = WebService::factory('details/Project');
$results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION)));
$expected = array(
'table_1'
);
$this->assertArraySubset($expected, $results);
}
}
|
Remove specific versions of dependencies
|
import os
from setuptools import find_packages, setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='wagtail-tinify',
version='0.1',
packages=find_packages(),
include_package_data=True,
license='MIT License', # example license
description='A simple Django app optimize Wagtail Renditions using TinyPNG',
long_description=README,
url='https://www.example.com/',
author='Overcast Software',
author_email='info@overcast.io',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
install_requires=[
"tinify",
"cloudflare"
],
)
|
import os
from setuptools import find_packages, setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='wagtail-tinify',
version='0.1',
packages=find_packages(),
include_package_data=True,
license='MIT License', # example license
description='A simple Django app optimize Wagtail Renditions using TinyPNG',
long_description=README,
url='https://www.example.com/',
author='Overcast Software',
author_email='info@overcast.io',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
install_requires=[
"wagtail>=1.6.0",
"Django>=1.7.1",
"tinify",
"cloudflare"
],
)
|
Put 'abstract' keyword before visibility to follow psr-2 standard
|
<?php
namespace App\Middleware;
use Interop\Container\ContainerInterface;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use Cartalyst\Sentinel\Sentinel;
use Slim\Flash\Messages;
use Slim\Router;
use Slim\Views\Twig;
/**
* @property Twig view
* @property Router router
* @property Messages flash
* @property Sentinel auth
*/
abstract class Middleware
{
/**
* Slim application container
*
* @var ContainerInterface
*/
protected $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
abstract public function __invoke(Request $request, Response $response, callable $next);
public function __get($property)
{
return $this->container->get($property);
}
}
|
<?php
namespace App\Middleware;
use Interop\Container\ContainerInterface;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use Cartalyst\Sentinel\Sentinel;
use Slim\Flash\Messages;
use Slim\Router;
use Slim\Views\Twig;
/**
* @property Twig view
* @property Router router
* @property Messages flash
* @property Sentinel auth
*/
abstract class Middleware
{
/**
* Slim application container
*
* @var ContainerInterface
*/
protected $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public abstract function __invoke(Request $request, Response $response, callable $next);
public function __get($property)
{
return $this->container->get($property);
}
}
|
Add view function for councili arhive
|
# -*- coding: utf-8 -*-
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib import auth
from hackfmi.utils import json_view
from .models import User
from protocols.models import Protocol
def homepage(request):
return render(request, "index.html", {})
@json_view
def search(request, name):
members = User.objects.filter(first_name__icontains=name) or \
User.objects.filter(last_name__icontains=name) or \
User.objects.filter(username__icontains=name)
json_data = [dict(
id=member.id,
faculty_number=member.faculty_number,
full_name=' '.join([member.first_name, member.last_name]))
for member in members]
return json_data
def login(request):
if request.user.is_authenticated():
return redirect('members.views.homepage')
else:
return auth.views.login(request, template_name='members/login_form.html')
def archive_student_council(request):
protocols = Protocol.objects.all().order_by('-conducted_at')
return render(request, 'members/archive.html', locals())
|
# -*- coding: utf-8 -*-
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib import auth
from hackfmi.utils import json_view
from .models import User
def homepage(request):
return render(request, "index.html", {})
@json_view
def search(request, name):
members = User.objects.filter(first_name__icontains=name) or \
User.objects.filter(last_name__icontains=name) or \
User.objects.filter(username__icontains=name)
json_data = [dict(
id=member.id,
faculty_number=member.faculty_number,
full_name=' '.join([member.first_name, member.last_name]))
for member in members]
return json_data
def login(request):
if request.user.is_authenticated():
return redirect('members.views.homepage')
else:
return auth.views.login(request, template_name='members/login_form.html')
|
Return activity objects to template
|
Template.latestActivitiesByType.created = function () {
// Create 'instance' variable for use througout template logic
var instance = this;
// Create variable to hold activity type selection
instance.activityTypeSelection = new ReactiveVar();
// Create a reactive var to hold data containing latest activities by type
instance.latestActivityIdsByTypeData = new ReactiveVar();
Meteor.call('getAllResidentsLatestActivityIdsByType', function (error, latestResidentActivityIdsByType) {
// Set latest activities by type
instance.latestActivityIdsByTypeData.set(latestResidentActivityIdsByType);
});
};
Template.latestActivitiesByType.helpers({
'latestActivitiesByType': function () {
// Get a reference to template instance
var instance = Template.instance();
var latestResidentActivityIdsByType = instance.latestActivityIdsByTypeData.get();
// Create an array of activities
var activities = _.map(latestResidentActivityIdsByType, function (activityId) {
// Find a single activity by ID
var activity = Activities.findOne(activityId);
return activity;
});
// If activities exist
if (activities) {
// Return the activities to template
return activities;
} else {
// Return an empty array
return [];
}
}
});
|
Template.latestActivitiesByType.created = function () {
// Create 'instance' variable for use througout template logic
var instance = this;
// Create variable to hold activity type selection
instance.activityTypeSelection = new ReactiveVar();
// Create a reactive var to hold data containing latest activities by type
instance.latestActivityIdsByTypeData = new ReactiveVar();
Meteor.call('getAllResidentsLatestActivityIdsByType', function (error, latestResidentActivityIdsByType) {
// Set latest activities by type
instance.latestActivityIdsByTypeData.set(latestResidentActivityIdsByType);
});
};
Template.latestActivitiesByType.helpers({
'latestActivitiesByType': function () {
// Get a reference to template instance
var instance = Template.instance();
var latestResidentActivityIdsByType = instance.latestActivityIdsByTypeData.get();
//console.log(latestResidentActivitiesByType);
if (latestResidentActivityIdsByType) {
console.log(latestResidentActivityIdsByType);
return latestResidentActivityIdsByType;
} else {
return [];
}
}
});
|
Add another missing import and only handle specific exceptions
|
from django.views import View
from django import http
from uxhelpers.utils import json_response
import json
import logging
logger = logging.getLogger(__name__)
LEVELS = {
'CRITICAL': 50,
'ERROR': 40,
'WARNING': 30,
'INFO': 20,
'DEBUG': 10,
'NOTSET': 0
}
class LogPostView(View):
def post(self, request):
logger.error('received log event from frontend')
try:
json_data = json.loads(request.body)
level = json_data['level']
logger.log(LEVELS[level], json_data['message'])
except (ValueError, KeyError):
logger.warning('Malformed client log received')
return json_response(request, {'status': 200})
|
from django.views import View
from django import http
from uxhelpers.utils import json_response
import logging
logger = logging.getLogger(__name__)
LEVELS = {
'CRITICAL': 50,
'ERROR': 40,
'WARNING': 30,
'INFO': 20,
'DEBUG': 10,
'NOTSET': 0
}
class LogPostView(View):
def post(self, request):
try:
json_data = json.loads(request.body)
level = json_data['level']
logger.log(LEVELS[level], json_data['message'])
except Exception:
logger.warning('Malformed client log received')
return json_response(request, {'status': 200})
|
Add a space to let it shine.
|
<?php
/**
* _s Theme Customizer
*
* @package _s
* @since _s 1.2
*/
/**
* Add postMessage support for site title and description for the Theme Customizer.
*
* @param WP_Customize_Manager $wp_customize Theme Customizer object.
*
* @since _s 1.2
*/
function _s_customize_register( $wp_customize ) {
$wp_customize->get_setting( 'blogname' )->transport = 'postMessage';
$wp_customize->get_setting( 'blogdescription' )->transport = 'postMessage';
}
add_action( 'customize_register', '_s_customize_register' );
/**
* Binds JS handlers to make Theme Customizer preview reload changes asynchronously.
*
* @since _s 1.2
*/
function _s_customize_preview_js() {
wp_enqueue_script( '_s_customizer', get_template_directory_uri() . '/js/customizer.js', array( 'customize-preview' ), '20120827', true );
}
add_action( 'customize_preview_init', '_s_customize_preview_js' );
|
<?php
/**
* _s Theme Customizer
*
* @package _s
* @since _s 1.2
*/
/**
* Add postMessage support for site title and description for the Theme Customizer.
*
* @param WP_Customize_Manager $wp_customize Theme Customizer object.
*
* @since _s 1.2
*/
function _s_customize_register( $wp_customize ) {
$wp_customize->get_setting( 'blogname' )->transport = 'postMessage';
$wp_customize->get_setting( 'blogdescription' )->transport = 'postMessage';
}
add_action( 'customize_register', '_s_customize_register' );
/**
* Binds JS handlers to make Theme Customizer preview reload changes asynchronously.
*
* @since _s 1.2
*/
function _s_customize_preview_js() {
wp_enqueue_script( '_s_customizer', get_template_directory_uri() . '/js/customizer.js', array( 'customize-preview' ), '20120827', true );
}
add_action( 'customize_preview_init', '_s_customize_preview_js' );
|
Set up defaults so it doesn't crash in tests
|
package weavedns
import (
"io"
"io/ioutil"
"log"
"os"
)
const (
standard_log_flags = log.Ldate | log.Ltime | log.Lshortfile
)
// Inspired by http://www.goinggo.net/2013/11/using-log-package-in-go.html
var (
Debug *log.Logger = log.New(ioutil.Discard, "DEBUG: ", standard_log_flags)
Info *log.Logger = log.New(os.Stdout, "INFO: ", standard_log_flags)
Warning *log.Logger = log.New(os.Stdout, "WARNING: ", standard_log_flags)
Error *log.Logger = log.New(os.Stdout, "ERROR: ", standard_log_flags)
)
func InitLogging(debugHandle io.Writer,
infoHandle io.Writer,
warningHandle io.Writer,
errorHandle io.Writer) {
Debug = log.New(debugHandle, "DEBUG: ", standard_log_flags)
Info = log.New(infoHandle, "INFO: ", standard_log_flags)
Warning = log.New(warningHandle, "WARNING: ", standard_log_flags)
Error = log.New(errorHandle, "ERROR: ", standard_log_flags)
}
|
package weavedns
import (
"io"
"log"
)
// Inspired by http://www.goinggo.net/2013/11/using-log-package-in-go.html
var (
Debug *log.Logger
Info *log.Logger
Warning *log.Logger
Error *log.Logger
)
func InitLogging(debugHandle io.Writer,
infoHandle io.Writer,
warningHandle io.Writer,
errorHandle io.Writer) {
Debug = log.New(debugHandle, "DEBUG: ", log.Ldate|log.Ltime|log.Lshortfile)
Info = log.New(infoHandle, "INFO: ", log.Ldate|log.Ltime|log.Lshortfile)
Warning = log.New(warningHandle, "WARNING: ", log.Ldate|log.Ltime|log.Lshortfile)
Error = log.New(errorHandle, "ERROR: ", log.Ldate|log.Ltime|log.Lshortfile)
}
|
Create 2.3 release with recent PR merges
|
import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='widget-party',
version='2.3',
packages=['widget_party'],
install_requires=['django-dashing>=0.2.6', 'Django>=1.6', ],
include_package_data=True,
setup_requires=["setuptools_git >= 0.3"],
license='MIT License',
description='A collection of widgets to add functionality to django-dashing.',
long_description=README,
url='https://github.com/mverteuil/widget-party',
author='Matthew de Verteuil',
author_email='onceuponajooks@gmail.com',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Utilities',
],
)
|
import os
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='widget-party',
version='2.2.3',
packages=['widget_party'],
install_requires=['django-dashing>=0.2.6', 'Django>=1.6', ],
include_package_data=True,
setup_requires=["setuptools_git >= 0.3"],
license='MIT License',
description='A collection of widgets to add functionality to django-dashing.',
long_description=README,
url='https://github.com/mverteuil/widget-party',
author='Matthew de Verteuil',
author_email='onceuponajooks@gmail.com',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Utilities',
],
)
|
Revert 11533 now that TestKey is checked in.
git-svn-id: 6bd94cac40bd5c1df74b384d972046d926de6ffa@11535 a8845c50-7012-0410-95d3-8e1449b9b1e4
|
package org.mifos.framework.components.configuration;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.mifos.application.master.business.TestMifosCurrency;
import org.mifos.framework.components.configuration.business.TestConfiguration;
import org.mifos.framework.components.configuration.cache.TestKey;
import org.mifos.framework.components.configuration.persistence.TestConfigurationPersistence;
import org.mifos.framework.components.configuration.persistence.service.TestConfigurationPersistenceService;
import org.mifos.framework.components.configuration.util.helpers.TestConfigurationIntializer;
import org.mifos.framework.components.configuration.util.helpers.TestSystemConfig;
public class ConfigurationTestSuite extends TestSuite {
public ConfigurationTestSuite() {
super();
}
public static Test suite()throws Exception
{
TestSuite testSuite = new ConfigurationTestSuite();
testSuite.addTestSuite(TestConfigurationPersistence.class);
testSuite.addTestSuite(TestConfigurationPersistenceService.class);
testSuite.addTestSuite(TestSystemConfig.class);
testSuite.addTestSuite(TestMifosCurrency.class);
testSuite.addTestSuite(TestConfigurationIntializer.class);
testSuite.addTestSuite(TestConfiguration.class);
testSuite.addTestSuite(TestKey.class);
return testSuite;
}
}
|
package org.mifos.framework.components.configuration;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.mifos.application.master.business.TestMifosCurrency;
import org.mifos.framework.components.configuration.business.TestConfiguration;
import org.mifos.framework.components.configuration.persistence.TestConfigurationPersistence;
import org.mifos.framework.components.configuration.persistence.service.TestConfigurationPersistenceService;
import org.mifos.framework.components.configuration.util.helpers.TestConfigurationIntializer;
import org.mifos.framework.components.configuration.util.helpers.TestSystemConfig;
public class ConfigurationTestSuite extends TestSuite {
public ConfigurationTestSuite() {
super();
}
public static Test suite()throws Exception
{
TestSuite testSuite = new ConfigurationTestSuite();
testSuite.addTestSuite(TestConfigurationPersistence.class);
testSuite.addTestSuite(TestConfigurationPersistenceService.class);
testSuite.addTestSuite(TestSystemConfig.class);
testSuite.addTestSuite(TestMifosCurrency.class);
testSuite.addTestSuite(TestConfigurationIntializer.class);
testSuite.addTestSuite(TestConfiguration.class);
// testSuite.addTestSuite(TestKey.class);
return testSuite;
}
}
|
Fix mocha tests to handle Features
|
const jsdom = require('jsdom');
global.document = jsdom.jsdom('<!doctype html><html><body><div></div></body></html>', {
url: 'http://localhost',
skipWindowCheck: true
});
global.window = document.defaultView;
global.navigator = global.window.navigator;
const sinon = require('sinon');
const React = require('react');
const ReactDOM = require('react-dom');
const ReactTestUtils = require('react-addons-test-utils');
const $ = require('jquery');
const _ = require('lodash');
const moment = require('moment');
const momentRecur = require('moment-recur');
const I18n = require('../public/assets/javascripts/i18n.js');
const chai = require('chai');
const sinonChai = require('sinon-chai');
global.$ = $;
global._ = _;
global.sinon = sinon;
global.React = React;
global.ReactDOM = ReactDOM;
global.ReactTestUtils = ReactTestUtils;
global.Simulate = ReactTestUtils.Simulate;
global.moment = moment;
global['moment-recur'] = momentRecur;
global.I18n = I18n;
global.chai = chai;
global.expect = chai.expect;
global.assert = chai.assert;
global.Features = {};
require('../public/assets/javascripts/i18n/en');
chai.use(sinonChai);
|
const jsdom = require('jsdom');
global.document = jsdom.jsdom('<!doctype html><html><body><div></div></body></html>', {
url: 'http://localhost',
skipWindowCheck: true
});
global.window = document.defaultView;
global.navigator = global.window.navigator;
const sinon = require('sinon');
const React = require('react');
const ReactDOM = require('react-dom');
const ReactTestUtils = require('react-addons-test-utils');
const $ = require('jquery');
const _ = require('lodash');
const moment = require('moment');
const momentRecur = require('moment-recur');
const I18n = require('../public/assets/javascripts/i18n.js');
const chai = require('chai');
const sinonChai = require('sinon-chai');
global.$ = $;
global._ = _;
global.sinon = sinon;
global.React = React;
global.ReactDOM = ReactDOM;
global.ReactTestUtils = ReactTestUtils;
global.Simulate = ReactTestUtils.Simulate;
global.moment = moment;
global['moment-recur'] = momentRecur;
global.I18n = I18n;
global.chai = chai;
global.expect = chai.expect;
global.assert = chai.assert;
require('../public/assets/javascripts/i18n/en');
chai.use(sinonChai);
|
Create new ViewHolder for Crime
|
package com.bignerdranch.android.criminalintent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class CrimeListFragment extends Fragment {
private RecyclerView mRecyclerView;
@Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_crime_list, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.crime_recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}
private class CrimeHolder extends RecyclerView.ViewHolder {
public TextView mTitleTextView;
public CrimeHolder(View itemView) {
super (itemView);
mTitleTextView = (TextView) itemView;
}
}
}
|
package com.bignerdranch.android.criminalintent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class CrimeListFragment extends Fragment {
private RecyclerView mRecyclerView;
@Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_crime_list, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.crime_recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}
}
|
Remove test cruft that is causing failures.
|
import { test , moduleForComponent } from 'appkit/tests/helpers/module-for';
import BayeuxStub from 'appkit/tests/helpers/bayeux-stub';
import PipedriveDealsComponent from 'appkit/components/pipedrive-deals';
moduleForComponent('dashboard-widget', 'Unit - Pipedrive Deals component', {
subject: function() {
var obj = PipedriveDealsComponent.create({
bayeux: new BayeuxStub(),
channel: 'awesome-deals'
});
return obj;
}
});
test('it exists', function() {
ok(this.subject() instanceof PipedriveDealsComponent);
});
test('it receives data and sets contents', function() {
var data = '[{"stage_name":"Opportunity","filters":' +
'[{"name":"Substantial","dollar_value":1217000,"deal_count":29},' +
'{"name":"SF","dollar_value":300000,"deal_count":8}]' +
'},' +
'{"stage_name":"Qualified","filters":' +
'[{"name":"Substantial","dollar_value":0,"deal_count":29},' +
'{"name":"SF","dollar_value":0,"deal_count":8}]' +
'}]';
this.subject().send('receiveEvent', data);
equal(this.subject().get('contents.0.stage_name'), 'Opportunity');
});
|
import { test , moduleForComponent } from 'appkit/tests/helpers/module-for';
import BayeuxStub from 'appkit/tests/helpers/bayeux-stub';
import PipedriveDealsComponent from 'appkit/components/pipedrive-deals';
moduleForComponent('dashboard-widget', 'Unit - Pipedrive Deals component', {
subject: function() {
var obj = PipedriveDealsComponent.create({
bayeux: new BayeuxStub(),
channel: 'awesome-deals'
});
return obj;
},
setup: function() {
this.subject().setupChart();
}
});
test('it exists', function() {
ok(this.subject() instanceof PipedriveDealsComponent);
});
test('it receives data and sets contents', function() {
var data = '[{"stage_name":"Opportunity","filters":' +
'[{"name":"Substantial","dollar_value":1217000,"deal_count":29},' +
'{"name":"SF","dollar_value":300000,"deal_count":8}]' +
'},' +
'{"stage_name":"Qualified","filters":' +
'[{"name":"Substantial","dollar_value":0,"deal_count":29},' +
'{"name":"SF","dollar_value":0,"deal_count":8}]' +
'}]';
this.subject().send('receiveEvent', data);
equal(this.subject().get('contents.0.stage_name'), 'Opportunity');
});
|
Use $directive prefix for directive traces
|
var utils = require('../utils')
module.exports = function ($provide) {
var instrumentDirective = function (name) {
var directiveName = name + 'Directive'
$provide.decorator(directiveName, ['$delegate', '$injector', function ($delegate, $injector) {
utils.instrumentObject($delegate[0], $injector, {
type: 'template.$directive',
prefix: '$directive.' + name
})
return $delegate
}])
}
return {
instrumentAll: function (modules) {
modules.forEach(function (name) {
instrumentDirective(name)
})
},
instrumentCore: function () {
// Core directive instrumentation
var coreDirectives = ['ngBind', 'ngClass', 'ngModel', 'ngIf', 'ngInclude', 'ngRepeat', 'ngSrc', 'ngStyle', 'ngSwitch', 'ngTransclude']
coreDirectives.forEach(function (name) {
instrumentDirective(name)
})
}
}
}
|
var utils = require('../utils')
module.exports = function ($provide) {
var instrumentDirective = function (name) {
var directiveName = name + 'Directive'
$provide.decorator(directiveName, ['$delegate', '$injector', function ($delegate, $injector) {
utils.instrumentObject($delegate[0], $injector, {
type: 'template.$directive',
prefix: directiveName
})
return $delegate
}])
}
return {
instrumentAll: function (modules) {
modules.forEach(function (name) {
instrumentDirective(name)
})
},
instrumentCore: function () {
// Core directive instrumentation
var coreDirectives = ['ngBind', 'ngClass', 'ngModel', 'ngIf', 'ngInclude', 'ngRepeat', 'ngSrc', 'ngStyle', 'ngSwitch', 'ngTransclude']
coreDirectives.forEach(function (name) {
instrumentDirective(name)
})
}
}
}
|
Reduce starting upgrader quantity to 3 at practical room level 6
Because of the size of the upgraders the storage is drained
considerably while they work. This means the system is basically doing
a big burst of upgrading, stopping to rebuild the energy buffer, and
then upgrading again.
Reducing to three upgraders will mean less upgraders run at once but
upgraders should be running more often in general.
In the event that energy builds up higher (such as when remote mining
gets enabled) the system already is already programmed to spawn an
extra two upgraders on top of the ones it already spawns.
|
// Each key corresponds to the current practical room level and contains a separate objects containing settings enabled
// at that level. Each higher level inherits the settings from the level below it.
let roomLevelOptions = {
1: {
'UPGRADERS_QUANTITY': 5
},
2: {},
3: {},
4: {
'DEDICATED_MINERS': true,
'PURE_CARRY_FILLERS': true
},
5: {},
6: {
'EXTRACT_MINERALS': true,
'UPGRADERS_QUANTITY': 3
},
7: {},
8: {
'UPGRADERS_QUANTITY': 1
}
}
// Have each level inherit the settings from the previous level unless already set.
for (let level = 0; level <= 8; level++) {
for (let addLevel = level - 1; addLevel > 0; addLevel--) {
const keys = Object.keys(roomLevelOptions[addLevel])
for (let key of keys) {
if (typeof roomLevelOptions[level][key] === 'undefined') {
roomLevelOptions[level][key] = roomLevelOptions[addLevel][key]
}
}
}
}
Room.prototype.getRoomSetting = function (key) {
const level = this.getPracticalRoomLevel()
return roomLevelOptions[level][key] ? roomLevelOptions[level][key] : false
}
|
// Each key corresponds to the current practical room level and contains a separate objects containing settings enabled
// at that level. Each higher level inherits the settings from the level below it.
let roomLevelOptions = {
1: {
'UPGRADERS_QUANTITY': 5
},
2: {},
3: {},
4: {
'DEDICATED_MINERS': true,
'PURE_CARRY_FILLERS': true
},
5: {},
6: {
'EXTRACT_MINERALS': true
},
7: {},
8: {
'UPGRADERS_QUANTITY': 1
}
}
// Have each level inherit the settings from the previous level unless already set.
for (let level = 0; level <= 8; level++) {
for (let addLevel = level - 1; addLevel > 0; addLevel--) {
const keys = Object.keys(roomLevelOptions[addLevel])
for (let key of keys) {
if (typeof roomLevelOptions[level][key] === 'undefined') {
roomLevelOptions[level][key] = roomLevelOptions[addLevel][key]
}
}
}
}
Room.prototype.getRoomSetting = function (key) {
const level = this.getPracticalRoomLevel()
return roomLevelOptions[level][key] ? roomLevelOptions[level][key] : false
}
|
Fix ordering for test executions
|
<?php namespace Nestor\Repositories;
use Nestor\Model\Execution;
class DbExecutionRepository extends DbBaseRepository implements ExecutionRepository {
public function __construct(Execution $model)
{
parent::__construct($model);
}
public function findByTestRunId($test_run_id)
{
return $this->model->where('test_run_id', $test_run_id)->get()->toArray();
}
public function findByTestCaseVersionId($testCaseVersionId)
{
return $this->model->where('test_case_version_id', $testCaseVersionId)->get()->toArray();
}
public function findByExecutionStatusId($execution_status_id)
{
return $this->model->where('execution_status_id', $execution_status_id)->get()->toArray();
}
public function getExecutionsForTestCaseVersion($testRunId, $testCaseVersionId)
{
return $this
->model
->where('test_case_version_id', '=', $testCaseVersionId)
->where('test_run_id', '=', $testRunId)
->orderBy('executions.created_at', 'DESC')
->with('executionStatus')
->get()
->toArray();
}
}
|
<?php namespace Nestor\Repositories;
use Nestor\Model\Execution;
class DbExecutionRepository extends DbBaseRepository implements ExecutionRepository {
public function __construct(Execution $model)
{
parent::__construct($model);
}
public function findByTestRunId($test_run_id)
{
return $this->model->where('test_run_id', $test_run_id)->get()->toArray();
}
public function findByTestCaseVersionId($testCaseVersionId)
{
return $this->model->where('test_case_version_id', $testCaseVersionId)->get()->toArray();
}
public function findByExecutionStatusId($execution_status_id)
{
return $this->model->where('execution_status_id', $execution_status_id)->get()->toArray();
}
public function getExecutionsForTestCaseVersion($testRunId, $testCaseVersionId)
{
return $this
->model
->where('test_case_version_id', '=', $testCaseVersionId)
->where('test_run_id', '=', $testRunId)
->orderBy('executions.created_at')
->with('executionStatus')
->get()
->toArray();
}
}
|
Set unichr = chr for Python 3.
|
"""
Internal utility functions.
`htmlentitydecode` came from here:
http://wiki.python.org/moin/EscapingHtml
"""
import re
import sys
try:
from html.entities import name2codepoint
unichr = chr
except ImportError:
from htmlentitydefs import name2codepoint
def htmlentitydecode(s):
return re.sub(
'&(%s);' % '|'.join(name2codepoint),
lambda m: unichr(name2codepoint[m.group(1)]), s)
def smrt_input(globals_, locals_, ps1=">>> ", ps2="... "):
inputs = []
while True:
if inputs:
prompt = ps2
else:
prompt = ps1
inputs.append(input(prompt))
try:
ret = eval('\n'.join(inputs), globals_, locals_)
if ret:
print(str(ret))
return
except SyntaxError:
pass
def printNicely(string):
if hasattr(sys.stdout, 'buffer'):
sys.stdout.buffer.write(string.encode('utf8'))
print()
else:
print(string.encode('utf8'))
__all__ = ["htmlentitydecode", "smrt_input"]
|
"""
Internal utility functions.
`htmlentitydecode` came from here:
http://wiki.python.org/moin/EscapingHtml
"""
import re
import sys
try:
from html.entities import name2codepoint
except ImportError:
from htmlentitydefs import name2codepoint
def htmlentitydecode(s):
return re.sub(
'&(%s);' % '|'.join(name2codepoint),
lambda m: unichr(name2codepoint[m.group(1)]), s)
def smrt_input(globals_, locals_, ps1=">>> ", ps2="... "):
inputs = []
while True:
if inputs:
prompt = ps2
else:
prompt = ps1
inputs.append(input(prompt))
try:
ret = eval('\n'.join(inputs), globals_, locals_)
if ret:
print(str(ret))
return
except SyntaxError:
pass
def printNicely(string):
if hasattr(sys.stdout, 'buffer'):
sys.stdout.buffer.write(string.encode('utf8'))
print()
else:
print(string.encode('utf8'))
__all__ = ["htmlentitydecode", "smrt_input"]
|
Increase timeout on RC sensor readings
|
#!/usr/bin/env python
import pexpect
import os
import re
path = os.path.dirname(__file__)
class RcSensor(object):
def __init__(self, gpio, cycles=200, discharge_delay=10):
if gpio is None:
raise ValueError("Must supply gpio value")
self.gpio = gpio
self.cycles = cycles
self.discharge_delay = discharge_delay
self.rcsensor_bin = os.path.join(path, '../utils/rcsensor_cli')
self.rcsensor_cmd = 'sudo %s -g %s -c %s -d %s' % (self.rcsensor_bin, gpio, cycles, discharge_delay)
self.rcsense_re = re.compile('(\d+)\s')
def rc_count(self):
"""
Returns the average of cycle number of readings from a GPIO based R/C sensor
:return: int
"""
m = self.rcsense_re.match(pexpect.run(self.rcsensor_cmd, timeout=180))
count = int(m.groups()[0])
return count
if __name__ == '__main__':
sensor = RcSensor(22)
print(sensor.rc_count())
|
#!/usr/bin/env python
import pexpect
import os
import re
path = os.path.dirname(__file__)
class RcSensor(object):
def __init__(self, gpio, cycles=200, discharge_delay=10):
if gpio is None:
raise ValueError("Must supply gpio value")
self.gpio = gpio
self.cycles = cycles
self.discharge_delay = discharge_delay
self.rcsensor_bin = os.path.join(path, '../utils/rcsensor_cli')
self.rcsensor_cmd = 'sudo %s -g %s -c %s -d %s' % (self.rcsensor_bin, gpio, cycles, discharge_delay)
self.rcsense_re = re.compile('(\d+)\s')
def rc_count(self):
"""
Returns the average of cycle number of readings from a GPIO based R/C sensor
:return: int
"""
m = self.rcsense_re.match(pexpect.run(self.rcsensor_cmd, timeout=150))
count = int(m.groups()[0])
return count
if __name__ == '__main__':
sensor = RcSensor(22)
print(sensor.rc_count())
|
Fix svg rich backend to correctly show multiple figures.
|
"""Produce SVG versions of active plots for display by the rich Qt frontend.
"""
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
# Standard library imports
from cStringIO import StringIO
# System library imports.
from matplotlib.backends.backend_svg import new_figure_manager
from matplotlib._pylab_helpers import Gcf
# Local imports.
from backend_payload import add_plot_payload
#-----------------------------------------------------------------------------
# Functions
#-----------------------------------------------------------------------------
def show():
""" Deliver a SVG payload.
"""
for figure_manager in Gcf.get_all_fig_managers():
# Make the background transparent.
# figure_manager.canvas.figure.patch.set_alpha(0.0)
# Set the background to white instead so it looks good on black.
figure_manager.canvas.figure.set_facecolor('white')
figure_manager.canvas.figure.set_edgecolor('white')
data = svg_from_canvas(figure_manager.canvas)
add_plot_payload('svg', data)
def svg_from_canvas(canvas):
""" Return a string containing the SVG representation of a FigureCanvasSvg.
"""
string_io = StringIO()
canvas.print_svg(string_io)
return string_io.getvalue()
|
# Standard library imports
from cStringIO import StringIO
# System library imports.
from matplotlib.backends.backend_svg import new_figure_manager
from matplotlib._pylab_helpers import Gcf
# Local imports.
from backend_payload import add_plot_payload
def show():
""" Deliver a SVG payload.
"""
figure_manager = Gcf.get_active()
if figure_manager is not None:
# Make the background transparent.
# figure_manager.canvas.figure.patch.set_alpha(0.0)
# Set the background to white instead so it looks good on black.
figure_manager.canvas.figure.set_facecolor('white')
figure_manager.canvas.figure.set_edgecolor('white')
data = svg_from_canvas(figure_manager.canvas)
add_plot_payload('svg', data)
def svg_from_canvas(canvas):
""" Return a string containing the SVG representation of a FigureCanvasSvg.
"""
string_io = StringIO()
canvas.print_svg(string_io)
return string_io.getvalue()
|
Clarify message for unexpected errors
When reading a lot, the phrasing "Expected error" at the start makes me think it
*is* expected...then we say "not to have occurred" which is awkward.
Let's avoid the double negative.
|
package matchers
import (
"fmt"
"github.com/onsi/gomega/format"
)
type HaveOccurredMatcher struct {
}
func (matcher *HaveOccurredMatcher) Match(actual interface{}) (success bool, err error) {
// is purely nil?
if actual == nil {
return false, nil
}
// must be an 'error' type
if !isError(actual) {
return false, fmt.Errorf("Expected an error-type. Got:\n%s", format.Object(actual, 1))
}
// must be non-nil (or a pointer to a non-nil)
return !isNil(actual), nil
}
func (matcher *HaveOccurredMatcher) FailureMessage(actual interface{}) (message string) {
return fmt.Sprintf("Expected an error to have occurred. Got:\n%s", format.Object(actual, 1))
}
func (matcher *HaveOccurredMatcher) NegatedFailureMessage(actual interface{}) (message string) {
return fmt.Sprintf("Unexpected error:\n%s\n%s\n%s", format.Object(actual, 1), format.IndentString(actual.(error).Error(), 1), "occurred")
}
|
package matchers
import (
"fmt"
"github.com/onsi/gomega/format"
)
type HaveOccurredMatcher struct {
}
func (matcher *HaveOccurredMatcher) Match(actual interface{}) (success bool, err error) {
// is purely nil?
if actual == nil {
return false, nil
}
// must be an 'error' type
if !isError(actual) {
return false, fmt.Errorf("Expected an error-type. Got:\n%s", format.Object(actual, 1))
}
// must be non-nil (or a pointer to a non-nil)
return !isNil(actual), nil
}
func (matcher *HaveOccurredMatcher) FailureMessage(actual interface{}) (message string) {
return fmt.Sprintf("Expected an error to have occurred. Got:\n%s", format.Object(actual, 1))
}
func (matcher *HaveOccurredMatcher) NegatedFailureMessage(actual interface{}) (message string) {
return fmt.Sprintf("Expected error:\n%s\n%s\n%s", format.Object(actual, 1), format.IndentString(actual.(error).Error(), 1), "not to have occurred")
}
|
Add label in error message
|
import pprint
import sublime
import json
from .util import Util
# for debug
pp = pprint.PrettyPrinter(indent=4)
class Base(object):
def settings(self, attr):
settings = json.loads(sublime.load_resource('Packages/MarkdownTOC/MarkdownTOC.sublime-settings'))
user_settings = json.loads(sublime.load_resource('Packages/User/MarkdownTOC.sublime-settings'))
Util.dict_merge(settings, user_settings)
return settings[attr]
def defaults(self):
return self.settings('defaults')
def log(self, arg):
if self.settings('logging') is True:
arg = str(arg)
sublime.status_message(arg)
pp.pprint(arg)
def error(self, arg):
arg = 'MarkdownTOC Error: '+arg
arg = str(arg)
sublime.status_message(arg)
pp.pprint(arg)
|
import pprint
import sublime
import json
from .util import Util
# for debug
pp = pprint.PrettyPrinter(indent=4)
class Base(object):
def settings(self, attr):
settings = json.loads(sublime.load_resource('Packages/MarkdownTOC/MarkdownTOC.sublime-settings'))
user_settings = json.loads(sublime.load_resource('Packages/User/MarkdownTOC.sublime-settings'))
Util.dict_merge(settings, user_settings)
return settings[attr]
def defaults(self):
return self.settings('defaults')
def log(self, arg):
if self.settings('logging') is True:
arg = str(arg)
sublime.status_message(arg)
pp.pprint(arg)
def error(self, arg):
arg = str(arg)
sublime.status_message(arg)
pp.pprint(arg)
|
Replace with trivial lambda default fixed after 2cfd1ece23
|
// "Fix all 'Constant conditions & exceptions' problems in file" "true"
import org.jetbrains.annotations.*;
import java.util.*;
import java.util.stream.Stream;
public class MethodReferenceConstantValue {
@Contract(value = "!null -> false", pure = true)
public boolean strangeMethod(String s) {
return s == null ? new Random().nextBoolean() : false;
}
public void test(Optional<String> opt) {
X x = (methodReferenceConstantValue, s1) -> false;
Boolean aBoolean = opt.map(s -> false)
.map(o1 -> true)
.map(o -> false)
.orElse(false);
if (opt.isPresent()) {
Stream.generate(() -> true)
.limit(10)
.forEach(System.out::println);
}
}
interface X {
boolean action(@Nullable MethodReferenceConstantValue a, @NotNull String b);
}
}
|
// "Fix all 'Constant conditions & exceptions' problems in file" "true"
import org.jetbrains.annotations.*;
import java.util.*;
import java.util.stream.Stream;
public class MethodReferenceConstantValue {
@Contract(value = "!null -> false", pure = true)
public boolean strangeMethod(String s) {
return s == null ? new Random().nextBoolean() : false;
}
public void test(Optional<String> opt) {
X x = (methodReferenceConstantValue, s) -> false;
Boolean aBoolean = opt.map(s -> false)
.map(o -> true)
.map(o -> false)
.orElse(false);
if (opt.isPresent()) {
Stream.generate(() -> true)
.limit(10)
.forEach(System.out::println);
}
}
interface X {
boolean action(@Nullable MethodReferenceConstantValue a, @NotNull String b);
}
}
|
Fix arguments to pass done through correctly.
|
var request = require('request');
var xml2js = require('xml2js');
function init() {
var module = {};
function latestRelease(project, majorVersion, done, cb) {
var releaseUri = 'https://updates.drupal.org/release-history/';
request(releaseUri + project + '/' + majorVersion, function (error, response, body) {
if (!error && response.statusCode == 200 && body.length) {
xml2js.parseString(body, function (err, result) {
if (!err && result && result.project && result.project.releases && result.project.releases[0] && result.project.releases[0].release && result.project.releases[0].release[0] && result.project.releases[0].release[0].version) {
cb(null, result.project.releases[0].release[0].version[0], done);
}
else {
cb('Could not parse latest version of ' + project + ' for Drush makefile. Received:\n', result, done);
}
});
}
else {
cb('Could not retrieve latest version of ' + project + ' for Drush makefile.\n', null, done);
}
});
}
module.latestRelease = latestRelease;
return module;
}
module.exports = init();
|
var request = require('request');
var xml2js = require('xml2js');
function init() {
var module = {};
function latestRelease(project, majorVersion, done, cb) {
var releaseUri = 'https://updates.drupal.org/release-history/';
request(releaseUri + project + '/' + majorVersion, function (error, response, body) {
if (!error && response.statusCode == 200 && body.length) {
xml2js.parseString(body, function (err, result) {
if (!err && result && result.project && result.project.releases && result.project.releases[0] && result.project.releases[0].release && result.project.releases[0].release[0] && result.project.releases[0].release[0].version) {
cb(null, result.project.releases[0].release[0].version[0], done);
}
else {
cb('Could not parse latest version of ' + project + ' for Drush makefile. Received:\n', result, done);
}
});
}
else {
cb('Could not retrieve latest version of ' + project + ' for Drush makefile.\n', done);
}
});
}
module.latestRelease = latestRelease;
return module;
}
module.exports = init();
|
Resolve urls embedded in stylus sheets
|
var _ = require('lodash'),
StylusIncludesPlugin = require('./plugins/stylus-includes');
module.exports.config = function(additions) {
var options = additions.stylus || {},
defines = options.defines || {};
return _.defaults({
module: _.defaults({
loaders: loaders(defines, additions.module && additions.module.loaders)
}, additions.module),
plugins: plugins(options, additions.plugins)
}, additions);
};
function loaders(stylusDefines, additions) {
var base = [
{
test: /\.styl$/,
loader: require.resolve('stylus-loader')
+ '?' + JSON.stringify({define: stylusDefines, 'resolve url': true})
},
];
return additions ? base.concat(additions) : base;
}
function plugins(options, additions) {
var base = [
new StylusIncludesPlugin(options)
];
return additions ? base.concat(additions) : base;
}
|
var _ = require('lodash'),
StylusIncludesPlugin = require('./plugins/stylus-includes');
module.exports.config = function(additions) {
var options = additions.stylus || {},
defines = options.defines || {};
return _.defaults({
module: _.defaults({
loaders: loaders(defines, additions.module && additions.module.loaders)
}, additions.module),
plugins: plugins(options, additions.plugins)
}, additions);
};
function loaders(stylusDefines, additions) {
var base = [
{
test: /\.styl$/,
loader: require.resolve('stylus-loader')
+ '?' + JSON.stringify({define: stylusDefines})
}
];
return additions ? base.concat(additions) : base;
}
function plugins(options, additions) {
var base = [
new StylusIncludesPlugin(options)
];
return additions ? base.concat(additions) : base;
}
|
Update api test util to create files to use target name instead
|
from blinker import ANY
from urlparse import urlparse
from contextlib import contextmanager
from addons.osfstorage import settings as osfstorage_settings
def create_test_file(target, user, filename='test_file', create_guid=True):
osfstorage = target.get_addon('osfstorage')
root_node = osfstorage.get_root()
test_file = root_node.append_file(filename)
if create_guid:
test_file.get_guid(create=True)
test_file.create_version(user, {
'object': '06d80e',
'service': 'cloud',
osfstorage_settings.WATERBUTLER_RESOURCE: 'osf',
}, {
'size': 1337,
'contentType': 'img/png'
}).save()
return test_file
def urlparse_drop_netloc(url):
url = urlparse(url)
if url[4]:
return url[2] + '?' + url[4]
return url[2]
@contextmanager
def disconnected_from_listeners(signal):
"""Temporarily disconnect all listeners for a Blinker signal."""
listeners = list(signal.receivers_for(ANY))
for listener in listeners:
signal.disconnect(listener)
yield
for listener in listeners:
signal.connect(listener)
|
from blinker import ANY
from urlparse import urlparse
from contextlib import contextmanager
from addons.osfstorage import settings as osfstorage_settings
def create_test_file(node, user, filename='test_file', create_guid=True):
osfstorage = node.get_addon('osfstorage')
root_node = osfstorage.get_root()
test_file = root_node.append_file(filename)
if create_guid:
test_file.get_guid(create=True)
test_file.create_version(user, {
'object': '06d80e',
'service': 'cloud',
osfstorage_settings.WATERBUTLER_RESOURCE: 'osf',
}, {
'size': 1337,
'contentType': 'img/png'
}).save()
return test_file
def urlparse_drop_netloc(url):
url = urlparse(url)
if url[4]:
return url[2] + '?' + url[4]
return url[2]
@contextmanager
def disconnected_from_listeners(signal):
"""Temporarily disconnect all listeners for a Blinker signal."""
listeners = list(signal.receivers_for(ANY))
for listener in listeners:
signal.disconnect(listener)
yield
for listener in listeners:
signal.connect(listener)
|
Hide scrollbar when scroll reaches the bottom of the page
|
var globalOffset = require("global-offset");
module.exports = function(element) {
var offset = globalOffset(element),
scrollbar = document.createElement("div"),
inner = document.createElement("div");
element.style.overflowX = "scroll";
element.parentNode.insertBefore(scrollbar, element);
scrollbar.style.backgroundColor = "transparent";
scrollbar.style.position = "fixed";
scrollbar.style.bottom = 0;
scrollbar.style.left = offset.left + "px";
scrollbar.style.height = "20px";
scrollbar.style.width = element.getBoundingClientRect().width + "px";
scrollbar.style.overflowX = "scroll";
scrollbar.style.overflowY = "hidden";
scrollbar.appendChild(inner);
inner.style.width = element.children[0].getBoundingClientRect().width + "px";
inner.style.height = "1px";
scrollbar.onscroll = function() {
element.scrollLeft = scrollbar.scrollLeft;
};
element.onscroll = function() {
scrollbar.scrollLeft = element.scrollLeft;
};
window.onscroll = function() {
scrollbar.style.display = element.getBoundingClientRect().height + offset.top <= window.scrollY + window.innerHeight ? "none" : "block";
scrollbar.scrollLeft = element.scrollLeft;
};
};
|
var globalOffset = require("global-offset");
module.exports = function(element) {
var offset = globalOffset(element),
scrollbar = document.createElement("div"),
inner = document.createElement("div");
element.style.overflowX = "scroll";
element.parentNode.insertBefore(scrollbar, element);
scrollbar.style.backgroundColor = "transparent";
scrollbar.style.position = "fixed";
scrollbar.style.bottom = 0;
scrollbar.style.left = offset.left + "px";
scrollbar.style.height = "20px";
scrollbar.style.width = element.getBoundingClientRect().width + "px";
scrollbar.style.overflowX = "scroll";
scrollbar.style.overflowY = "hidden";
scrollbar.appendChild(inner);
inner.style.width = element.children[0].getBoundingClientRect().width + "px";
inner.style.height = "1px";
scrollbar.onscroll = function() {
element.scrollLeft = scrollbar.scrollLeft;
};
element.onscroll = function() {
scrollbar.scrollLeft = element.scrollLeft;
};
window.onscroll = function() {
scrollbar.style.display = element.getBoundingClientRect().height + offset.top < window.scrollY + window.innerHeight ? "none" : "block";
scrollbar.scrollLeft = element.scrollLeft;
};
};
|
Fix missing json encoding for support of large text chunks
|
<?php header('Content-Type: application/ld+json'); ?>
<?php header('Access-Control-Allow-Origin: *'); ?>
{
"@context": "<?php echo get_option('ldp_context', 'http://owl.openinitiative.com/oicontext.jsonld'); ?>",
"@graph": [
<?php while (have_posts()) : the_post(); ?>
{
<?php
$value = get_the_terms($post->ID, 'ldp_container')[0];
$termMeta = get_option("ldp_container_$value->term_id");
$modelsDecoded = json_decode($termMeta["ldp_model"]);
$fields = $modelsDecoded->{$value->slug}->fields;
foreach($fields as $field) {
if(substr($field->name, 0, 4) == "ldp_") {
echo('"'.substr($field->name, 4).'": ');
echo('' . json_encode(get_post_custom_values($field->name)[0]) . ',');
echo "\n ";
}
}
?>
"@id": "<?php the_permalink(); ?>"
}
<?php endwhile; ?>
]
}
|
<?php header('Content-Type: application/ld+json'); ?>
<?php header('Access-Control-Allow-Origin: *'); ?>
{
"@context": "<?php echo get_option('ldp_context', 'http://owl.openinitiative.com/oicontext.jsonld'); ?>",
"@graph": [
<?php while (have_posts()) : the_post(); ?>
{
<?php
$value = get_the_terms($post->ID, 'ldp_container')[0];
$termMeta = get_option("ldp_container_$value->term_id");
$modelsDecoded = json_decode($termMeta["ldp_model"]);
$fields = $modelsDecoded->{$value->slug}->fields;
foreach($fields as $field) {
if(substr($field->name, 0, 4) == "ldp_") {
echo('"'.substr($field->name, 4).'": ');
echo('"'.get_post_custom_values($field->name)[0].'",');
echo "\n ";
}
}
?>
"@id": "<?php the_permalink(); ?>"
}
<?php endwhile; ?>
]
}
|
Use revert() instead of throw
|
// Using web3 for its sha function...
var Web3 = require("web3");
var Deployed = {
makeSolidityDeployedAddressesLibrary: function(mapping) {
var self = this;
var source = "";
source += "pragma solidity ^0.4.6; \n\n library DeployedAddresses {" + "\n";
Object.keys(mapping).forEach(function(name) {
var address = mapping[name];
var body = "revert();";
if (address) {
address = self.toChecksumAddress(address);
body = "return " + address + ";";
}
source += " function " + name + "() returns (address) { " + body + " }"
source += "\n";
});
source += "}";
return source;
},
// Pulled from ethereumjs-util, but I don't want all its dependencies at the moment.
toChecksumAddress: function (address) {
var web3 = new Web3();
address = address.toLowerCase().replace("0x", "");
var hash = web3.sha3(address).replace("0x", "");
var ret = '0x'
for (var i = 0; i < address.length; i++) {
if (parseInt(hash[i], 16) >= 8) {
ret += address[i].toUpperCase()
} else {
ret += address[i]
}
}
return ret
}
};
module.exports = Deployed;
|
// Using web3 for its sha function...
var Web3 = require("web3");
var Deployed = {
makeSolidityDeployedAddressesLibrary: function(mapping) {
var self = this;
var source = "";
source += "pragma solidity ^0.4.6; \n\n library DeployedAddresses {" + "\n";
Object.keys(mapping).forEach(function(name) {
var address = mapping[name];
var body = "throw;";
if (address) {
address = self.toChecksumAddress(address);
body = "return " + address + ";";
}
source += " function " + name + "() returns (address) { " + body + " }"
source += "\n";
});
source += "}";
return source;
},
// Pulled from ethereumjs-util, but I don't want all its dependencies at the moment.
toChecksumAddress: function (address) {
var web3 = new Web3();
address = address.toLowerCase().replace("0x", "");
var hash = web3.sha3(address).replace("0x", "");
var ret = '0x'
for (var i = 0; i < address.length; i++) {
if (parseInt(hash[i], 16) >= 8) {
ret += address[i].toUpperCase()
} else {
ret += address[i]
}
}
return ret
}
};
module.exports = Deployed;
|
Make sure region name is uppercase.
|
import pyrax
from st2actions.runners.pythonrunner import Action
__all__ = [
'PyraxBaseAction'
]
class PyraxBaseAction(Action):
def __init__(self, config):
super(PyraxBaseAction, self).__init__(config)
self.pyrax = self._get_client()
def _get_client(self):
username = self.config['username']
api_key = self.config['api_key']
# Needs to be extracted to per-action
region = self.config['region'].upper()
print 'xxx', region
pyrax.set_setting('identity_type', 'rackspace')
pyrax.set_default_region(region)
pyrax.set_credentials(username, api_key)
return pyrax
|
from st2actions.runners.pythonrunner import Action
import pyrax
__all__ = [
'PyraxBaseAction'
]
class PyraxBaseAction(Action):
def __init__(self, config):
super(PyraxBaseAction, self).__init__(config)
self.pyrax = self._get_client()
def _get_client(self):
username = self.config['username']
api_key = self.config['api_key']
# Needs to be extracted to per-action
region = self.config['region']
pyrax.set_setting('identity_type', 'rackspace')
pyrax.set_default_region(region)
pyrax.set_credentials(username, api_key)
return pyrax
|
Move user input prompt (and input manip) inside activate()
|
var openBlockList = function (blog) {
$('document').ready( function () {
$("#blocked_blogs > .accordion_trigger_wrapper > .accordion_trigger").click();
block(blog);
});
}
var block = function (blog) {
$("#blocked_blogs > .accordion_content > .block-input > .text > #block").val(blog);
setTimeout(function () {
$("#blocked_blogs > .accordion_content > .block-input > .block-button").click();
}, 500);
}
var activate = function () {
console.log ("activate");
var str = window.prompt("Please input comma separated list of users to be blocked","");
var str = str.replace(" ", "");
var arr = str.split(",");
openBlockList(arr[0]);
var i = 1;
var inter = setInterval (function () {
console.log (i + " -- " + arr[i]);
block(arr[i++]);
if (i >= arr.length) {
clearInterval(inter);
console.log ("exit");
}
}, 1100);
}
activate ();
|
var openBlockList = function (blog) {
$('document').ready( function () {
$("#blocked_blogs > .accordion_trigger_wrapper > .accordion_trigger").click();
block(blog);
});
}
var block = function (blog) {
$("#blocked_blogs > .accordion_content > .block-input > .text > #block").val(blog);
setTimeout(function () {
$("#blocked_blogs > .accordion_content > .block-input > .block-button").click();
}, 500);
}
var str = window.prompt("Please input comma separated list of users to be blocked","");
var str = str.replace(" ", "");
var arr = str.split(",");
var activate = function () {
console.log ("activate");
openBlockList(arr[0]);
var i = 1;
var inter = setInterval (function () {
console.log (i + " -- " + arr[i]);
block(arr[i++]);
if (i >= arr.length) {
clearInterval(inter);
console.log ("exit");
}
}, 1100);
}
activate ();
|
Update task creds as well
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
module.exports = function (grunt) {
'use strict';
grunt.config('intern', {
node: {
options: {
config: 'tests/intern',
reporters: ['console'],
suites: ['tests/all']
}
},
// local browser
browser: {
options: {
runType: 'runner',
config: 'tests/intern_browser',
suites: ['tests/all']
}
},
sauce: {
options: {
runType: 'runner',
config: 'tests/intern_sauce',
suites: ['tests/all'],
sauceUsername: 'fxa-client',
sauceAccessKey: '863203af-38fd-4f1d-9332-adc8f60f157b'
}
}
});
};
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
module.exports = function (grunt) {
'use strict';
grunt.config('intern', {
node: {
options: {
config: 'tests/intern',
reporters: ['console'],
suites: ['tests/all']
}
},
// local browser
browser: {
options: {
runType: 'runner',
config: 'tests/intern_browser',
suites: ['tests/all']
}
},
sauce: {
options: {
runType: 'runner',
config: 'tests/intern_sauce',
suites: ['tests/all'],
sauceUsername: 'gherkin-web',
sauceAccessKey: 'de4982ac-cb05-4b9c-8059-385a83de8af4'
}
}
});
};
|
Switch to using Eimann's mirror to resolve jamendo track ids, due to jamendo downtime.
|
<?php
function resolve_external_url($url) {
if (substr($url, 0, 10) == 'jamendo://') {
return process_jamendo_url($url);
}
return $url;
}
function process_jamendo_url($url) {
if (substr($url, 10, 13) == 'track/stream/') {
$id = substr($url, 23);
return 'http://gigue.rrbone.net/' . $id . '.ogg2';
}
if (substr($url, 10, 15) == 'album/download/') {
$id = substr($url, 25);
return 'http://api.jamendo.com/get2/bittorrent/file/plain/?album_id=' . $id . '&type=archive&class=ogg3';
}
if (substr($url, 10, 10) == 'album/art/') {
$id = substr($url, 20);
return 'http://api.jamendo.com/get2/image/album/redirect/?id=' . $id . '&imagesize=200';
}
// We don't know what this is
return $url;
}
|
<?php
function resolve_external_url($url) {
if (substr($url, 0, 10) == 'jamendo://') {
return process_jamendo_url($url);
}
return $url;
}
function process_jamendo_url($url) {
if (substr($url, 10, 13) == 'track/stream/') {
$id = substr($url, 23);
return 'http://api.jamendo.com/get2/stream/track/redirect/?id=' . $id . '&streamencoding=ogg2';
}
if (substr($url, 10, 15) == 'album/download/') {
$id = substr($url, 25);
return 'http://api.jamendo.com/get2/bittorrent/file/plain/?album_id=' . $id . '&type=archive&class=ogg3';
}
if (substr($url, 10, 10) == 'album/art/') {
$id = substr($url, 20);
return 'http://api.jamendo.com/get2/image/album/redirect/?id=' . $id . '&imagesize=200';
}
// We don't know what this is
return $url;
}
|
Use tabs in new completions file snippet
Respects the user's indentation configuration.
|
import sublime_plugin
from sublime_lib.path import root_at_packages, get_package_name
PLUGIN_NAME = get_package_name()
COMPLETIONS_SYNTAX_DEF = "Packages/%s/Syntax Definitions/Sublime Completions.tmLanguage" % PLUGIN_NAME
TPL = """{
"scope": "source.${1:off}",
"completions": [
{ "trigger": "${2:some_trigger}", "contents": "${3:Hint: Use f, ff and fff plus Tab inside here.}" }$0
]
}""".replace(" ", "\t") # NOQA - line length
class NewCompletionsCommand(sublime_plugin.WindowCommand):
def run(self):
v = self.window.new_file()
v.run_command('insert_snippet', {"contents": TPL})
v.settings().set('syntax', COMPLETIONS_SYNTAX_DEF)
v.settings().set('default_dir', root_at_packages('User'))
|
import sublime_plugin
from sublime_lib.path import root_at_packages, get_package_name
PLUGIN_NAME = get_package_name()
COMPLETIONS_SYNTAX_DEF = "Packages/%s/Syntax Definitions/Sublime Completions.tmLanguage" % PLUGIN_NAME
TPL = """{
"scope": "source.${1:off}",
"completions": [
{ "trigger": "${2:some_trigger}", "contents": "${3:Hint: Use f, ff and fff plus Tab inside here.}" }$0
]
}"""
class NewCompletionsCommand(sublime_plugin.WindowCommand):
def run(self):
v = self.window.new_file()
v.run_command('insert_snippet', {"contents": TPL})
v.settings().set('syntax', COMPLETIONS_SYNTAX_DEF)
v.settings().set('default_dir', root_at_packages('User'))
|
Update dsub version to 0.2.3.
PiperOrigin-RevId: 222307052
|
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.2.3'
|
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.2.3.dev0'
|
Add ability to change the response status code on ErrorsException
|
<?php
/**
* Created by PhpStorm.
* User: Alex
* Date: 14/04/2019
* Time: 12:48
*/
namespace vr\api\components;
use Error;
use Exception;
use vr\core\ErrorsException;
use Yii;
/**
* Class ErrorHandler
* @package vr\api\components
*/
class ErrorHandler extends \yii\web\ErrorHandler
{
/**
* @var int
*/
public $errorStatusCode = 400;
/**
* @param Error|Exception $exception
*
* @return array
*/
protected function convertExceptionToArray($exception)
{
$array = parent::convertExceptionToArray($exception);
if ($exception instanceof ErrorsException) {
Yii::$app->response->statusCode = $this->errorStatusCode;
$array += [
'data' => $exception->data,
];
if (YII_DEBUG) {
$array += [
'trace' => explode("\n", $exception->getTraceAsString())
];
}
}
return $array;
}
}
|
<?php
/**
* Created by PhpStorm.
* User: Alex
* Date: 14/04/2019
* Time: 12:48
*/
namespace vr\api\components;
use Error;
use Exception;
use vr\core\ErrorsException;
/**
* Class ErrorHandler
* @package vr\api\components
*/
class ErrorHandler extends \yii\web\ErrorHandler
{
/**
* @param Error|Exception $exception
*
* @return array
*/
protected function convertExceptionToArray($exception)
{
$array = parent::convertExceptionToArray($exception);
if ($exception instanceof ErrorsException) {
$array += [
'data' => $exception->data,
];
if (YII_DEBUG) {
$array += [
'trace' => explode("\n", $exception->getTraceAsString())
];
}
}
return $array;
}
}
|
Use the correct type for Metrics in the Config struct
|
// Package config allows for reading configuration from a JSON file
package config
import (
"encoding/json"
"io/ioutil"
)
var conf *Config
type (
// Config struct holds data from a JSON config file
Config struct {
DB DB `json:"db"`
Metrics Metrics `json:"metrics"`
Mistify map[string]map[string]string `json:"mistify"`
}
)
// Load parses a JSON config file
func Load(path string) error {
data, err := ioutil.ReadFile(path)
if err != nil {
return err
}
newConfig := &Config{}
if err := json.Unmarshal(data, newConfig); err != nil {
return err
}
if err := newConfig.DB.Validate(); err != nil {
return err
}
conf = newConfig
return nil
}
// Get returns the configuration data and dies if the config is not loaded
func Get() *Config {
if conf == nil {
panic("attempted to access config while config not loaded")
}
return conf
}
|
// Package config allows for reading configuration from a JSON file
package config
import (
"encoding/json"
"io/ioutil"
)
var conf *Config
type (
// Config struct holds data from a JSON config file
Config struct {
DB DB `json:"db"`
Metrics map[string]string `json:"metrics"`
Mistify map[string]map[string]string `json:"mistify"`
}
)
// Load parses a JSON config file
func Load(path string) error {
data, err := ioutil.ReadFile(path)
if err != nil {
return err
}
newConfig := &Config{}
if err := json.Unmarshal(data, newConfig); err != nil {
return err
}
if err := newConfig.DB.Validate(); err != nil {
return err
}
conf = newConfig
return nil
}
// Get returns the configuration data and dies if the config is not loaded
func Get() *Config {
if conf == nil {
panic("attempted to access config while config not loaded")
}
return conf
}
|
Correct an AttributeError and a potential IndexErr
|
# -*- coding: utf-8 -*-
"""
utils.py
~~~~~~~~
Defines utility functions used by UPnPy.
"""
def camelcase_to_underscore(text):
"""
Convert a camelCasedString to one separated_by_underscores. Treats
neighbouring capitals as acronyms and doesn't separated them, e.g. URL does
not become u_r_l. That would be stupid.
:param text: The string to convert.
"""
outstr = []
for char in text:
if char.islower():
outstr.append(char)
elif (len(outstr) > 0) and (outstr[-1].islower()):
outstr.append('_')
outstr.append(char.lower())
else:
outstr.append(char.lower())
return ''.join(outstr)
|
# -*- coding: utf-8 -*-
"""
utils.py
~~~~~~~~
Defines utility functions used by UPnPy.
"""
def camelcase_to_underscore(text):
"""
Convert a camelCasedString to one separated_by_underscores. Treats
neighbouring capitals as acronyms and doesn't separated them, e.g. URL does
not become u_r_l. That would be stupid.
:param text: The string to convert.
"""
outstr = []
for char in text:
if char.is_lower():
outstr.append(char)
elif outstr[-1].is_lower():
outstr.append('_')
outstr.append(char.lower())
else:
outstr.append(char.lower())
return ''.join(outstr)
|
Change case of Django to django else pypi lookup fails
|
from setuptools import setup, find_packages
setup(
name='django-dfp',
version='0.3.2',
description='DFP implementation for Django',
long_description = open('README.rst', 'r').read() + open('AUTHORS.rst', 'r').read() + open('CHANGELOG.rst', 'r').read(),
author='Praekelt Foundation',
author_email='dev@praekelt.com',
license='BSD',
url='http://github.com/praekelt/django-dfp',
packages = find_packages(),
install_requires = [
'django',
],
include_package_data=True,
tests_require=[
'django-setuptest>=0.1.4',
],
test_suite="setuptest.setuptest.SetupTestSuite",
classifiers=[
"Programming Language :: Python",
"License :: OSI Approved :: BSD License",
"Development Status :: 4 - Beta",
"Operating System :: OS Independent",
"Framework :: Django",
"Intended Audience :: Developers",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content",
],
zip_safe=False,
)
|
from setuptools import setup, find_packages
setup(
name='django-dfp',
version='0.3.2',
description='DFP implementation for Django',
long_description = open('README.rst', 'r').read() + open('AUTHORS.rst', 'r').read() + open('CHANGELOG.rst', 'r').read(),
author='Praekelt Foundation',
author_email='dev@praekelt.com',
license='BSD',
url='http://github.com/praekelt/django-dfp',
packages = find_packages(),
install_requires = [
'Django',
],
include_package_data=True,
tests_require=[
'django-setuptest>=0.1.2',
],
test_suite="setuptest.setuptest.SetupTestSuite",
classifiers=[
"Programming Language :: Python",
"License :: OSI Approved :: BSD License",
"Development Status :: 4 - Beta",
"Operating System :: OS Independent",
"Framework :: Django",
"Intended Audience :: Developers",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content",
],
zip_safe=False,
)
|
Fix user not defined error for not logged in users
|
from django import forms
from django_fixmystreet.fixmystreet.models import FMSUser, getLoggedInUserId
from django.contrib.auth.models import User
from django.conf import settings
from django.utils.translation import ugettext_lazy
from django.contrib.sessions.models import Session
from django.contrib.auth.decorators import login_required
class ManagersChoiceField (forms.fields.ChoiceField):
def __init__(self, *args, **kwargs):
choices = []
choices.append(('', ugettext_lazy("Select a manager")))
currentUserOrganisationId = 1
if Session.objects.all()[0].session_key:
currentUserOrganisationId = FMSUser.objects.get(pk=getLoggedInUserId(Session.objects.all()[0].session_key)).organisation
managers = FMSUser.objects.filter(manager=True)
managers = managers.filter(organisation_id=currentUserOrganisationId)
for manager in managers:
choices.append((manager.pk,manager.first_name+manager.last_name))
super(ManagersChoiceField,self).__init__(choices,*args,**kwargs)
def clean(self, value):
super(ManagersChoiceField,self).clean(value)
try:
model = FMSUser.objects.get(pk=value)
except FMSUser.DoesNotExist:
raise ValidationError(self.error_messages['invalid_choice'])
return model
class ManagersListForm(forms.Form):
manager=ManagersChoiceField(label="")
|
from django import forms
from django_fixmystreet.fixmystreet.models import FMSUser, getLoggedInUserId
from django.contrib.auth.models import User
from django.conf import settings
from django.utils.translation import ugettext_lazy
from django.contrib.sessions.models import Session
class ManagersChoiceField (forms.fields.ChoiceField):
def __init__(self, *args, **kwargs):
# assemble the opt groups.
choices = []
choices.append(('', ugettext_lazy("Select a manager")))
currentUserOrganisationId = FMSUser.objects.get(pk=getLoggedInUserId(Session.objects.all()[0].session_key)).organisation
managers = FMSUser.objects.filter(manager=True)
managers = managers.filter(organisation_id=currentUserOrganisationId)
for manager in managers:
choices.append((manager.pk,manager.first_name+manager.last_name))
super(ManagersChoiceField,self).__init__(choices,*args,**kwargs)
def clean(self, value):
super(ManagersChoiceField,self).clean(value)
try:
model = FMSUser.objects.get(pk=value)
except FMSUser.DoesNotExist:
raise ValidationError(self.error_messages['invalid_choice'])
return model
class ManagersListForm(forms.Form):
manager=ManagersChoiceField(label="")
|
Increase the timeout to an absurd value
|
# Load in core dependencies
import code
import os
import sublime
# Set up constants
__dir__ = os.path.dirname(os.path.abspath(__file__))
def run():
# On every run, re-import the test class
# TODO: Determine if this is necessary
filepath = __dir__ + '/plugin_runner.py'
plugin_dict = {
'__dir__': __dir__,
'__file__': filepath,
'__name__': '%s.plugin_runner' % __package__,
'__package__': __package__,
'__builtins__': __builtins__,
}
# DEV: In Python 2.x, use execfile. In 3.x, use compile + exec.
# if getattr(__builtins__, 'execfile', None):
if sublime.version() < '3000':
execfile(filepath, plugin_dict, plugin_dict)
else:
f = open(filepath)
script = f.read()
interpretter = code.InteractiveInterpreter(plugin_dict)
interpretter.runcode(compile(script, filepath, 'exec'))
test = plugin_dict['Test']()
test.run(__dir__)
# TODO: Set timeout loop that checks if `run` has set a global variable
# TODO: This thought was along side a plugin hook so we can guarantee most plugins are loaded
sublime.set_timeout(run, 5000)
|
# Load in core dependencies
import code
import os
import sublime
# Set up constants
__dir__ = os.path.dirname(os.path.abspath(__file__))
def run():
# On every run, re-import the test class
# TODO: Determine if this is necessary
filepath = __dir__ + '/plugin_runner.py'
plugin_dict = {
'__dir__': __dir__,
'__file__': filepath,
'__name__': '%s.plugin_runner' % __package__,
'__package__': __package__,
'__builtins__': __builtins__,
}
# DEV: In Python 2.x, use execfile. In 3.x, use compile + exec.
# if getattr(__builtins__, 'execfile', None):
if sublime.version() < '3000':
execfile(filepath, plugin_dict, plugin_dict)
else:
f = open(filepath)
script = f.read()
interpretter = code.InteractiveInterpreter(plugin_dict)
interpretter.runcode(compile(script, filepath, 'exec'))
test = plugin_dict['Test']()
test.run(__dir__)
# TODO: Set timeout loop that checks if `run` has set a global variable
# TODO: This thought was along side a plugin hook so we can guarantee most plugins are loaded
sublime.set_timeout(run, 1000)
|
Add specific test scenario for pre-2.0
|
module.exports = {
scenarios: [
{
name: 'default',
dependencies: { }
},
{
name: 'pre-2',
dependencies: {
'ember': '1.13.9'
}
},
{
name: 'ember-release',
dependencies: {
'ember': 'components/ember#release'
},
resolutions: {
'ember': 'release'
}
},
{
name: 'ember-beta',
dependencies: {
'ember': 'components/ember#beta'
},
resolutions: {
'ember': 'beta'
}
},
{
name: 'ember-canary',
dependencies: {
'ember': 'components/ember#canary'
},
resolutions: {
'ember': 'canary'
}
}
]
};
|
module.exports = {
scenarios: [
{
name: 'default',
dependencies: { }
},
{
name: 'ember-release',
dependencies: {
'ember': 'components/ember#release'
},
resolutions: {
'ember': 'release'
}
},
{
name: 'ember-beta',
dependencies: {
'ember': 'components/ember#beta'
},
resolutions: {
'ember': 'beta'
}
},
{
name: 'ember-canary',
dependencies: {
'ember': 'components/ember#canary'
},
resolutions: {
'ember': 'canary'
}
}
]
};
|
Increase default search count to 12
Based off designer feedback
Change-Id: Icbccadb089a2ce650fdcfe4f0560aa5ef0087441
|
package org.wikipedia.search;
import org.json.JSONArray;
import org.mediawiki.api.json.Api;
import org.mediawiki.api.json.ApiResult;
import org.mediawiki.api.json.RequestBuilder;
import org.wikipedia.ApiTask;
import org.wikipedia.PageTitle;
import org.wikipedia.Site;
import org.wikipedia.concurrency.ExecutorService;
import java.util.ArrayList;
import java.util.List;
public class SearchArticlesTask extends ApiTask<List<PageTitle>> {
private final String prefix;
private final Site site;
public SearchArticlesTask(Api api, Site site, String prefix) {
super(ExecutorService.getSingleton().getExecutor(SearchArticlesTask.class, 4), api);
this.prefix = prefix;
this.site = site;
}
@Override
public RequestBuilder buildRequest(Api api) {
return api.action("opensearch").param("search", prefix).param("limit", "12");
}
@Override
public List<PageTitle> processResult(ApiResult result) throws Throwable {
JSONArray searchResults = result.asArray().optJSONArray(1);
ArrayList<PageTitle> pageTitles = new ArrayList<PageTitle>();
for (int i = 0; i < searchResults.length(); i++) {
pageTitles.add(new PageTitle(null, searchResults.optString(i), site));
}
return pageTitles;
}
}
|
package org.wikipedia.search;
import org.json.JSONArray;
import org.mediawiki.api.json.Api;
import org.mediawiki.api.json.ApiResult;
import org.mediawiki.api.json.RequestBuilder;
import org.wikipedia.ApiTask;
import org.wikipedia.PageTitle;
import org.wikipedia.Site;
import org.wikipedia.concurrency.ExecutorService;
import java.util.ArrayList;
import java.util.List;
public class SearchArticlesTask extends ApiTask<List<PageTitle>> {
private final String prefix;
private final Site site;
public SearchArticlesTask(Api api, Site site, String prefix) {
super(ExecutorService.getSingleton().getExecutor(SearchArticlesTask.class, 4), api);
this.prefix = prefix;
this.site = site;
}
@Override
public RequestBuilder buildRequest(Api api) {
return api.action("opensearch").param("search", prefix).param("limit", "5");
}
@Override
public List<PageTitle> processResult(ApiResult result) throws Throwable {
JSONArray searchResults = result.asArray().optJSONArray(1);
ArrayList<PageTitle> pageTitles = new ArrayList<PageTitle>();
for (int i = 0; i < searchResults.length(); i++) {
pageTitles.add(new PageTitle(null, searchResults.optString(i), site));
}
return pageTitles;
}
}
|
Make sure that organization new button goes to organization page
|
import React, {Component} from 'react'
import {connect} from 'react-redux'
import {httpRequestSelector} from 'gComponents/organizations/show/httpRequestSelector'
import {organizationMemberSelector} from 'gComponents/organizations/show/organizationMemberSelector'
import Card, {CardListElement} from 'gComponents/utility/card/index'
import {MemberAddForm} from '../shared/MemberAddForm/index'
import * as userOrganizationMembershipActions from 'gModules/userOrganizationMemberships/actions'
import {organization} from 'gEngine/engine'
export class LocalAddMembers extends Component {
render() {
const {organizationId} = this.props
return (
<div className='row'>
<div className='col-sm-7'>
<MemberAddForm organizationId={organizationId}/>
<br/>
<br/>
<a className='ui button green' href={organization.url({id: organizationId})}>Finish Registration </a>
</div>
<div className='col-sm-1'/>
<div className='col-sm-4'>
<div className='ui message'>
<h3> Organization Members </h3>
<p>Organization members will be able to see and edit all organization models.</p>
<p>As an organization admin, you will be able to invite, add, and remove members in the future.</p>
</div>
</div>
</div>
)
}
}
|
import React, {Component} from 'react'
import {connect} from 'react-redux'
import {httpRequestSelector} from 'gComponents/organizations/show/httpRequestSelector'
import {organizationMemberSelector} from 'gComponents/organizations/show/organizationMemberSelector'
import Card, {CardListElement} from 'gComponents/utility/card/index'
import {MemberAddForm} from '../shared/MemberAddForm/index'
import * as userOrganizationMembershipActions from 'gModules/userOrganizationMemberships/actions'
export class LocalAddMembers extends Component {
render() {
const {organizationId} = this.props
return (
<div className='row'>
<div className='col-sm-7'>
<MemberAddForm organizationId={organizationId}/>
<br/>
<br/>
<div className='ui button green'>Finish Registration </div>
</div>
<div className='col-sm-1'/>
<div className='col-sm-4'>
<div className='ui message'>
<h3> Organization Members </h3>
<p>Organization members will be able to see and edit all organization models.</p>
<p>As an organization admin, you will be able to invite, add, and remove members in the future.</p>
</div>
</div>
</div>
)
}
}
|
Fix broken test (new "countries" added to data)
|
<?php
class KeyValueTest extends \PHPUnit_Framework_TestCase
{
protected $maker;
public function setUp()
{
$this->maker = new PeterColes\Countries\Maker;
}
public function testDefaultSettings()
{
$keyValue = $this->maker->keyValue();
$this->assertEquals(255, $keyValue->count());
$this->assertEquals((object)[ 'key' => 'AF', 'value' => 'Afghanistan' ], $keyValue->first());
}
public function testAlternativeLocale()
{
$keyValue = $this->maker->keyValue('es');
$this->assertEquals((object)[ 'key' => 'AF', 'value' => 'Afganistán' ], $keyValue->first());
}
public function testAlternativeKeys()
{
$keyValue = $this->maker->keyValue(null, 'label', 'text');
$this->assertEquals((object)[ 'label' => 'ZW', 'text' => 'Zimbabwe' ], $keyValue->last());
}
}
|
<?php
class KeyValueTest extends \PHPUnit_Framework_TestCase
{
protected $maker;
public function setUp()
{
$this->maker = new PeterColes\Countries\Maker;
}
public function testDefaultSettings()
{
$keyValue = $this->maker->keyValue();
$this->assertEquals(253, $keyValue->count());
$this->assertEquals((object)[ 'key' => 'AF', 'value' => 'Afghanistan' ], $keyValue->first());
}
public function testAlternativeLocale()
{
$keyValue = $this->maker->keyValue('es');
$this->assertEquals((object)[ 'key' => 'AF', 'value' => 'Afganistán' ], $keyValue->first());
}
public function testAlternativeKeys()
{
$keyValue = $this->maker->keyValue(null, 'label', 'text');
$this->assertEquals((object)[ 'label' => 'ZW', 'text' => 'Zimbabwe' ], $keyValue->last());
}
}
|
CRM-1480: Create jobs to load files to database
|
<?php
namespace Oro\Bundle\TrackingBundle\Tests\Unit\DependencyInjection;
use Oro\Bundle\TrackingBundle\DependencyInjection\OroTrackingExtension;
class OroBundleTrackingExtensionTest extends \PHPUnit_Framework_TestCase
{
/**
* @var OroTrackingExtension
*/
protected $extension;
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
protected $container;
protected function setUp()
{
$this->container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')
->disableOriginalConstructor()
->getMock();
$this->extension = new OroTrackingExtension();
}
public function testLoad()
{
$this->container->expects($this->once())
->method('prependExtensionConfig')
->with('oro_tracking', $this->isType('array'));
$this->extension->load([], $this->container);
}
}
|
<?php
namespace Oro\Bundle\TrackingBundle\Tests\Unit\DependencyInjection;
use Oro\Bundle\TrackingBundle\DependencyInjection\OroTrackingExtension;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class OroBundleTrackingExtensionTest extends \PHPUnit_Framework_TestCase
{
/**
* @var OroTrackingExtension
*/
protected $extension;
/**
* @var ContainerBuilder
*/
protected $container;
protected function setUp()
{
$this->container = new ContainerBuilder();
$this->extension = new OroTrackingExtension();
}
public function testLoad()
{
$this->extension->load([], $this->container);
}
}
|
typing: Use `getUsersById` for fast user search.
part of #3339.
|
/* @flow strict-local */
import { createSelector } from 'reselect';
import type { Narrow, Selector, User } from '../types';
import { getTyping } from '../directSelectors';
import { getOwnEmail } from '../account/accountsSelectors';
import { isPrivateOrGroupNarrow } from '../utils/narrow';
import { normalizeRecipients } from '../utils/recipient';
import { NULL_ARRAY, NULL_USER } from '../nullObjects';
import { getUsersById } from '../users/userSelectors';
export const getCurrentTypingUsers: Selector<$ReadOnlyArray<User>, Narrow> = createSelector(
(state, narrow) => narrow,
state => getTyping(state),
state => getUsersById(state),
state => getOwnEmail(state),
(narrow, typing, usersById, ownEmail): User[] => {
if (!isPrivateOrGroupNarrow(narrow)) {
return NULL_ARRAY;
}
const recipients = narrow[0].operand.split(',').map(email => ({ email }));
const normalizedRecipients = normalizeRecipients(recipients);
const currentTyping = typing[normalizedRecipients];
if (!currentTyping || !currentTyping.userIds) {
return NULL_ARRAY;
}
return currentTyping.userIds.map(userId => usersById.get(userId) || NULL_USER);
},
);
|
/* @flow strict-local */
import { createSelector } from 'reselect';
import type { Narrow, Selector, User } from '../types';
import { getTyping, getUsers } from '../directSelectors';
import { getOwnEmail } from '../account/accountsSelectors';
import { getUserById } from '../users/userHelpers';
import { isPrivateOrGroupNarrow } from '../utils/narrow';
import { normalizeRecipients } from '../utils/recipient';
import { NULL_ARRAY } from '../nullObjects';
export const getCurrentTypingUsers: Selector<$ReadOnlyArray<User>, Narrow> = createSelector(
(state, narrow) => narrow,
state => getTyping(state),
state => getUsers(state),
state => getOwnEmail(state),
(narrow, typing, users, ownEmail): User[] => {
if (!isPrivateOrGroupNarrow(narrow)) {
return NULL_ARRAY;
}
const recipients = narrow[0].operand.split(',').map(email => ({ email }));
const normalizedRecipients = normalizeRecipients(recipients);
const currentTyping = typing[normalizedRecipients];
if (!currentTyping || !currentTyping.userIds) {
return NULL_ARRAY;
}
return currentTyping.userIds.map(userId => getUserById(users, userId));
},
);
|
Remove undefined import in coach plugin.
|
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from kolibri.core.auth.constants.user_kinds import COACH
from kolibri.core.hooks import NavigationHook
from kolibri.core.hooks import RoleBasedRedirectHook
from kolibri.core.webpack import hooks as webpack_hooks
from kolibri.plugins.base import KolibriPluginBase
class Coach(KolibriPluginBase):
untranslated_view_urls = "api_urls"
translated_view_urls = "urls"
class CoachRedirect(RoleBasedRedirectHook):
role = COACH
@property
def url(self):
return self.plugin_url(Coach, "coach")
class CoachNavItem(NavigationHook, webpack_hooks.WebpackBundleHook):
unique_slug = "coach_side_nav"
class CoachAsset(webpack_hooks.WebpackBundleHook):
unique_slug = "coach_module"
|
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from . import hooks
from kolibri.core.auth.constants.user_kinds import COACH
from kolibri.core.hooks import NavigationHook
from kolibri.core.hooks import RoleBasedRedirectHook
from kolibri.core.webpack import hooks as webpack_hooks
from kolibri.plugins.base import KolibriPluginBase
class Coach(KolibriPluginBase):
untranslated_view_urls = "api_urls"
translated_view_urls = "urls"
class CoachRedirect(RoleBasedRedirectHook):
role = COACH
@property
def url(self):
return self.plugin_url(Coach, "coach")
class CoachNavItem(NavigationHook, webpack_hooks.WebpackBundleHook):
unique_slug = "coach_side_nav"
class CoachAsset(webpack_hooks.WebpackBundleHook):
unique_slug = "coach_module"
class CoachInclusionHook(hooks.CoachSyncHook):
bundle_class = CoachAsset
|
ui: Check the return value of ReleaseDC()
|
// Copyright 2016 Hajime Hoshi
//
// 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.
// +build !js
package ui
// #cgo LDFLAGS: -lgdi32
//
// #include <windows.h>
//
// static char* getDPI(int* dpi) {
// HDC dc = GetWindowDC(0);
// *dpi = GetDeviceCaps(dc, LOGPIXELSX);
// if (!ReleaseDC(0, dc)) {
// return "ReleaseDC failed";
// }
// return "";
// }
import "C"
func deviceScale() float64 {
dpi := C.int(0)
if errmsg := C.GoString(C.getDPI(&dpi)); errmsg != "" {
panic(errmsg)
}
return float64(dpi) / 96
}
func glfwScale() float64 {
return deviceScale()
}
|
// Copyright 2016 Hajime Hoshi
//
// 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.
// +build !js
package ui
// #cgo LDFLAGS: -lgdi32
//
// #include <windows.h>
//
// static int getDPI() {
// HDC dc = GetWindowDC(0);
// int dpi = GetDeviceCaps(dc, LOGPIXELSX);
// ReleaseDC(0, dc);
// return dpi;
// }
import "C"
func deviceScale() float64 {
dpi := int(C.getDPI())
return float64(dpi) / 96
}
func glfwScale() float64 {
return deviceScale()
}
|
Add hashCode method to starter solution
|
class Rational {
Rational(int numerator, int denominator) {
throw new UnsupportedOperationException("Delete this statement and write your own implementation.");
}
int getNumerator() {
throw new UnsupportedOperationException("Delete this statement and write your own implementation.");
}
int getDenominator() {
throw new UnsupportedOperationException("Delete this statement and write your own implementation.");
}
@Override
public String toString() {
return String.format("%d/%d", this.getNumerator(), this.getDenominator());
}
@Override
public boolean equals(Object obj) {
if (obj == null || !this.getClass().isAssignableFrom(obj.getClass())) {
return false;
}
Rational other = (Rational) obj;
return this.getNumerator() == other.getNumerator()
&& this.getDenominator() == other.getDenominator();
}
@Override
public int hashCode() {
int prime = 31;
int result = 1;
result = prime * result + this.getNumerator();
result = prime * result + this.getDenominator();
return result;
}
}
|
class Rational {
Rational(int numerator, int denominator) {
throw new UnsupportedOperationException("Delete this statement and write your own implementation.");
}
int getNumerator() {
throw new UnsupportedOperationException("Delete this statement and write your own implementation.");
}
int getDenominator() {
throw new UnsupportedOperationException("Delete this statement and write your own implementation.");
}
@Override
public String toString() {
return String.format("%d/%d", this.getNumerator(), this.getDenominator());
}
@Override
public boolean equals(Object obj) {
if (obj == null || !this.getClass().isAssignableFrom(obj.getClass())) {
return false;
}
Rational other = (Rational) obj;
return this.getNumerator() == other.getNumerator()
&& this.getDenominator() == other.getDenominator();
}
}
|
Remove warning for existing output directory.
In our configuration puppet will manage the output directory, so it
is expected behavior for it to exist, removing warning. Also
switching to distutils.dir_util copy_tree since that allows for
copying of required supporting files into an existing output
directory.
Change-Id: I38b2c6ec47fd61814554a4b5007a83553b05aeb2
Reviewed-on: https://review.openstack.org/20647
Approved: Dan Prince <62cccc0004df0a8e3c343b26b69e434f6aa9711c@redhat.com>
Reviewed-by: Dan Prince <62cccc0004df0a8e3c343b26b69e434f6aa9711c@redhat.com>
Tested-by: Jenkins
|
import os
import html_helper
from Cheetah.Template import Template
from distutils.dir_util import copy_tree
def prep_out_dir(out_dir='out_report'):
src_dir = os.path.dirname(__file__)
report_files_dir = os.path.join(src_dir, 'report_files')
copy_tree(report_files_dir, out_dir)
def create_report(name_space={}):
filename = os.path.join(os.path.dirname(__file__), 'report.html')
report_text = open(filename).read()
name_space['helper'] = html_helper
t = Template(report_text, searchList=[name_space])
out_dir = 'out_report'
prep_out_dir(out_dir)
out_file = open(os.path.join(out_dir, 'index.html'), "w")
out_file.write(str(t))
out_file.close()
|
import os
import shutil
import html_helper
from Cheetah.Template import Template
def prep_out_dir(out_dir='out_report'):
src_dir = os.path.dirname(__file__)
report_files_dir = os.path.join(src_dir, 'report_files')
if os.path.exists(out_dir):
print 'WARNING: output directory "%s" already exists' % out_dir
else:
shutil.copytree(report_files_dir, out_dir)
def create_report(name_space={}):
filename = os.path.join(os.path.dirname(__file__), 'report.html')
report_text = open(filename).read()
name_space['helper'] = html_helper
t = Template(report_text, searchList=[name_space])
out_dir = 'out_report'
prep_out_dir(out_dir)
out_file = open(os.path.join(out_dir, 'index.html'), "w")
out_file.write(str(t))
out_file.close()
|
Fix variable store breaking crash
|
package org.cyclops.integrateddynamics.network;
import org.cyclops.cyclopscore.datastructure.DimPos;
import org.cyclops.integrateddynamics.api.network.IPartNetwork;
import org.cyclops.integrateddynamics.core.network.TileNetworkElement;
import org.cyclops.integrateddynamics.tileentity.TileVariablestore;
/**
* Network element for variable stores.
* @author rubensworks
*/
public class VariablestoreNetworkElement extends TileNetworkElement<TileVariablestore> {
public VariablestoreNetworkElement(DimPos pos) {
super(pos);
}
@Override
public boolean onNetworkAddition(IPartNetwork network) {
return network.addVariableContainer(getPos());
}
@Override
public void onNetworkRemoval(IPartNetwork network) {
network.removeVariableContainer(getPos());
}
@Override
public int getConsumptionRate() {
return 4;
}
@Override
protected Class<TileVariablestore> getTileClass() {
return TileVariablestore.class;
}
}
|
package org.cyclops.integrateddynamics.network;
import org.cyclops.cyclopscore.datastructure.DimPos;
import org.cyclops.integrateddynamics.api.network.IPartNetwork;
import org.cyclops.integrateddynamics.core.network.TileNetworkElement;
import org.cyclops.integrateddynamics.tileentity.TileVariablestore;
/**
* Network element for variable stores.
* @author rubensworks
*/
public class VariablestoreNetworkElement extends TileNetworkElement<TileVariablestore> {
public VariablestoreNetworkElement(DimPos pos) {
super(pos);
}
@Override
public boolean onNetworkAddition(IPartNetwork network) {
return network.addVariableContainer(getPos());
}
@Override
public void onNetworkRemoval(IPartNetwork network) {
network.removeVariableContainer(getPos());
}
@Override
public int getConsumptionRate() {
return 4;
}
@Override
protected Class<TileVariablestore> getTileClass() {
return null;
}
}
|
Use just the default exports
|
import color from "./src/color";
import rgb from "./src/rgb";
import hsl from "./src/hsl";
import lab from "./src/lab";
import hcl from "./src/hcl";
import cubehelix from "./src/cubehelix";
import interpolateRgb from "./src/interpolateRgb";
import interpolateHsl from "./src/interpolateHsl";
import interpolateHslLong from "./src/interpolateHslLong";
import interpolateLab from "./src/interpolateLab";
import interpolateHcl from "./src/interpolateHcl";
import interpolateHclLong from "./src/interpolateHclLong";
import interpolateCubehelixGamma from "./src/interpolateCubehelixGamma";
import interpolateCubehelixGammaLong from "./src/interpolateCubehelixGammaLong";
export var interpolateCubehelix = interpolateCubehelixGamma(1);
export var interpolateCubehelixLong = interpolateCubehelixGammaLong(1);
export {
color,
rgb,
hsl,
lab,
hcl,
cubehelix,
interpolateRgb,
interpolateHsl,
interpolateHslLong,
interpolateLab,
interpolateHcl,
interpolateHclLong,
interpolateCubehelixGamma,
interpolateCubehelixGammaLong
};
|
import {default as color, Color} from "./src/color";
import {default as rgb, Rgb} from "./src/rgb";
import {default as hsl, Hsl} from "./src/hsl";
import {default as lab, Lab} from "./src/lab";
import {default as hcl, Hcl} from "./src/hcl";
import {default as cubehelix, Cubehelix} from "./src/cubehelix";
import interpolateRgb from "./src/interpolateRgb";
import interpolateHsl from "./src/interpolateHsl";
import interpolateHslLong from "./src/interpolateHslLong";
import interpolateLab from "./src/interpolateLab";
import interpolateHcl from "./src/interpolateHcl";
import interpolateHclLong from "./src/interpolateHclLong";
import interpolateCubehelixGamma from "./src/interpolateCubehelixGamma";
import interpolateCubehelixGammaLong from "./src/interpolateCubehelixGammaLong";
export var interpolateCubehelix = interpolateCubehelixGamma(1);
export var interpolateCubehelixLong = interpolateCubehelixGammaLong(1);
export {
color,
rgb,
hsl,
lab,
hcl,
cubehelix,
interpolateRgb,
interpolateHsl,
interpolateHslLong,
interpolateLab,
interpolateHcl,
interpolateHclLong,
interpolateCubehelixGamma,
interpolateCubehelixGammaLong
};
|
Add margin between open job posting rows.
|
import { Component, PropTypes } from 'react'
import {Link} from 'react-router'
class JobListing extends Component {
static propTypes: {
title: PropTypes.string.isRequired,
description: PropTypes.string.isRequired,
url: PropTypes.string.isRequired
}
constructor(props) {
super(props)
}
render() {
return (
<div className="row mb-3">
<div className="col-md-6">
{this.props.title}
</div>
<div className="col-md-6">
<Link to={this.props.url} target="_blank"
className="btn btn-primary btn-sm">
Read More
</Link>
</div>
</div>
)
}
}
export default JobListing
|
import { Component, PropTypes } from 'react'
import {Link} from 'react-router'
class JobListing extends Component {
static propTypes: {
title: PropTypes.string.isRequired,
description: PropTypes.string.isRequired,
url: PropTypes.string.isRequired
}
constructor(props) {
super(props)
}
render() {
return (
<div className="row m-b-1">
<div className="col-md-6">
{this.props.title}
</div>
<div className="col-md-6">
<Link to={this.props.url} target="_blank"
className="btn btn-primary btn-sm">
Read More
</Link>
</div>
</div>
)
}
}
export default JobListing
|
Change to exists instead of catching DoesNotExist exception.
|
# -*- coding: utf8 -*-
from django.conf import settings
from holonet.mappings.helpers import clean_address, split_address
from .models import DomainBlacklist, DomainWhitelist, SenderBlacklist, SenderWhitelist
def is_blacklisted(sender):
sender = clean_address(sender)
prefix, domain = split_address(sender)
if DomainBlacklist.objects.filter(domain=domain).exists():
return True
if SenderBlacklist.objects.filter(sender=sender).exists():
return True
return False
def is_not_whitelisted(sender):
sender = clean_address(sender)
prefix, domain = split_address(sender)
if settings.SENDER_WHITELIST_ENABLED:
if SenderWhitelist.objects.filter(sender=sender).exists():
return False
if settings.DOMAIN_WHITELIST_ENABLED:
if DomainWhitelist.objects.filter(domain=domain).exists():
return False
return bool(settings.SENDER_WHITELIST_ENABLED or settings.DOMAIN_WHITELIST_ENABLED)
|
# -*- coding: utf8 -*-
from django.conf import settings
from holonet.mappings.helpers import clean_address, split_address
from .models import DomainBlacklist, DomainWhitelist, SenderBlacklist, SenderWhitelist
def is_blacklisted(sender):
sender = clean_address(sender)
prefix, domain = split_address(sender)
try:
DomainBlacklist.objects.get(domain=domain)
return True
except DomainBlacklist.DoesNotExist:
pass
try:
SenderBlacklist.objects.get(sender=sender)
return True
except SenderBlacklist.DoesNotExist:
pass
return False
def is_not_whitelisted(sender):
sender = clean_address(sender)
prefix, domain = split_address(sender)
if settings.SENDER_WHITELIST_ENABLED:
try:
SenderWhitelist.objects.get(sender=sender)
return False
except SenderWhitelist.DoesNotExist:
pass
if settings.DOMAIN_WHITELIST_ENABLED:
try:
DomainWhitelist.objects.get(domain=domain)
return False
except DomainWhitelist.DoesNotExist:
pass
return bool(settings.SENDER_WHITELIST_ENABLED or settings.DOMAIN_WHITELIST_ENABLED)
|
Load Vue globals before app
|
import Vue from 'vue'
import VueFire from 'vuefire'
import App from './App'
import 'jquery-ui/jquery-ui.min.js'
// import imagesLoaded from 'imagesloaded'
// imagesLoaded.makeJQueryPlugin($)
import 'semantic-ui-css/semantic.js'
import 'semantic-ui-css/semantic.css'
// import marked from 'marked'
Vue.use(VueFire)
// Register a global custom directive called v-dropdown
Vue.directive('dropdown', {
bind (el) {
$(el).dropdown()
},
unbind (el) {
$(el).dropdown('destroy')
}
})
Vue.filter('capatalise', (text) => {
return text[0].toUpperCase() + text.slice(1)
})
Vue.filter('formatDate', (value) => {
var date = new Date(value)
return date.getDate() + '/' + date.getMonth() + '/' + date.getFullYear()
})
console.log('NEWT!')
/* eslint-disable no-new */
new Vue({
el: '#app',
template: '<App/>',
components: { App }
})
|
import Vue from 'vue'
import VueFire from 'vuefire'
import App from './App'
import 'jquery-ui/jquery-ui.min.js'
import imagesLoaded from 'imagesloaded'
imagesLoaded.makeJQueryPlugin($)
import 'semantic-ui-css/semantic.js'
import 'semantic-ui-css/semantic.css'
// import marked from 'marked'
Vue.use(VueFire)
console.log('NEWT!')
/* eslint-disable no-new */
new Vue({
el: '#app',
template: '<App/>',
components: { App }
})
// Register a global custom directive called v-dropdown
Vue.directive('dropdown', {
bind (el) {
$(el).dropdown()
},
unbind (el) {
$(el).dropdown('destroy')
}
})
Vue.filter('capatalise', (text) => {
return text[0].toUpperCase() + text.slice(1)
})
Vue.filter('formatDate', (value) => {
var date = new Date(value)
return date.getDate() + '/' + date.getMonth() + '/' + date.getFullYear()
})
|
Apply jscs to server code
Atom's jscs-fixer automatically fixed some problems: now all lines have a tab
indentation and statements are well spaced. Google's preset also converts all
double quotes into single quotes unless it's pure JSON.
|
Jobs = new Mongo.Collection('jobs'); //both on client and server
Applications = new Mongo.Collection('applications');
// added repoz channel
Meteor.startup(function() {
// console.log('Jobs.remove({})');
// Jobs.remove({});
if (Jobs.find({}).count() == 0) {
console.log('job count == ', Jobs.find({}).count(), 'inserting jobs');
Jobs.insert({_id: '0', title: 'Select a job position...'});
Jobs.insert({_id: '1', title: 'Haiti Village Photographer'});
Jobs.insert({_id: '2', title: 'Rapallo On The Beach'});
} else {
console.log('server/getreel.js:', 'job count > 0 (', Jobs.find({}).count(), '): no insert needed');
}
});
Meteor.methods({
apply: function(args) {
if (!Meteor.userId()) {
throw new Meteor.Error('not-authorized');
}
console.log(args);
Applications.insert({
createdAt: new Date(),
applicant: Meteor.userId(),
firstname: args.firstname,
lastname: args.lastname,
job: args.job,
resume: args.resume,
videofile: args.videofile,
videolink: args.videolink
});
}
});
|
Jobs = new Mongo.Collection('jobs'); //both on client and server
Applications = new Mongo.Collection('applications');
// added repoz channel
Meteor.startup(function() {
// console.log('Jobs.remove({})');
// Jobs.remove({});
if(Jobs.find({}).count()==0) {
console.log("job count == ", Jobs.find({}).count(), "inserting jobs");
Jobs.insert({_id:'0', title:'Select a job position...'});
Jobs.insert({_id:'1', title:'Haiti Village Photographer'});
Jobs.insert({_id:'2', title:'Rapallo On The Beach'});
} else {
console.log('server/getreel.js:', 'job count > 0 (', Jobs.find({}).count(), '): no insert needed');
}
});
Meteor.methods({
apply: function(args) {
if (!Meteor.userId()) {
throw new Meteor.Error("not-authorized");
}
console.log(args);
Applications.insert({
createdAt: new Date(),
applicant: Meteor.userId(),
firstname: args.firstname,
lastname: args.lastname,
job: args.job,
resume: args.resume,
videofile: args.videofile,
videolink: args.videolink
});
}
});
|
Add correct dependencies to gulp tasks
|
var gulp = require('gulp');
var less = require('gulp-less');
var exec = require('child_process').exec;
var sourcemaps = require('gulp-sourcemaps');
var csso = require('gulp-csso');
var rename = require('gulp-rename');
function run(command) {
var child = exec(command);
child.stdout.pipe(process.stdout);
child.stderr.pipe(process.stderr);
process.on('exit', function(code) {
if (child.exit) { child.exit(code); }
});
child.on('exit', function(code) {
process.exit(code);
});
}
gulp.task('less', function() {
return gulp.src('public/less/main.less')
.pipe(sourcemaps.init())
.pipe(less())
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('public/css'));
});
gulp.task('cssmin', ['less'], function() {
return gulp.src('public/css/main.css')
.pipe(csso())
.pipe(rename({
suffix: '.min'
}))
.pipe(gulp.dest('public/css'));
});
gulp.task('watch', function() {
run('npm run watchify');
run('npm run watchify-test');
gulp.watch('public/less/**/*.less', ['less']);
});
gulp.task('dev', ['default'], function() {
run('npm start');
});
gulp.task('css', ['less', 'cssmin']);
gulp.task('default', ['less', 'watch']);
|
var gulp = require('gulp');
var less = require('gulp-less');
var exec = require('child_process').exec;
var sourcemaps = require('gulp-sourcemaps');
var csso = require('gulp-csso');
var rename = require('gulp-rename');
function run(command) {
var child = exec(command);
child.stdout.pipe(process.stdout);
child.stderr.pipe(process.stderr);
process.on('exit', function(code) {
if (child.exit) { child.exit(code); }
});
child.on('exit', function(code) {
process.exit(code);
});
}
gulp.task('less', function() {
gulp.src('public/less/main.less')
.pipe(sourcemaps.init())
.pipe(less())
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('public/css'));
});
gulp.task('cssmin', function() {
gulp.src('public/css/main.css')
.pipe(csso())
.pipe(rename({
suffix: '.min'
}))
.pipe(gulp.dest('public/css'));
});
gulp.task('watch', function() {
run('npm run watchify');
run('npm run watchify-test');
gulp.watch('public/less/**/*.less', ['less']);
});
gulp.task('dev', ['default'], function() {
run('npm start');
});
gulp.task('css', ['less', 'cssmin']);
gulp.task('default', ['less', 'watch']);
|
Add refines to getClassDeps and prepend any deps with no package with 'foam.core.'
|
foam.CLASS({
package: 'foam.apploader',
name: 'ModelRefines',
refines: 'foam.core.Model',
methods: [
{
name: 'getClassDeps',
code: function() {
var deps = this.requires ?
this.requires.map(function(r) { return r.path }) :
[];
deps = deps.concat(this.implements ?
this.implements.map(function(i) { return i.path }) :
[]);
if ( this.extends ) deps.push(this.extends);
if ( this.refines ) deps.push(this.refines);
return deps.map(function(d) {
if ( d.indexOf('.') == -1 ) return 'foam.core.' + d;
return d;
});
return deps;
}
},
],
});
|
foam.CLASS({
package: 'foam.apploader',
name: 'ModelRefines',
refines: 'foam.core.Model',
methods: [
{
name: 'getClassDeps',
code: function() {
var deps = this.requires ?
this.requires.map(function(r) { return r.path }) :
[];
deps = deps.concat(this.implements ?
this.implements.map(function(i) { return i.path }) :
[]);
if ( this.extends ) deps.push(this.extends);
return deps;
}
},
],
});
|
Add ability to disable frame evaluation
(cherry picked from commit 6cd89d0)
|
import os
import sys
IS_PY36_OR_OLDER = False
if (sys.version_info[0] == 3 and sys.version_info[1] >= 6) or sys.version_info[0] > 3:
IS_PY36_OR_OLDER = True
set_frame_eval = None
stop_frame_eval = None
use_frame_eval = os.environ.get('PYDEVD_USE_FRAME_EVAL', None)
if use_frame_eval == 'NO':
frame_eval_func, stop_frame_eval = None, None
else:
if IS_PY36_OR_OLDER:
try:
from _pydevd_frame_eval.pydevd_frame_evaluator import frame_eval_func, stop_frame_eval
except ImportError:
from _pydev_bundle.pydev_monkey import log_error_once
dirname = os.path.dirname(__file__)
log_error_once("warning: Debugger speedups for Python 3.6 not found. Run '\"%s\" \"%s\" build_ext --inplace' to build." % (
sys.executable, os.path.join(dirname, 'setup.py')))
|
import os
import sys
IS_PY36_OR_OLDER = False
if (sys.version_info[0] == 3 and sys.version_info[1] >= 6) or sys.version_info[0] > 3:
IS_PY36_OR_OLDER = True
set_frame_eval = None
stop_frame_eval = None
if IS_PY36_OR_OLDER:
try:
from _pydevd_frame_eval.pydevd_frame_evaluator import frame_eval_func, stop_frame_eval
except ImportError:
from _pydev_bundle.pydev_monkey import log_error_once
dirname = os.path.dirname(__file__)
log_error_once("warning: Debugger speedups for Python 3.6 not found. Run '\"%s\" \"%s\" build_ext --inplace' to build." % (
sys.executable, os.path.join(dirname, 'setup.py')))
|
Support python 2 with io.open
|
import io
import os.path
import yaml
from sphinx.util.osutil import ensuredir
def create_directory(app):
''' Creates the yaml directory if necessary '''
app.env.yaml_dir = os.path.join(app.builder.confdir, '_build', 'yaml')
ensuredir(app.env.yaml_dir)
def file_path(env, name):
''' Creates complete yaml file path for a name '''
return os.path.join(
env.yaml_dir,
name if name.endswith('.yaml') else (name + '.yaml')
)
def write(file_path, data_dict):
''' Writes dictionary into a yaml file '''
with io.open(file_path, 'w', encoding='utf-8') as f:
f.write(yaml.dump(data_dict, default_flow_style=False, allow_unicode=True))
def read(file_path):
''' Reads dictionary from a yaml file '''
with io.open(file_path, 'r', encoding='utf-8') as f:
return yaml.load(f.read())
|
import os.path
import yaml
from sphinx.util.osutil import ensuredir
def create_directory(app):
''' Creates the yaml directory if necessary '''
app.env.yaml_dir = os.path.join(app.builder.confdir, '_build', 'yaml')
ensuredir(app.env.yaml_dir)
def file_path(env, name):
''' Creates complete yaml file path for a name '''
return os.path.join(
env.yaml_dir,
name if name.endswith('.yaml') else (name + '.yaml')
)
def write(file_path, data_dict):
''' Writes dictionary into a yaml file '''
with open(file_path, 'w') as f:
f.write(yaml.dump(data_dict, default_flow_style=False, allow_unicode=True))
def read(file_path):
''' Reads dictionary from a yaml file '''
with open(file_path, 'r') as f:
return yaml.load(f.read())
|
Use fully qualified class name instead of string
|
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
$this->app->bind(
'Illuminate\Contracts\Auth\Registrar',
'App\Services\Registrar'
);
if ($this->app->environment() == 'local') {
$this->app->register(\Laracasts\Generators\GeneratorsServiceProvider::class);
$this->app->register(\Barryvdh\Debugbar\ServiceProvider::class);
$this->app->register(\Potsky\LaravelLocalizationHelpers\LaravelLocalizationHelpersServiceProvider::class);
}
if (env('ROLLBAR_TOKEN', false)) {
$this->app->register(\Jenssegers\Rollbar\RollbarServiceProvider::class);
}
}
}
|
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Jenssegers\Rollbar\RollbarServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
$this->app->bind(
'Illuminate\Contracts\Auth\Registrar',
'App\Services\Registrar'
);
if ($this->app->environment() == 'local') {
$this->app->register('Laracasts\Generators\GeneratorsServiceProvider');
$this->app->register('Barryvdh\Debugbar\ServiceProvider');
$this->app->register('Potsky\LaravelLocalizationHelpers\LaravelLocalizationHelpersServiceProvider');
}
if (env('ROLLBAR_TOKEN', false)) {
$this->app->register(RollbarServiceProvider::class);
}
}
}
|
Change the order of the subcommands.
|
from __future__ import absolute_import, print_function
__author__ = 'katharine'
import argparse
import logging
import sys
from .commands.base import register_children
from .commands.sdk import build, create
from .commands import install, logs, screenshot, timeline, account, repl
from .commands.sdk import convert, emulator
from .exceptions import ToolError
from .sdk import sdk_version
def run_tool(args=None):
logging.basicConfig()
parser = argparse.ArgumentParser(description="Pebble Tool", prog="pebble")
parser.add_argument("--version", action="version", version="Pebble SDK {}".format(sdk_version()))
register_children(parser)
args = parser.parse_args(args)
try:
args.func(args)
except ToolError as e:
print(str(e))
sys.exit(1)
|
from __future__ import absolute_import, print_function
__author__ = 'katharine'
import argparse
import logging
import sys
from .commands.base import register_children
from .commands import repl, install, screenshot, logs, account, timeline
from .commands.sdk import build, emulator, create, convert
from .exceptions import ToolError
from .sdk import sdk_version
def run_tool(args=None):
logging.basicConfig()
parser = argparse.ArgumentParser(description="Pebble Tool", prog="pebble")
parser.add_argument("--version", action="version", version="Pebble SDK {}".format(sdk_version()))
register_children(parser)
args = parser.parse_args(args)
try:
args.func(args)
except ToolError as e:
print(str(e))
sys.exit(1)
|
eslint: Allow dangling commas and warn about console statements
|
module.exports = {
env: {
browser: true,
es2021: true,
},
extends: [
'standard',
],
parserOptions: {
ecmaVersion: 12,
sourceType: 'module',
},
plugins: [
'svelte3',
],
overrides: [
{
files: ['**/*.svelte'],
processor: 'svelte3/svelte3',
rules: {
'import/first': ['off', 'always'],
'no-multiple-empty-lines': ['error', { max: 1, maxBOF: 2, maxEOF: 0 }],
},
},
],
rules: {
'comma-dangle': ['off', 'always'],
'indent': ['error', 4],
'no-console': ['warn', {}],
}
}
|
module.exports = {
env: {
browser: true,
es2021: true,
},
extends: [
'standard',
],
parserOptions: {
ecmaVersion: 12,
sourceType: 'module',
},
plugins: [
'svelte3',
],
overrides: [
{
files: ['**/*.svelte'],
processor: 'svelte3/svelte3',
rules: {
'import/first': ['off', 'always'],
'no-multiple-empty-lines': ['error', { max: 1, maxBOF: 2, maxEOF: 0 }],
},
},
],
rules: {
indent: ['error', 4],
}
}
|
[Enhancement] Add the interface name for comodity
|
package toscalib
type Playbook struct {
AdjacencyMatrix Matrix
Index map[int]Play
Inputs map[string]PropertyDefinition
Outputs map[string]Output
}
type Play struct {
NodeTemplate NodeTemplate
InterfaceName string
OperationName string
}
func GeneratePlaybook(s ServiceTemplateDefinition) Playbook {
var e Playbook
i := 0
index := make(map[int]Play, 0)
for _, node := range s.TopologyTemplate.NodeTemplates {
for intfn, intf := range node.Interfaces {
for op, _ := range intf.Operations {
index[i] = Play{node, intfn, op}
i += 1
}
}
}
e.Index = index
e.Inputs = s.TopologyTemplate.Inputs
e.Outputs = s.TopologyTemplate.Outputs
return e
}
|
package toscalib
type Playbook struct {
AdjacencyMatrix Matrix
Index map[int]Play
Inputs map[string]PropertyDefinition
Outputs map[string]Output
}
type Play struct {
NodeTemplate NodeTemplate
OperationName string
}
func GeneratePlaybook(s ServiceTemplateDefinition) Playbook {
var e Playbook
i := 0
index := make(map[int]Play, 0)
for _, node := range s.TopologyTemplate.NodeTemplates {
for _, intf := range node.Interfaces {
for op, _ := range intf.Operations {
index[i] = Play{node, op}
i += 1
}
}
}
e.Index = index
e.Inputs = s.TopologyTemplate.Inputs
e.Outputs = s.TopologyTemplate.Outputs
return e
}
|
Handle other links in content view to browser
|
package com.erakk.lnreader.helper;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.erakk.lnreader.Constants;
import com.erakk.lnreader.DisplayImageActivity;
public class BakaTsukiWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// if (Uri.parse(url).getHost().equals("www.example.com")) {
// // This is my web site, so do not override; let my WebView load the page
// return false;
// }
Log.d("shouldOverrideUrlLoading", url);
Context context = view.getContext();
// if image file
if(url.contains("title=File:")) {
Intent intent = new Intent(context, DisplayImageActivity.class);
intent.putExtra(Constants.EXTRA_IMAGE_URL, url);
context.startActivity(intent);
}
else {
//Toast.makeText(context, "Url: " + url, Toast.LENGTH_SHORT).show();
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
context.startActivity(browserIntent);
return true;
}
return true;
}
}
|
package com.erakk.lnreader.helper;
import com.erakk.lnreader.Constants;
import com.erakk.lnreader.DisplayImageActivity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class BakaTsukiWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// if (Uri.parse(url).getHost().equals("www.example.com")) {
// // This is my web site, so do not override; let my WebView load the page
// return false;
// }
Log.d("shouldOverrideUrlLoading", url);
Context context = view.getContext();
// if image file
if(url.contains("title=File:")) {
Intent intent = new Intent(context, DisplayImageActivity.class);
intent.putExtra(Constants.EXTRA_IMAGE_URL, url);
context.startActivity(intent);
}
else {
Toast.makeText(context, "Url: " + url, Toast.LENGTH_SHORT).show();
}
return true;
}
}
|
Fix spelling in help text
|
#!/usr/bin/env node
"use strict";
var backup = require("../lib/backup");
var ArgumentParser = require('argparse').ArgumentParser;
var pkg = require('../package.json');
function main(argv) {
var parser = new ArgumentParser({
version: pkg.version,
addHelp: true,
description: pkg.description
});
parser.addArgument("username", {
help: "The github username to backup."
});
parser.addArgument("path", {
help: "The path where to backup the repositories to."
});
parser.addArgument(['--include', '-i'], {
defaultValue: 'user,org,starred',
type: function(i) { return i.split(","); },
help: "Choose which repositories to backup. You can " +
"select \"user\", \"org\" and \"starred\", and any combination" +
" separated by a comma"
});
parser.addArgument(['--dry-run', '-n'], {
action: "storeTrue",
help: "If set, no action is actually performed."
});
var args = parser.parseArgs();
backup.publicUserRepos(args).catch(function(err) {
console.error("Unhandled error:", err);
}).done();
}
main();
|
#!/usr/bin/env node
"use strict";
var backup = require("../lib/backup");
var ArgumentParser = require('argparse').ArgumentParser;
var pkg = require('../package.json');
function main(argv) {
var parser = new ArgumentParser({
version: pkg.version,
addHelp: true,
description: pkg.description
});
parser.addArgument("username", {
help: "The github username to backup."
});
parser.addArgument("path", {
help: "The path where to backup the repositories to."
});
parser.addArgument(['--include', '-i'], {
defaultValue: 'user,org,starred',
type: function(i) { return i.split(","); },
help: "Choose which repositories to backup. You can " +
"select \"user\", \"org\" and \"stared\", and any combination" +
" separated by a comma"
});
parser.addArgument(['--dry-run', '-n'], {
action: "storeTrue",
help: "If set, no action is actually performed."
});
var args = parser.parseArgs();
backup.publicUserRepos(args).catch(function(err) {
console.error("Unhandled error:", err);
}).done();
}
main();
|
Fix last printer not showing when there was odd number of printers
|
import React, { PropTypes } from 'react';
import style from './style.css';
import Printer from '../printer';
class PrinterListComponent extends React.Component {
getPrinterComponent(key) {
return (<Printer
{...this.props.printers[key]} key={key}
toggleSelected={() => { this.props.toggleSelected(key); }} />);
}
generatePrinterList() {
let keys = Object.keys(this.props.printers);
let printerRows = [];
if (keys.length > 0) {
let howManyTimes = Math.ceil(keys.length / 2);
for (let i = 0; i < howManyTimes; i+=1) {
printerRows.push(
<div key={i}>
{this.getPrinterComponent(keys[i * 2])}
{ keys[(i * 2) + 1] && this.getPrinterComponent(keys[(i * 2) + 1])}
</div>);
}
return printerRows;
}
return (<div></div>);
}
render() {
return (
<div className={style.printerList}>
{this.generatePrinterList()}
</div>);
}
}
PrinterListComponent.propTypes = {
printers: PropTypes.object.isRequired,
toggleSelected: PropTypes.func.isRequired,
};
export default PrinterListComponent;
|
import React, { PropTypes } from 'react';
import style from './style.css';
import Printer from '../printer';
class PrinterListComponent extends React.Component {
getPrinterComponent(key) {
return (<Printer
{...this.props.printers[key]} key={key}
toggleSelected={() => { this.props.toggleSelected(key); }} />);
}
generatePrinterList() {
let keys = Object.keys(this.props.printers);
let printerRows = [];
if (keys.length > 0) {
let howManyTimes = Math.floor(keys.length / 2);
for (let i = 0; i < howManyTimes; i+=1) {
console.log(Math.floor(keys.length/2));
printerRows.push(
<div key={i}>
{this.getPrinterComponent(keys[i * 2])}
{ keys[(i * 2) + 1] && this.getPrinterComponent(keys[(i * 2) + 1])}
</div>);
}
return printerRows;
}
return (<div></div>);
}
render() {
return (
<div className={style.printerList}>
{this.generatePrinterList()}
</div>);
}
}
PrinterListComponent.propTypes = {
printers: PropTypes.object.isRequired,
toggleSelected: PropTypes.func.isRequired,
};
export default PrinterListComponent;
|
test: Add some failing tests to fix...
|
/*global describe, it, before, beforeEach */
/*jshint -W030 */
'use strict';
var join = require('path').join
, fs = require('fs')
, expect = require('chai').expect
, cheerio = require('cheerio')
, bd = require('../lib/bedecked');
// Fixtures dir
var fxd = join(__dirname, 'fixtures');
describe('bedecked', function() {
describe('api basics', function() {
var err, $;
before(function(done) {
bd(join(fxd, '001.md'), function(e, html) {
err = e;
$ = cheerio.load(html);
done();
});
});
it('should not generate an error', function() {
expect(err).to.not.be.ok;
});
it('should split into slides', function() {
expect($('.slides > section').length).to.equal(4);
});
it('should add styles and scripts to the page', function() {
/**
* @todo
*/
expect(false).to.be.true;
});
});
describe('api custom opts', function() {
/**
* @todo
*/
});
});
|
/*global describe, it, before, beforeEach */
/*jshint -W030 */
'use strict';
var join = require('path').join
, fs = require('fs')
, expect = require('chai').expect
, cheerio = require('cheerio')
, bd = require('../lib/bedecked');
// Fixtures dir
var fxd = join(__dirname, 'fixtures');
describe('bedecked', function() {
describe('api', function() {
var err, $;
before(function(done) {
bd(join(fxd, '001.md'), function(e, html) {
err = e;
$ = cheerio.load(html);
done();
});
});
it('should not generate an error', function() {
expect(err).to.not.be.ok;
});
it('should split into slides', function() {
expect($('.slides > section').length).to.equal(4);
});
});
});
|
Allow null values to be provided for source.
|
<?php
namespace Rogue\Http\Requests;
class SignupRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'northstar_id' => 'required|string',
'campaign_id' => 'required|int',
'campaign_run_id' => 'required|int',
'quantity' => 'int',
'why_participated' => 'string',
'source' => 'string|nullable',
];
}
}
|
<?php
namespace Rogue\Http\Requests;
class SignupRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'northstar_id' => 'required|string',
'campaign_id' => 'required|int',
'campaign_run_id' => 'required|int',
'quantity' => 'int',
'why_participated' => 'string',
'source' => 'string',
];
}
}
|
Update the PyPI version to 7.0.16.
|
# -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='7.0.16',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
|
# -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='7.0.15',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
|
Add service functions to get transactions by time
|
from datetime import datetime
from datetime import timedelta
from django.utils import timezone
from books.models import Transaction
def get_months_transactions():
today = timezone.now()
first_day_of_a_month = datetime(today.year, today.month, 1,
tzinfo=today.tzinfo)
qs = Transaction.objects.filter(created__gte=first_day_of_a_month)
return qs
def get_last_months_transactions():
first_day_of_a_month = timezone.now().replace(day=1)
last_month = first_day_of_a_month - timedelta(days=1)
first_day_of_last_month = datetime(last_month.year, last_month.month, 1,
tzinfo=last_month.tzinfo)
qs = Transaction.objects.filter(created__gte=first_day_of_last_month)
return qs
def get_this_years_transactions():
today = timezone.now()
first_day_of_this_year = datetime(today.year, 1, 1, tzinfo=today.tzinfo)
qs = Transaction.objects.filter(created__gte=first_day_of_this_year)
return qs
|
from datetime import date
from datetime import timedelta
from django.utils import timezone
from books.models import Transaction
def get_months_transactions():
today = timezone.now()
first_day_of_a_month = date(today.year, today.month, 1)
qs = Transaction.objects.filter(created__gte=first_day_of_a_month)
return qs
def get_last_months_transactions():
first_day_of_a_month = timezone.now().replace(day=1)
last_month = first_day_of_a_month - timedelta(days=1)
first_day_of_last_month = date(last_month.year, last_month.month, 1)
qs = Transaction.objects.filter(created__gte=first_day_of_last_month)
return qs
def get_this_years_transactions():
today = timezone.now()
first_day_of_this_year = date(today.year, 1, 1)
qs = Transaction.objects.filter(created__gte=first_day_of_this_year)
return qs
|
BAP-9558: Create new type Origin oauthOrigin
|
<?php
namespace Oro\Bundle\ImapBundle\Migrations\Schema\v1_4;
use Doctrine\DBAL\Schema\SchemaException;
use Doctrine\DBAL\Schema\Schema;
use Oro\Bundle\MigrationBundle\Migration\Migration;
use Oro\Bundle\MigrationBundle\Migration\QueryBag;
class OroImapBundle implements Migration
{
/**
* {@inheritdoc}
*/
public function up(Schema $schema, QueryBag $queries)
{
self::addAccessTokenFieldToOroEmailOriginTable($schema);
}
/**
* Adds Access Token field to the oro_email_origin table
*
* @param Schema $schema
* @throws SchemaException
*/
public static function addAccessTokenFieldToOroEmailOriginTable(Schema $schema)
{
$table = $schema->getTable('oro_email_origin');
$table->addColumn('access_token', 'string', ['notnull' => false, 'length' => 255]);
}
}
|
<?php
namespace Oro\Bundle\ImapBundle\Migrations\Schema\v1_4;
use Doctrine\DBAL\Schema\Schema;
use Oro\Bundle\MigrationBundle\Migration\Migration;
use Oro\Bundle\MigrationBundle\Migration\QueryBag;
class OroImapBundle implements Migration
{
/**
* {@inheritdoc}
*/
public function up(Schema $schema, QueryBag $queries)
{
self::addAccessTokenFieldToOroEmailOriginTable($schema);
}
/**
* Adds Access Token field to the oro_email_origin table
*
* @param Schema $schema
* @throws \Doctrine\DBAL\Schema\SchemaException
*/
public static function addAccessTokenFieldToOroEmailOriginTable(Schema $schema)
{
$table = $schema->getTable('oro_email_origin');
$table->addColumn('access_token', 'string', ['notnull' => false, 'length' => 255]);
}
}
|
Change exec time to response time
|
/**
* default options
*/
const defaultOptions = {
requestTimeout: 10 * 1000, //request timeout, default is 10s
requestTimeoutCallback: () => {}, //request timeout callback
sendPowerBy: true, //send power by
sendResponseTime: true //send response time
}
/**
* send meta middleware
*/
module.exports = (options, app) => {
options = Object.assign({}, defaultOptions, options);
return (ctx, next) => {
//set request timeout
ctx.res.setTimeout(options.requestTimeout, options.requestTimeoutCallback);
//send power by header
if(options.sendPowerBy){
const version = app.think.version;
ctx.res.setHeader('X-Powered-By', `thinkjs-${version}`);
}
//send response time header
if(options.sendResponseTime){
const startTime = Date.now();
let err;
return next().catch(e => {
err = e;
}).then(() => {
const endTime = Date.now();
ctx.res.setHeader('X-Response-Time', `${endTime - startTime}ms`);
if(err) return Promise.reject(err);
})
}else{
return next();
}
}
}
|
/**
* default options
*/
const defaultOptions = {
requestTimeout: 10 * 1000, //request timeout, default is 10s
requestTimeoutCallback: () => {}, //request timeout callback
sendPowerBy: true,
sendExecTime: true
}
/**
* send meta middleware
*/
module.exports = (options, app) => {
options = Object.assign({}, defaultOptions, options);
return (ctx, next) => {
//set request timeout
ctx.res.setTimeout(options.requestTimeout, options.requestTimeoutCallback);
//send power by header
if(options.sendPowerBy){
const version = app.think.version;
ctx.res.setHeader('X-Powered-By', `thinkjs-${version}`);
}
//send exec time header
if(options.sendExecTime){
const startTime = Date.now();
let err;
return next().catch(e => {
err = e;
}).then(() => {
const endTime = Date.now();
ctx.res.setHeader('X-Exec-Time', `${endTime - startTime}ms`);
if(err) return Promise.reject(err);
})
}else{
return next();
}
}
}
|
:bug: Fix bug breaking webpages with yt embeds
|
// listen for new tabs
chrome.tabs.onCreated.addListener(function (tabId , info) {
if(isYouTubeUrl(info.url) && doesUrlNotContainField(info.url)){
revertYT(tabId);
}
});
// listen for updated tabs
chrome.tabs.onUpdated.addListener(function (tabId , info) {
// check
if(isYouTubeUrl(info.url) && doesUrlNotContainField(info.url)){
revertYT(tabId);
}
});
// enable old version
function revertYT(tabId){
chrome.tabs.get(tabId, function(tab){
if(tab.url.indexOf("?") !== -1){
chrome.tabs.update(tabId, {
url: tab.url + "&disable_polymer=true"
});
}else{
chrome.tabs.update(tabId, {
url: tab.url + "?disable_polymer=true"
});
}
});
}
function doesUrlNotContainField(url){
return url.indexOf("disable_polymer=true") === -1;
}
function isYouTubeUrl(url){
return (url.indexOf("www.youtube.com") !== -1 || url.indexOf("https://youtube.com") !== -1);
}
|
// listen for page navigations, detect if they're YT & include our disable
chrome.webNavigation.onBeforeNavigate.addListener((details) => {
if(detectYTURL(details.url) && details.url.indexOf("disable_polymer=true") === -1){
// append the disabling field
if(details.url.indexOf("?") !== -1){
chrome.tabs.update(details.tabId, {
url: details.url + "&disable_polymer=true"
});
}else{
chrome.tabs.update(details.tabId, {
url: details.url + "?disable_polymer=true"
});
}
}
});
// helper to keep things clean 👍
function detectYTURL(url){
return ((url.indexOf("www.youtube.com") !== -1 || url.indexOf("https://youtube.com") !== -1)
&& url.indexOf("/js") === -1) && url.indexOf("google") === -1 &&
url.indexOf("googleads") === -1 && url.indexOf(".g.") === -1 &&
url.indexOf("www.youtube.com/ad_companion") === -1;
}
|
Make importing secrets explicitly relative
|
# -*- coding: utf-8 -*-
import pytest
from epo_ops.middlewares import Dogpile, Throttler
from epo_ops.middlewares.throttle.storages import sqlite
from inet.sources.ops import OpsClient
from .secrets import OPS_KEY, OPS_SECRET
def test_ops_client_instantiated():
"""Test our subclass od epo_ops.RegisteredClient
to ensure it is instantiatied correctly."""
client = OpsClient(OPS_KEY, OPS_SECRET)
assert len(client.middlewares) == 1
assert client.middlewares[0].history.db_path == sqlite.DEFAULT_DB_PATH
middlewares = [
Dogpile(),
Throttler(),
]
client = OpsClient(OPS_KEY,
OPS_SECRET,
accept_type='JSON',
middlewares=middlewares)
assert len(client.middlewares) == 2
if __name__ == '__main__':
pytest.main()
|
# -*- coding: utf-8 -*-
import pytest
from epo_ops.middlewares import Dogpile, Throttler
from epo_ops.middlewares.throttle.storages import sqlite
from inet.sources.ops import OpsClient
from secrets import OPS_KEY, OPS_SECRET
def test_ops_client_instantiated():
"""Test our subclass od epo_ops.RegisteredClient
to ensure it is instantiatied correctly."""
client = OpsClient(OPS_KEY, OPS_SECRET)
assert len(client.middlewares) == 1
assert client.middlewares[0].history.db_path == sqlite.DEFAULT_DB_PATH
middlewares = [
Dogpile(),
Throttler(),
]
client = OpsClient(OPS_KEY,
OPS_SECRET,
accept_type='JSON',
middlewares=middlewares)
assert len(client.middlewares) == 2
if __name__ == '__main__':
pytest.main()
|
Use is_null to check if a state isn't available.
|
<?php
/**
* @version $Id$
* @category Nooku
* @package Nooku_Server
* @subpackage Categories
* @copyright Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net).
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://www.nooku.org
*/
defined('KOOWA') or die( 'Restricted access' ); ?>
<div id="filter" class="group">
<ul>
<li class="<?= is_null($state->published) ? 'active' : ''; ?> separator-right">
<a href="<?= @route('published=' ) ?>">
<?= @text('All') ?>
</a>
</li>
<li class="<?= $state->published === true ? 'active' : ''; ?>">
<a href="<?= @route($state->published === true ? 'published=' : 'published=1') ?>">
<?= @text('Published') ?>
</a>
</li>
<li class="<?= $state->published === false ? 'active' : ''; ?>">
<a href="<?= @route($state->published === false ? 'published=' : 'published=0' ) ?>">
<?= @text('Unpublished') ?>
</a>
</li>
</ul>
</div>
|
<?php
/**
* @version $Id$
* @category Nooku
* @package Nooku_Server
* @subpackage Categories
* @copyright Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net).
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://www.nooku.org
*/
defined('KOOWA') or die( 'Restricted access' ); ?>
<div id="filter" class="group">
<ul>
<li class="<?= !is_numeric($state->published) ? 'active' : ''; ?> separator-right">
<a href="<?= @route('&published=' ) ?>">
<?= @text('All') ?>
</a>
</li>
<li class="<?= $state->published === true ? 'active' : ''; ?>">
<a href="<?= @route($state->published === true ? 'published=' : 'published=1') ?>">
<?= @text('Published') ?>
</a>
</li>
<li class="<?= $state->published === false ? 'active' : ''; ?>">
<a href="<?= @route($state->published === false ? 'published=' : 'published=0' ) ?>">
<?= @text('Unpublished') ?>
</a>
</li>
</ul>
</div>
|
Add with_statement import for python2.5.
See http://www.python.org/dev/peps/pep-0343/ which describes
the with statement.
Review URL: http://codereview.chromium.org/5690003
git-svn-id: e7e1075985beda50ea81ac4472467b4f6e91fc78@863 78cadc50-ecff-11dd-a971-7dbc132099af
|
#!/usr/bin/env python
# Copyright (c) 2010 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies that .so files that are order only dependencies are specified by
their install location rather than by their alias.
"""
# Python 2.5 needs this for the with statement.
from __future__ import with_statement
import os
import TestGyp
test = TestGyp.TestGyp(formats=['make'])
test.run_gyp('shared_dependency.gyp',
chdir='src')
test.relocate('src', 'relocate/src')
test.build('shared_dependency.gyp', test.ALL, chdir='relocate/src')
with open('relocate/src/Makefile') as makefile:
make_contents = makefile.read()
# If we remove the code to generate lib1, Make should still be able
# to build lib2 since lib1.so already exists.
make_contents = make_contents.replace('include lib1.target.mk', '')
with open('relocate/src/Makefile', 'w') as makefile:
makefile.write(make_contents)
test.build('shared_dependency.gyp', test.ALL, chdir='relocate/src')
test.pass_test()
|
#!/usr/bin/env python
# Copyright (c) 2010 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies that .so files that are order only dependencies are specified by
their install location rather than by their alias.
"""
import os
import TestGyp
test = TestGyp.TestGyp(formats=['make'])
test.run_gyp('shared_dependency.gyp',
chdir='src')
test.relocate('src', 'relocate/src')
test.build('shared_dependency.gyp', test.ALL, chdir='relocate/src')
with open('relocate/src/Makefile') as makefile:
make_contents = makefile.read()
# If we remove the code to generate lib1, Make should still be able
# to build lib2 since lib1.so already exists.
make_contents = make_contents.replace('include lib1.target.mk', '')
with open('relocate/src/Makefile', 'w') as makefile:
makefile.write(make_contents)
test.build('shared_dependency.gyp', test.ALL, chdir='relocate/src')
test.pass_test()
|
Add the NewSpec testing helper.
|
// Copyright 2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package cmd
import (
"strings"
jc "github.com/juju/testing/checkers"
gc "gopkg.in/check.v1"
"gopkg.in/juju/charm.v6-unstable"
"github.com/juju/juju/resource"
)
func NewSpec(c *gc.C, name, suffix, comment string) resource.Spec {
info := charm.ResourceInfo{
Name: name,
Type: charm.ResourceTypeFile,
Path: name + suffix,
Comment: comment,
}
spec, err := resource.NewSpec(info, resource.OriginUpload, "")
c.Assert(err, jc.ErrorIsNil)
return spec
}
func NewSpecs(c *gc.C, names ...string) []resource.Spec {
var specs []resource.Spec
for _, name := range names {
var comment string
parts := strings.SplitN(name, ":", 2)
if len(parts) == 2 {
name = parts[0]
comment = parts[1]
}
spec := NewSpec(c, name, ".tgz", comment)
specs = append(specs, spec)
}
return specs
}
|
// Copyright 2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package status
import (
"fmt"
"strings"
gc "gopkg.in/check.v1"
"gopkg.in/juju/charm.v6-unstable"
"github.com/juju/juju/resource"
)
func NewSpecs(c *gc.C, names ...string) []resource.Spec {
var specs []resource.Spec
for _, name := range names {
var comment string
parts := strings.SplitN(name, ":", 2)
if len(parts) == 2 {
name = parts[0]
comment = parts[1]
}
info := charm.ResourceInfo{
Name: name,
Type: charm.ResourceTypeFile,
Path: name + ".tgz",
Comment: comment,
}
spec, err := resource.NewSpec(info, resource.OriginUpload, "")
c.Assert(err, jc.ErrorIsNil)
specs = append(specs, spec)
}
return specs
}
|
Refactor default value for BankAccountType as refactored on enum
|
package me.pagarme.factory;
import me.pagar.BankAccountType;
import me.pagar.model.BankAccount;
public class BankAccountFactory {
public static String DEFAULT_AGENCIA = "0192";
public static String DEFAULT_AGENCIA_DV = "0";
public static String DEFAULT_CONTA = "03245";
public static String DEFAULT_CONTA_DV = "0";
public static String DEFAULT_BANK_CODE = "341";
public static String DEFAULT_LEGAL_NAME = "Conta teste";
public static String DEFAULT_DOCUMENT_NUMBER = "18344334799";
public static BankAccountType DEFAULT_TYPE = BankAccountType.CORRENTE;
public BankAccount create(){
BankAccount bankAccount = new BankAccount();
bankAccount.setAgencia(DEFAULT_AGENCIA);
bankAccount.setAgenciaDv(DEFAULT_AGENCIA_DV);
bankAccount.setBankCode(DEFAULT_BANK_CODE);
bankAccount.setConta(DEFAULT_CONTA);
bankAccount.setContaDv(DEFAULT_CONTA_DV);
bankAccount.setLegalName(DEFAULT_LEGAL_NAME);
bankAccount.setDocumentNumber(DEFAULT_DOCUMENT_NUMBER);
bankAccount.setType(DEFAULT_TYPE);
return bankAccount;
}
}
|
package me.pagarme.factory;
import me.pagar.BankAccountType;
import me.pagar.model.BankAccount;
public class BankAccountFactory {
public static String DEFAULT_AGENCIA = "0192";
public static String DEFAULT_AGENCIA_DV = "0";
public static String DEFAULT_CONTA = "03245";
public static String DEFAULT_CONTA_DV = "0";
public static String DEFAULT_BANK_CODE = "341";
public static String DEFAULT_LEGAL_NAME = "Conta teste";
public static String DEFAULT_DOCUMENT_NUMBER = "18344334799";
public static BankAccountType DEFAULT_TYPE = BankAccountType.CONTA_CORRENTE;
public BankAccount create(){
BankAccount bankAccount = new BankAccount();
bankAccount.setAgencia(DEFAULT_AGENCIA);
bankAccount.setAgenciaDv(DEFAULT_AGENCIA_DV);
bankAccount.setBankCode(DEFAULT_BANK_CODE);
bankAccount.setConta(DEFAULT_CONTA);
bankAccount.setContaDv(DEFAULT_CONTA_DV);
bankAccount.setLegalName(DEFAULT_LEGAL_NAME);
bankAccount.setDocumentNumber(DEFAULT_DOCUMENT_NUMBER);
bankAccount.setType(DEFAULT_TYPE);
return bankAccount;
}
}
|
Fix unicode encoding of Slack message posts
|
#! /usr/bin/env python2.7
import requests
class Slackbot(object):
def __init__(self, slack_name, token):
self.slack_name = slack_name
self.token = token
assert self.token, "Token should not be blank"
self.url = self.sb_url()
def sb_url(self):
url = "https://{}.slack.com/".format(self.slack_name)
url += "services/hooks/slackbot"
return url
def say(self, channel, statement):
"""
channel should not be preceded with '#'
"""
assert channel # not blank
if channel[0] == '#':
channel = channel[1:]
nurl = self.url + "?token={}&channel=%23{}".format(self.token, channel)
p = requests.post(nurl, data=statement.encode('utf-8'))
return p.status_code
|
#! /usr/bin/env python2.7
import requests
class Slackbot(object):
def __init__(self, slack_name, token):
self.slack_name = slack_name
self.token = token
assert self.token, "Token should not be blank"
self.url = self.sb_url()
def sb_url(self):
url = "https://{}.slack.com/".format(self.slack_name)
url += "services/hooks/slackbot"
return url
def say(self, channel, statement):
"""
channel should not be preceded with '#'
"""
assert channel # not blank
if channel[0] == '#':
channel = channel[1:]
nurl = self.url + "?token={}&channel=%23{}".format(self.token, channel)
p = requests.post(nurl, statement)
return p.status_code
|
Check an authentication in the group router
|
import {check_authentication, validate_request} from '../utils/errors'
import express from 'express'
function validate_request_body(request, response, next_handler) {
request.checkBody({
'screen_name': {
notEmpty: {
errorMessage: 'parameter is required',
},
},
})
validate_request(request, next_handler)
}
const all_groups_router = express.Router()
all_groups_router.route('/groups')
.get(check_authentication, (request, response) => {
response.json({})
})
.post(check_authentication, validate_request_body, (request, response) => {
response.json({
group: request.body,
})
})
const one_group_router = express.Router()
one_group_router.param('group_id', (request, response, next_handler) => {
request.checkParams('group_id', 'parameter is required').notEmpty()
request
.checkParams('group_id', 'parameter must be a MongoDB ObjectId')
.isMongoId()
validate_request(request, next_handler)
})
one_group_router.route('/groups/:group_id')
.delete(check_authentication, (request, response) => {
response.json({
group_id: request.params.group_id,
})
})
export const group_router = express.Router()
group_router.use(all_groups_router)
group_router.use(one_group_router)
|
import {validate_request} from '../utils/errors'
import express from 'express'
function validate_request_body(request, response, next_handler) {
request.checkBody({
'screen_name': {
notEmpty: {
errorMessage: 'parameter is required',
},
},
})
validate_request(request, next_handler)
}
const all_groups_router = express.Router()
all_groups_router.route('/groups')
.get((request, response) => {
response.json({})
})
.post(validate_request_body, (request, response) => {
response.json({
group: request.body,
})
})
const one_group_router = express.Router()
one_group_router.param('group_id', (request, response, next_handler) => {
request.checkParams('group_id', 'parameter is required').notEmpty()
request
.checkParams('group_id', 'parameter must be a MongoDB ObjectId')
.isMongoId()
validate_request(request, next_handler)
})
one_group_router.route('/groups/:group_id')
.delete((request, response) => {
response.json({
group_id: request.params.group_id,
})
})
export const group_router = express.Router()
group_router.use(all_groups_router)
group_router.use(one_group_router)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.