text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Disable most Nova functions for DuesTransactions | <?php
namespace App\Policies;
use App\User;
use App\DuesTransaction;
use Illuminate\Auth\Access\HandlesAuthorization;
class DuesTransactionPolicy
{
use HandlesAuthorization;
public function view(User $user, DuesTransaction $resource)
{
return $user->can('read-dues-transactions');
}
public function viewAny(User $user)
{
return $user->can('read-dues-transactions');
}
public function create(User $user)
{
return false;
}
public function update(User $user, DuesTransaction $resource)
{
return false;
}
public function delete(User $user, DuesTransaction $resource)
{
return false;
}
public function restore(User $user, DuesTransaction $resource)
{
return false;
}
public function forceDelete(User $user, DuesTransaction $resource)
{
return false;
}
}
| <?php
namespace App\Policies;
use App\User;
use App\DuesTransaction;
use Illuminate\Auth\Access\HandlesAuthorization;
class DuesTransactionPolicy
{
use HandlesAuthorization;
public function view(User $user, DuesTransaction $resource)
{
return $user->can('read-dues-transactions');
}
public function viewAny(User $user)
{
return $user->can('read-dues-transactions');
}
public function create(User $user)
{
return $user->can('create-dues-transactions');
}
public function update(User $user, DuesTransaction $resource)
{
return $user->can('update-dues-transactions');
}
public function delete(User $user, DuesTransaction $resource)
{
return $user->can('delete-dues-transactions');
}
public function restore(User $user, DuesTransaction $resource)
{
return $user->can('delete-dues-transactions');
}
public function forceDelete(User $user, DuesTransaction $resource)
{
return false;
}
}
|
Flyway: Fix Scanner constructor substitution for Flyway 7.9.0 | package io.quarkus.flyway.runtime.graal;
import java.nio.charset.Charset;
import java.util.Collection;
import org.flywaydb.core.api.Location;
import org.flywaydb.core.internal.scanner.LocationScannerCache;
import org.flywaydb.core.internal.scanner.ResourceNameCache;
import com.oracle.svm.core.annotate.Substitute;
import com.oracle.svm.core.annotate.TargetClass;
/**
* Needed to get rid of some Android related classes
*/
@TargetClass(className = "org.flywaydb.core.internal.scanner.Scanner")
public final class ScannerSubstitutions {
@Substitute
public ScannerSubstitutions(Class<?> implementedInterface, Collection<Location> locations, ClassLoader classLoader,
Charset encoding,
boolean detectEncoding,
boolean stream,
ResourceNameCache resourceNameCache, LocationScannerCache locationScannerCache,
boolean throwOnMissingLocations) {
throw new IllegalStateException("'org.flywaydb.core.internal.scanner.Scanner' is never used in Quarkus");
}
}
| package io.quarkus.flyway.runtime.graal;
import java.nio.charset.Charset;
import java.util.Collection;
import org.flywaydb.core.api.Location;
import org.flywaydb.core.internal.scanner.LocationScannerCache;
import org.flywaydb.core.internal.scanner.ResourceNameCache;
import com.oracle.svm.core.annotate.Substitute;
import com.oracle.svm.core.annotate.TargetClass;
/**
* Needed to get rid of some Android related classes
*/
@TargetClass(className = "org.flywaydb.core.internal.scanner.Scanner")
public final class ScannerSubstitutions {
@Substitute
public ScannerSubstitutions(Class<?> implementedInterface, Collection<Location> locations, ClassLoader classLoader,
Charset encoding,
boolean stream,
ResourceNameCache resourceNameCache, LocationScannerCache locationScannerCache) {
throw new IllegalStateException("'org.flywaydb.core.internal.scanner.Scanner' is never used in Quarkus");
}
}
|
Add a link in doc. | /*
* Copyright 2018, TeamDev. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.system.server;
import com.google.protobuf.Message;
import io.spine.annotation.Internal;
/**
* A gateway for sending messages into a system bounded context.
*
* @author Dmytro Dashenkov
*/
@Internal
public interface SystemGateway {
/**
* Posts a system command.
*
* <p>In a multitenant environment, the command is posted for
* the {@linkplain io.spine.server.tenant.TenantAwareOperation current tenant}.
*
* @param systemCommand command message
*/
void postCommand(Message systemCommand);
}
| /*
* Copyright 2018, TeamDev. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.system.server;
import com.google.protobuf.Message;
import io.spine.annotation.Internal;
/**
* A gateway for sending messages into a system bounded context.
*
* @author Dmytro Dashenkov
*/
@Internal
public interface SystemGateway {
/**
* Posts a system command.
*
* <p>In a multitenant environment, the command is posted for the current tenant.
*
* @param systemCommand command message
*/
void postCommand(Message systemCommand);
}
|
Call the new findByDates method | package <%=packageName%>.service;
import <%=packageName%>.config.audit.AuditEventConverter;
import <%=packageName%>.domain.PersistentAuditEvent;
import <%=packageName%>.repository.PersistenceAuditEventRepository;
import org.joda.time.LocalDateTime;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.inject.Inject;
import java.util.List;
/**
* Service for managing audit event.
* <p/>
* <p>
* This is the default implementation to support SpringBoot Actuator AuditEventRepository
* </p>
*/
@Service
@Transactional
public class AuditEventService {
@Inject
private PersistenceAuditEventRepository persistenceAuditEventRepository;
@Inject
private AuditEventConverter auditEventConverter;
public List<AuditEvent> findAll() {
return auditEventConverter.convertToAuditEvent(persistenceAuditEventRepository.findAll());
}
public List<AuditEvent> findBetweenDates(LocalDateTime fromDate, LocalDateTime toDate) {
final List<PersistentAuditEvent> persistentAuditEvents =
persistenceAuditEventRepository.findByDates(fromDate, toDate);
return auditEventConverter.convertToAuditEvent(persistentAuditEvents);
}
}
| package <%=packageName%>.service;
import <%=packageName%>.config.audit.AuditEventConverter;
import <%=packageName%>.domain.PersistentAuditEvent;
import <%=packageName%>.repository.PersistenceAuditEventRepository;
import org.joda.time.LocalDateTime;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.inject.Inject;
import java.util.List;
/**
* Service for managing audit event.
* <p/>
* <p>
* This is the default implementation to support SpringBoot Actuator AuditEventRepository
* </p>
*/
@Service
@Transactional
public class AuditEventService {
@Inject
private PersistenceAuditEventRepository persistenceAuditEventRepository;
@Inject
private AuditEventConverter auditEventConverter;
public List<AuditEvent> findAll() {
return auditEventConverter.convertToAuditEvent(persistenceAuditEventRepository.findAll());
}
public List<AuditEvent> findBetweenDates(LocalDateTime fromDate, LocalDateTime toDate) {
final List<PersistentAuditEvent> persistentAuditEvents =
persistenceAuditEventRepository.findByAuditEventDateBetween(fromDate, toDate);
return auditEventConverter.convertToAuditEvent(persistentAuditEvents);
}
}
|
Allow quitting the application with SIGINT (Ctrl-C) | # -*- coding: utf-8 -*-
import util.colored_exceptions
from gui import main_window
from core import volumes, control
from PySide import QtGui
from PySide import QtCore
import signal
import sys
import os
import core.calculation
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
control = control.Control()
window = main_window.MainWindow(control)
app.setOrganizationName("Forschungszentrum Jülich GmbH")
app.setOrganizationDomain("fz-juelich.de")
app.setApplicationName("pyMolDyn 2")
# filename = '../xyz/generated2.xyz'
# filename = '../xyz/generated.xyz'
# filename = '../xyz/traject_200.xyz'
# filename = '../xyz/GST_111_196_bulk.xyz'
filename = '../xyz/structure_c.xyz'
# filename = '../xyz/hexagonal.xyz'
control = window.control
settings = core.calculation.CalculationSettings([filename], [0], 32, domains=False, surface_cavities=False, center_cavities=False)
control.calculate(settings)
control.update()
window.updatestatus()
# Let the Python interpreter run every 50ms...
timer = QtCore.QTimer()
timer.start(50)
timer.timeout.connect(lambda: None)
# ... to allow it to quit the application on SIGINT (Ctrl-C)
signal.signal(signal.SIGINT, lambda *args: app.quit())
sys.exit(app.exec_())
| # -*- coding: utf-8 -*-
import util.colored_exceptions
from gui import main_window
from core import volumes, control
from PySide import QtGui
import sys
import os
import core.calculation
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
control = control.Control()
window = main_window.MainWindow(control)
app.setOrganizationName("Forschungszentrum Jülich GmbH")
app.setOrganizationDomain("fz-juelich.de")
app.setApplicationName("pyMolDyn 2")
# filename = '../xyz/generated2.xyz'
# filename = '../xyz/generated.xyz'
# filename = '../xyz/traject_200.xyz'
# filename = '../xyz/GST_111_196_bulk.xyz'
filename = '../xyz/structure_c.xyz'
# filename = '../xyz/hexagonal.xyz'
control = window.control
settings = core.calculation.CalculationSettings([filename], [0], 32, domains=False, surface_cavities=False, center_cavities=False)
control.calculate(settings)
control.update()
window.updatestatus()
sys.exit(app.exec_())
|
Change input box to <form> to enable search with Enter key. | /**
* Poster v0.1.0
* A React webapp to list upcoming movies and maintain a watchlist, powered by TMDb
*
* Author: Kushal Pandya <kushalspandya@gmail.com> (https://doublslash.com)
* Date: 13 June, 2016
* License: MIT
*
* Section > Home -> [ SearchBox ]
*/
import React from "react";
export default
class SearchBox extends React.Component {
constructor() {
super();
}
render() {
return (
<form class="input-group">
<input type="text" class="form-control" placeholder="Search movies or people..." />
<span class="input-group-btn">
<button class="btn btn-default glyphicon glyphicon-search" type="submit"></button>
</span>
</form>
);
}
}
| /**
* Poster v0.1.0
* A React webapp to list upcoming movies and maintain a watchlist, powered by TMDb
*
* Author: Kushal Pandya <kushalspandya@gmail.com> (https://doublslash.com)
* Date: 13 June, 2016
* License: MIT
*
* Section > Home -> [ SearchBox ]
*/
import React from "react";
export default
class SearchBox extends React.Component {
constructor() {
super();
}
render() {
return (
<div class="input-group">
<input type="text" class="form-control" placeholder="Search movies or people..." />
<span class="input-group-btn">
<button class="btn btn-default glyphicon glyphicon-search" type="button"></button>
</span>
</div>
);
}
}
|
Set default value for lasteditor | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddLasteditorGeodataLiterature extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('geodata', function (Blueprint $table) {
$table->text('lasteditor')->default('');
});
Schema::table('literature', function (Blueprint $table) {
$table->text('lasteditor')->default('');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('geodata', function (Blueprint $table) {
$table->dropColumn('lasteditor');
});
Schema::table('literature', function (Blueprint $table) {
$table->dropColumn('lasteditor');
});
}
}
| <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddLasteditorGeodataLiterature extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('geodata', function (Blueprint $table) {
$table->text('lasteditor');
});
Schema::table('literature', function (Blueprint $table) {
$table->text('lasteditor');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('geodata', function (Blueprint $table) {
$table->dropColumn('lasteditor');
});
Schema::table('literature', function (Blueprint $table) {
$table->dropColumn('lasteditor');
});
}
}
|
Update the default value for the header cta link to be an empty string instead of a hash. | /**
* WidgetHeaderCTA component.
*
* Site Kit by Google, Copyright 2021 Google LLC
*
* 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
*
* https://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.
*/
/**
* External dependencies
*/
import PropTypes from 'prop-types';
/**
* Internal dependencies
*/
import Link from '../../../components/Link';
const WidgetHeaderCTA = ( { href, label, external } ) => (
<div className="googlesitekit-widget__header--cta">
<Link
href={ href }
external={ external }
>
{ label }
</Link>
</div>
);
WidgetHeaderCTA.propTypes = {
href: PropTypes.string,
label: PropTypes.string.isRequired,
external: PropTypes.bool,
};
WidgetHeaderCTA.defaultProps = {
href: '',
external: true,
};
export default WidgetHeaderCTA;
| /**
* WidgetHeaderCTA component.
*
* Site Kit by Google, Copyright 2021 Google LLC
*
* 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
*
* https://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.
*/
/**
* External dependencies
*/
import PropTypes from 'prop-types';
/**
* Internal dependencies
*/
import Link from '../../../components/Link';
const WidgetHeaderCTA = ( { href, label, external } ) => (
<div className="googlesitekit-widget__header--cta">
<Link
href={ href }
external={ external }
>
{ label }
</Link>
</div>
);
WidgetHeaderCTA.propTypes = {
href: PropTypes.string,
label: PropTypes.string.isRequired,
external: PropTypes.bool,
};
WidgetHeaderCTA.defaultProps = {
href: '#',
external: true,
};
export default WidgetHeaderCTA;
|
Add Python 2.6 to classifiers | from setuptools import setup, find_packages
setup(
name='pymediainfo',
version='2.1.5',
author='Louis Sautier',
author_email='sautier.louis@gmail.com',
url='https://github.com/sbraz/pymediainfo',
description="""A Python wrapper for the mediainfo library.""",
packages=find_packages(),
namespace_packages=[],
include_package_data=True,
zip_safe=False,
license='MIT',
tests_require=["nose"],
test_suite="nose.collector",
classifiers=[
"Development Status :: 5 - Production/Stable",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Operating System :: POSIX :: Linux",
"Operating System :: MacOS :: MacOS X",
"Operating System :: Microsoft :: Windows",
"License :: OSI Approved :: MIT License",
]
)
| from setuptools import setup, find_packages
setup(
name='pymediainfo',
version='2.1.5',
author='Louis Sautier',
author_email='sautier.louis@gmail.com',
url='https://github.com/sbraz/pymediainfo',
description="""A Python wrapper for the mediainfo library.""",
packages=find_packages(),
namespace_packages=[],
include_package_data=True,
zip_safe=False,
license='MIT',
tests_require=["nose"],
test_suite="nose.collector",
classifiers=[
"Development Status :: 5 - Production/Stable",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Operating System :: POSIX :: Linux",
"Operating System :: MacOS :: MacOS X",
"Operating System :: Microsoft :: Windows",
"License :: OSI Approved :: MIT License",
]
)
|
Fix iPhone/iPad not triggering click event | const userAgent = navigator.userAgent.toLowerCase()
const event = userAgent.match(/(iphone|ipod|ipad)/) ? "touchstart" : "click"
const directive = {
instances: []
}
directive.onEvent = function (event) {
directive.instances.forEach(({ el, fn }) => {
if (event.target !== el && !el.contains(event.target)) {
fn && fn(event)
}
})
}
directive.bind = function (el) {
directive.instances.push({ el, fn: null })
if (directive.instances.length === 1) {
document.addEventListener(event, directive.onEvent)
}
}
directive.update = function (el, binding) {
if (typeof binding.value !== 'function') {
throw new Error('Argument must be a function')
}
const instance = directive.instances.find(i => i.el === el)
instance.fn = binding.value
}
directive.unbind = function (el) {
const instance = directive.instances.find(i => i.el === el)
const instanceIndex = directive.instances.indexOf(instance)
directive.instances.splice(instanceIndex, 1)
if (directive.instances.length === 0) {
document.removeEventListener(event, directive.onEvent)
}
}
export default directive
| const directive = {
instances: []
}
directive.onEvent = function (event) {
directive.instances.forEach(({ el, fn }) => {
if (event.target !== el && !el.contains(event.target)) {
fn && fn(event)
}
})
}
directive.bind = function (el) {
directive.instances.push({ el, fn: null })
if (directive.instances.length === 1) {
document.addEventListener('click', directive.onEvent)
}
}
directive.update = function (el, binding) {
if (typeof binding.value !== 'function') {
throw new Error('Argument must be a function')
}
const instance = directive.instances.find(i => i.el === el)
instance.fn = binding.value
}
directive.unbind = function (el) {
const instance = directive.instances.find(i => i.el === el)
const instanceIndex = directive.instances.indexOf(instance)
directive.instances.splice(instanceIndex, 1)
if (directive.instances.length === 0) {
document.removeEventListener('click', directive.onEvent)
}
}
export default directive
|
Use stream while reading file | 'use strict';
/**
* @file Hydrate the file from scratch.
* Download it from Cluestr, save it to local storage, run tika and returns the result.
*
* This helper is used in the server queue.
*/
var async = require('async');
var request = require('request');
var crypto = require('crypto');
var fs = require('fs');
var tikaShell = require('./tika-shell.js');
/**
* Take a Cluestr document and returns metadatas
*
* @param {Object} task Task object, keys must be file_path (file URL) and callback (URL)
* @param {Function} cb Callback, first parameter is the error.
*/
module.exports = function(task, done) {
var serverUrl = require('../../../app.js').url;
async.waterfall([
function(cb) {
var path = '/tmp/' + crypto.randomBytes(20).toString('hex');
// Download the file
request(task.file_path)
.pipe(fs.createWriteStream(path))
.on('finish', function() {
cb(null, path);
});
},
function(path, cb) {
tikaShell(path , cb);
},
function(data, cb) {
// Upload to server
var params = {
url: task.callback,
json: {
hydrater: serverUrl + '/hydrate',
metadatas: data,
}
};
request.patch(params, cb);
}
], done);
};
| 'use strict';
/**
* @file Hydrate the file from scratch.
* Download it from Cluestr, save it to local storage, run tika and returns the result.
*
* This helper is used in the server queue.
*/
var async = require('async');
var request = require('request');
var crypto = require('crypto');
var fs = require('fs');
var tikaShell = require('./tika-shell.js');
/**
* Take a Cluestr document and returns metadatas
*
* @param {Object} task Task object, keys must be file_path (file URL) and callback (URL)
* @param {Function} cb Callback, first parameter is the error.
*/
module.exports = function(task, done) {
var serverUrl = require('../../../app.js').url;
// Download the file
async.waterfall([
function(cb) {
request.get(task.file_path, cb);
},
function(res, body, cb) {
var path = '/tmp/' + crypto.randomBytes(20).toString('hex');
fs.writeFile(path, body, function(err) {
cb(err, path);
});
},
function(path, cb) {
tikaShell(path , cb);
},
function(data, cb) {
// Upload to server
var params = {
url: task.callback,
json: {
hydrater: serverUrl + '/hydrate',
metadatas: data,
}
};
request.patch(params, cb);
}
], done);
};
|
Use bodyParser.json() instead of bodyParser itself.
See: http://stackoverflow.com/questions/24330014/bodyparser-is-deprecated-express-4 | var express = require('express');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var serveStatic = require('serve-static');
var errorhandler = require('errorhandler');
var less = require('less-middleware');
var path = require('path');
exports.register = function(application, params) {
params = params || {};
var prefix = params.prefix || '';
prefix = prefix.replace(/\/$/, '');
var topDirectory = path.join(__dirname, '..', '..', '..');
application.set('views', path.join(topDirectory, 'views'));
application.set('view engine', 'jade');
application.use(prefix, bodyParser.json());
application.use(prefix, methodOverride());
application.use(prefix, less(path.join(topDirectory, 'public')));
application.use(prefix, serveStatic(path.join(topDirectory, 'public')));
var env = process.env.NODE_ENV || 'development';
if (env == 'development') {
application.use(prefix, errorhandler());
}
application.get(prefix + '/dashboard', function(request, response) {
response.render('index', { title: '', prefix: prefix });
});
}
| var express = require('express');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var serveStatic = require('serve-static');
var errorhandler = require('errorhandler');
var less = require('less-middleware');
var path = require('path');
exports.register = function(application, params) {
params = params || {};
var prefix = params.prefix || '';
prefix = prefix.replace(/\/$/, '');
var topDirectory = path.join(__dirname, '..', '..', '..');
application.set('views', path.join(topDirectory, 'views'));
application.set('view engine', 'jade');
application.use(prefix, bodyParser());
application.use(prefix, methodOverride());
application.use(prefix, less(path.join(topDirectory, 'public')));
application.use(prefix, serveStatic(path.join(topDirectory, 'public')));
var env = process.env.NODE_ENV || 'development';
if (env == 'development') {
application.use(prefix, errorhandler());
}
application.get(prefix + '/dashboard', function(request, response) {
response.render('index', { title: '', prefix: prefix });
});
}
|
Update email task test for members | from app.na_celery.email_tasks import send_emails
class WhenProcessingSendEmailsTask:
def it_calls_send_email_to_task(self, mocker, db, db_session, sample_email, sample_member):
mock_send_email = mocker.patch('app.na_celery.email_tasks.send_email', return_value=200)
send_emails(sample_email.id)
assert mock_send_email.call_args[0][0] == sample_member.email
assert mock_send_email.call_args[0][1] == 'workshop: test title'
def it_sends_an_email_to_members_up_to_email_limit(self):
pass
def it_does_not_send_an_email_if_not_between_start_and_expiry(self):
pass
def it_sends_email_with_correct_template(self):
pass
| from app.na_celery.email_tasks import send_emails
class WhenProcessingSendEmailsTask:
def it_calls_send_email_to_task(self, mocker, db, db_session, sample_admin_user, sample_email):
mock_send_email = mocker.patch('app.na_celery.email_tasks.send_email')
send_emails(sample_email.id)
assert mock_send_email.call_args[0][0] == 'admin@example.com'
assert mock_send_email.call_args[0][1] == 'workshop: test title'
def it_sends_an_email_to_members_up_to_email_limit(self):
pass
def it_does_not_send_an_email_if_not_between_start_and_expiry(self):
pass
def it_sends_email_with_correct_template(self):
pass
|
Fix array out of bounds bug | package core.commands;
import core.Constants;
import core.entities.QueueManager;
import core.entities.Server;
import core.exceptions.BadArgumentsException;
import core.exceptions.DoesNotExistException;
import core.util.Utils;
import net.dv8tion.jda.core.entities.Member;
public class CmdDeleteNotification extends Command{
public CmdDeleteNotification(){
this.helpMsg = Constants.DELETENOTIFICATION_HELP;
this.description = Constants.DELETENOTIFICATION_DESC;
this.name = Constants.DELETENOTIFICATION_NAME;
}
@Override
public void execCommand(Server server, Member member, String[] args) {
QueueManager qm = server.getQueueManager();
try{
if(args.length <= 1){
if(args.length == 0){
qm.removeNotification(member.getUser());
}else{
try{
qm.removeNotification(member.getUser(), Integer.valueOf(args[0]));
}catch(NumberFormatException ex){
qm.removeNotification(member.getUser(), args[0]);
}
}
}else{
throw new BadArgumentsException();
}
this.response = Utils.createMessage("Notification(s) removed", "", true);
System.out.println(success());
qm.saveToFile();
}catch(BadArgumentsException | DoesNotExistException ex){
this.response = Utils.createMessage("Error!", ex.getMessage(), false);
}
}
}
| package core.commands;
import core.Constants;
import core.entities.QueueManager;
import core.entities.Server;
import core.exceptions.BadArgumentsException;
import core.exceptions.DoesNotExistException;
import core.util.Utils;
import net.dv8tion.jda.core.entities.Member;
public class CmdDeleteNotification extends Command{
public CmdDeleteNotification(){
this.helpMsg = Constants.DELETENOTIFICATION_HELP;
this.description = Constants.DELETENOTIFICATION_DESC;
this.name = Constants.DELETENOTIFICATION_NAME;
}
@Override
public void execCommand(Server server, Member member, String[] args) {
QueueManager qm = server.getQueueManager();
try{
if(args.length <= 1){
if(args.length == 0){
qm.removeNotification(member.getUser());
}else{
try{
qm.removeNotification(member.getUser(), Integer.valueOf(args[0]));
}catch(NumberFormatException ex){
qm.removeNotification(member.getUser(), args[1]);
}
}
}else{
throw new BadArgumentsException();
}
this.response = Utils.createMessage("Notification(s) removed", "", true);
System.out.println(success());
qm.saveToFile();
}catch(BadArgumentsException | DoesNotExistException ex){
this.response = Utils.createMessage("Error!", ex.getMessage(), false);
}
}
}
|
Add missing method for empty panel | /**
* Empty panel which is shown when no data object is selected.
* @class
*/
export default class EmptyDetailPanel {
constructor(rootElement, rb) {
this.rootElement = rootElement;
this.rb = rb;
}
render() {
let panel = $('#rbro_detail_panel');
$('#rbro_detail_panel').append(`<div id="rbro_empty_detail_panel" class="rbroEmptyDetailPanel rbroHidden">
<div class="rbroLogo"></div>
</div>`);
}
destroy() {
}
show(data) {
$('#rbro_empty_detail_panel').removeClass('rbroHidden');
}
hide() {
$('#rbro_empty_detail_panel').addClass('rbroHidden');
}
isKeyEventDisabled() {
return false;
}
notifyEvent(obj, operation) {
}
updateErrors() {
}
}
| /**
* Empty panel which is shown when no data object is selected.
* @class
*/
export default class EmptyDetailPanel {
constructor(rootElement, rb) {
this.rootElement = rootElement;
this.rb = rb;
}
render() {
let panel = $('#rbro_detail_panel');
$('#rbro_detail_panel').append(`<div id="rbro_empty_detail_panel" class="rbroEmptyDetailPanel rbroHidden">
<div class="rbroLogo"></div>
</div>`);
}
destroy() {
}
show(data) {
$('#rbro_empty_detail_panel').removeClass('rbroHidden');
}
hide() {
$('#rbro_empty_detail_panel').addClass('rbroHidden');
}
notifyEvent(obj, operation) {
}
updateErrors() {
}
}
|
Implement ucFirst() to pass test | /**
* Has Vowels
*
* hasVowel tests if the String calling the function has a vowels
*
* @param {void}
* @return {Boolean} returns true or false indicating if the string
* has a vowel or not
*/
String.prototype.hasVowels = function() {
var inputString = this;
return /[aeiou]/gi.test(inputString);
};
/**
* To Upper
*
* toUpper converts its calling string to all uppercase characters
*
* @param {void}
* @return {String} returns an upperCase version of the calling string
*/
String.prototype.toUpper = function() {
// the 'this' keyword represents the string calling the function
return this.replace(/[a-z]/g, function(item, position, string) {
return String.fromCharCode(string.charCodeAt(position)-32);
});
};
String.prototype.toLower = function() {
// the 'this' keyword represents the string calling the function
return this.replace(/[A-Z]/g, function(item, position, string) {
return String.fromCharCode(string.charCodeAt(position)+32);
});
};
/**
* Uc First
*
* ucFirst capitalises the first character of its calling string
*
* @param {void}
* @return {String} returns the calling string with the first character
* capitalised
*/
String.prototype.ucFirst = function() {
return this.replace(/^[a-z]/g, function(item, position, string) {
return item.toUpper();
});
}; | /**
* Has Vowels
*
* hasVowel tests if the String calling the function has a vowels
*
* @param {void}
* @return {Boolean} returns true or false indicating if the string
* has a vowel or not
*/
String.prototype.hasVowels = function() {
var inputString = this;
return /[aeiou]/gi.test(inputString);
};
/**
* To Upper
*
* toUpper converts its calling string to all uppercase characters
*
* @param {void}
* @return {String} returns an upperCase version of the calling string
*/
String.prototype.toUpper = function() {
// the 'this' keyword represents the string calling the function
return this.replace(/[a-z]/g, function(item, position, string) {
return String.fromCharCode(string.charCodeAt(position)-32);
});
};
String.prototype.toLower = function() {
// the 'this' keyword represents the string calling the function
return this.replace(/[A-Z]/g, function(item, position, string) {
return String.fromCharCode(string.charCodeAt(position)+32);
});
};
/**
* Uc First
*
* ucFirst capitalises the first character of its calling string
*
* @param {void}
* @return {String} returns the calling string with the first character
* capitalised
*/
String.prototype.ucFirst = function() {
return '';
}; |
Move the package as well as the group | package net.stickycode.resource.stereotype;
import net.stickycode.stereotype.ConfiguredComponent;
/**
* Interface used to mark of point where an external resource should be injected.
*
* <pre>
* @Configured
* private Resource<String> helpText;
*
* @Configured
* private Resource<Properties> decodeMappings;
*
* </pre>
*/
@ConfiguredComponent
public interface Resource<T> {
/**
* Return the current value of the resource, depending on the nature of the resource
* this could be a fixed value or change on every call.
*
* <h2>e.g.</h2>
* <ul>
* <li>A string from the classpath might be fixed for the lifetime of the application.</li>
* <li>A Properties resource loaded from a file might change each time its updated</li>
* </ul>
*/
T get();
/**
* Update the underlying resource with the new value
*/
void set(T value);
}
| package net.stickycode.stereotype.resource;
import net.stickycode.stereotype.ConfiguredComponent;
/**
* Interface used to mark of point where an external resource should be injected.
*
* <pre>
* @Configured
* private Resource<String> helpText;
*
* @Configured
* private Resource<Properties> decodeMappings;
*
* </pre>
*/
@ConfiguredComponent
public interface Resource<T> {
/**
* Return the current value of the resource, depending on the nature of the resource
* this could be a fixed value or change on every call.
*
* <h2>e.g.</h2>
* <ul>
* <li>A string from the classpath might be fixed for the lifetime of the application.</li>
* <li>A Properties resource loaded from a file might change each time its updated</li>
* </ul>
*/
T get();
/**
* Update the underlying resource with the new value
*/
void set(T value);
}
|
Use Set.removeAll instead my own loop. | package mccoyst;
import java.io.*;
import java.util.*;
import org.objectweb.asm.*;
public class App{
public static void main(String[] args) throws Exception{
if(args.length < 2){
System.err.println("I need the names of two class files.");
System.exit(1);
}
InputStream a = new FileInputStream(args[0]);
MethodCollector ma = new MethodCollector();
InputStream b = new FileInputStream(args[1]);
MethodCollector mb = new MethodCollector();
try{
ClassReader cra = new ClassReader(a);
cra.accept(ma, 0);
ClassReader crb = new ClassReader(b);
crb.accept(mb, 0);
}finally{
a.close();
b.close();
}
mb.methods.removeAll(ma.methods);
for(Method m : mb.methods){
System.out.println(m);
}
}
}
| package mccoyst;
import java.io.*;
import java.util.*;
import org.objectweb.asm.*;
public class App{
public static void main(String[] args) throws Exception{
if(args.length < 2){
System.err.println("I need the names of two class files.");
System.exit(1);
}
InputStream a = new FileInputStream(args[0]);
MethodCollector ma = new MethodCollector();
InputStream b = new FileInputStream(args[1]);
MethodCollector mb = new MethodCollector();
try{
ClassReader cra = new ClassReader(a);
cra.accept(ma, 0);
ClassReader crb = new ClassReader(b);
crb.accept(mb, 0);
}finally{
a.close();
b.close();
}
List<Method> newer = new ArrayList<Method>();
for(Method m : mb.methods){
if(!ma.methods.contains(m)){
newer.add(m);
}
}
for(Method m : newer){
System.out.println(m);
}
}
}
|
Remove github link from 'install_requires' | from setuptools import setup
setup(
name='firetv',
version='1.0.5.dev',
description='Communicate with an Amazon Fire TV device via ADB over a network.',
url='https://github.com/happyleavesaoc/python-firetv/',
license='MIT',
author='happyleaves',
author_email='happyleaves.tfr@gmail.com',
packages=['firetv'],
install_requires=['adb==1.3.0.dev'],
extras_require={
'firetv-server': ['Flask>=0.10.1', 'PyYAML>=3.12']
},
entry_points={
'console_scripts': [
'firetv-server = firetv.__main__:main'
]
},
classifiers=[
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
]
)
| from setuptools import setup
setup(
name='firetv',
version='1.0.5.dev',
description='Communicate with an Amazon Fire TV device via ADB over a network.',
url='https://github.com/happyleavesaoc/python-firetv/',
license='MIT',
author='happyleaves',
author_email='happyleaves.tfr@gmail.com',
packages=['firetv'],
install_requires=['https://github.com/JeffLIrion/python-adb/zipball/master#adb==1.3.0.dev'],
extras_require={
'firetv-server': ['Flask>=0.10.1', 'PyYAML>=3.12']
},
entry_points={
'console_scripts': [
'firetv-server = firetv.__main__:main'
]
},
classifiers=[
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
]
)
|
Fix class name, got it totally wrong. | <?php
/**
* An exception for ZendExt_Db_Dao_Select.
*
* @category ZendExt
* @package ZendExt_Db_Dao
* @copyright 2010 Juan Sotuyo
* @license Copyright (C) 2010. All rights reserved.
* @version Release: 1.0.0
* @link http://www.zendext.com/
* @since 1.0.0
*/
/**
* An exception for ZendExt_Db_Dao_Select.
*
* @category ZendExt
* @package ZendExt_Db_Dao
* @author jsotuyod <juansotuyo@gmail.com>
* @copyright 2010 Juan Sotuyo
* @license Copyright 2010. All rights reserved.
* @version Release: 1.0.0
* @link http://www.zendext.com/
* @since 1.0.0
*/
class ZendExt_Db_Dao_Select_Exception extends Zend_Db_Table_Select_Exception
{
} | <?php
/**
* An exception for Zend_Db_Dao_Select.
*
* @category ZendExt
* @package ZendExt_Db_Dao
* @copyright 2010 Juan Sotuyo
* @license Copyright (C) 2010. All rights reserved.
* @version Release: 1.0.0
* @link http://www.zendext.com/
* @since 1.0.0
*/
/**
* An exception for Zend_Db_Dao_Select.
*
* @category ZendExt
* @package ZendExt_Db_Dao
* @author jsotuyod <juansotuyo@gmail.com>
* @copyright 2010 Juan Sotuyo
* @license Copyright 2010. All rights reserved.
* @version Release: 1.0.0
* @link http://www.zendext.com/
* @since 1.0.0
*/
class Zend_Db_Dao_Select_Exception extends Zend_Db_Table_Select_Exception
{
} |
Disable django debug toolbar until wagtail 1.12 is released
see https://github.com/jazzband/django-debug-toolbar/issues/950 for
reference | from .base import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
for template_engine in TEMPLATES:
template_engine['OPTIONS']['debug'] = True
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'qid$h1o8&wh#p(j)lifis*5-rf@lbiy8%^3l4x%@b$z(tli@ab'
# FIXME: reenable after upgrade to wagtail 1.12
# see: https://github.com/jazzband/django-debug-toolbar/issues/950
# try:
# import debug_toolbar
# except ImportError:
# pass
# else:
# INSTALLED_APPS += ('debug_toolbar',)
# MIDDLEWARE += ('debug_toolbar.middleware.DebugToolbarMiddleware',)
#
# INTERNAL_IPS = ('127.0.0.1', 'localhost')
try:
from .local import *
except ImportError:
pass
try:
INSTALLED_APPS += tuple(ADDITIONAL_APPS)
except NameError:
pass
| from .base import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
for template_engine in TEMPLATES:
template_engine['OPTIONS']['debug'] = True
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'qid$h1o8&wh#p(j)lifis*5-rf@lbiy8%^3l4x%@b$z(tli@ab'
try:
import debug_toolbar
except ImportError:
pass
else:
INSTALLED_APPS += ('debug_toolbar',)
MIDDLEWARE += ('debug_toolbar.middleware.DebugToolbarMiddleware',)
INTERNAL_IPS = ('127.0.0.1', 'localhost')
try:
from .local import *
except ImportError:
pass
try:
INSTALLED_APPS += tuple(ADDITIONAL_APPS)
except NameError:
pass
|
Add support for the patching connection and the prefix through config dict | from boto.dynamodb2.layer1 import DynamoDBConnection
from .model import Model
def patch_from_config(config):
if 'DYNAMODB_CONNECTION' in config:
patch_dynamodb_connection(**config['DYNAMODB_CONNECTION'])
if 'DYNAMODB_PREFIX' in config:
patch_table_name_prefix(config['DYNAMODB_PREFIX'])
def patch_dynamodb_connection(**kwargs):
""":class:`boto.dynamodb2.layer1.DynamoDBConnection` patcher.
It partially applies the keyword arguments to the
:class:`boto.dynamodb2.layer1.DynamoDBConnection` initializer method.
The common usage of this function would be patching host and port
to the local DynamoDB or remote DynamoDB as the project configuration
changes.
"""
if hasattr(DynamoDBConnection, '__original_init__'):
return
DynamoDBConnection.__original_init__ = DynamoDBConnection.__init__
def init(self, **fkwargs):
fkwargs.update(kwargs)
self.__original_init__(**fkwargs)
DynamoDBConnection.__init__ = init
def patch_table_name_prefix(prefix):
"""Patch the table name prefix"""
Model._table_prefix = prefix
| from boto.dynamodb2.layer1 import DynamoDBConnection
from .model import Model
def patch_dynamodb_connection(**kwargs):
""":class:`boto.dynamodb2.layer1.DynamoDBConnection` patcher.
It partially applies the keyword arguments to the
:class:`boto.dynamodb2.layer1.DynamoDBConnection` initializer method.
The common usage of this function would be patching host and port
to the local DynamoDB or remote DynamoDB as the project configuration
changes.
"""
if hasattr(DynamoDBConnection, '__original_init__'):
return
DynamoDBConnection.__original_init__ = DynamoDBConnection.__init__
def init(self, **fkwargs):
fkwargs.update(kwargs)
self.__original_init__(**fkwargs)
DynamoDBConnection.__init__ = init
def patch_table_name_prefix(prefix):
"""Patch the table name prefix"""
Model._table_prefix = prefix
|
Add Extra Cache Headers To Build Badge Response
Add extra cache prevention headers to the build badge response. This should help
reduce caching on GitHub README's. | import path from 'path';
import logging from '../logging';
const logger = logging.getLogger('express');
import {
internalFindSnap,
internalGetSnapBuilds
} from './launchpad';
import { getGitHubRepoUrl } from '../../common/helpers/github-url';
import { snapBuildFromAPI } from '../../common/helpers/snap-builds';
const BADGES_PATH = path.join(__dirname, '../../common/images/badges');
export const badge = async (req, res) => {
const repoUrl = getGitHubRepoUrl(req.params.owner, req.params.name);
try {
const snap = await internalFindSnap(repoUrl);
const builds = await internalGetSnapBuilds(snap);
let badgeName = 'never_built';
if (builds.length) {
const latestBuild = snapBuildFromAPI(builds[0]);
if (latestBuild.badge) {
badgeName = latestBuild.badge;
}
}
res.setHeader('Cache-Control', 'no-cache, no-store, max-age=0, must-revalidate, value');
res.setHeader('Expires', 'Thu, 01 Jan 1970 00:00:00 GMT');
res.setHeader('Pragma', 'no-cache');
return res.sendFile(path.join(BADGES_PATH, `${badgeName}.svg`));
} catch (err) {
logger.error(`Error generating badge for repo ${repoUrl}`, err);
res.status(404).send('Not found');
}
};
| import path from 'path';
import logging from '../logging';
const logger = logging.getLogger('express');
import {
internalFindSnap,
internalGetSnapBuilds
} from './launchpad';
import { getGitHubRepoUrl } from '../../common/helpers/github-url';
import { snapBuildFromAPI } from '../../common/helpers/snap-builds';
const BADGES_PATH = path.join(__dirname, '../../common/images/badges');
export const badge = async (req, res) => {
const repoUrl = getGitHubRepoUrl(req.params.owner, req.params.name);
try {
const snap = await internalFindSnap(repoUrl);
const builds = await internalGetSnapBuilds(snap);
let badgeName = 'never_built';
if (builds.length) {
const latestBuild = snapBuildFromAPI(builds[0]);
if (latestBuild.badge) {
badgeName = latestBuild.badge;
}
}
res.setHeader('Cache-Control', 'no-cache');
return res.sendFile(path.join(BADGES_PATH, `${badgeName}.svg`));
} catch (err) {
logger.error(`Error generating badge for repo ${repoUrl}`, err);
res.status(404).send('Not found');
}
};
|
Include slugs in ghost response | // @flow
import GhostContentAPI from "@tryghost/content-api";
const ghostContentAPI =
window.GHOST_URL &&
window.GHOST_CONTENT_API_KEY &&
new GhostContentAPI({
url: window.GHOST_URL,
key: window.GHOST_CONTENT_API_KEY,
version: "v3",
});
export type GhostPost = {|
title: string,
url: string,
slug: string,
excerpt: ?string,
custom_excerpt: ?string,
feature_image: string,
|};
class ghostApiHelper {
static browse(
tag: string,
successCallback: ($ReadOnlyArray<GhostPost>) => void,
errCallback: string => void
) {
ghostContentAPI.posts
.browse({
filter: "tag:" + tag,
fields: "title, url, slug, excerpt, custom_excerpt, feature_image",
})
.then(postsResponse => {
successCallback
? successCallback(postsResponse)
: console.log(JSON.stringify(postsResponse));
})
.catch(err => {
errCallback ? errCallback(err) : console.error(err);
});
}
static isConfigured(): boolean {
return !!ghostContentAPI;
}
}
export default ghostApiHelper;
| // @flow
import GhostContentAPI from "@tryghost/content-api";
const ghostContentAPI =
window.GHOST_URL &&
window.GHOST_CONTENT_API_KEY &&
new GhostContentAPI({
url: window.GHOST_URL,
key: window.GHOST_CONTENT_API_KEY,
version: "v3",
});
export type GhostPost = {|
title: string,
url: string,
excerpt: ?string,
custom_excerpt: ?string,
feature_image: string,
|};
class ghostApiHelper {
static browse(
tag: string,
successCallback: ($ReadOnlyArray<GhostPost>) => void,
errCallback: string => void
) {
ghostContentAPI.posts
.browse({
filter: "tag:" + tag,
fields: "title, url, excerpt, custom_excerpt, feature_image",
})
.then(postsResponse => {
successCallback
? successCallback(postsResponse)
: console.log(JSON.stringify(postsResponse));
})
.catch(err => {
errCallback ? errCallback(err) : console.error(err);
});
}
static isConfigured(): boolean {
return !!ghostContentAPI;
}
}
export default ghostApiHelper;
|
Change formula validation error to consistent form | from rest_framework.views import APIView
from rest_framework.reverse import reverse
from rest_framework.response import Response
from rest_framework import generics, status
from django.core.exceptions import ValidationError
from .models import *
from .serializers import *
from .formula import validate_formula
class MetricsBase(APIView):
def get(self, request, format=None):
"""
:type request: Request
:param request:
:return:
"""
result = {
"Metrics": reverse('metrics-create', request=request)
}
return Response(result)
class FormulaValidate(APIView):
def get(self, request):
if "formula" not in request.QUERY_PARAMS:
return Response("No formula provided")
try:
validate_formula(request.QUERY_PARAMS["formula"])
return Response(status=status.HTTP_204_NO_CONTENT)
except ValidationError as e:
return Response({ "formula": e.message }, status=status.HTTP_400_BAD_REQUEST)
class MetricsCreate(generics.CreateAPIView):
model = Metric
serializer_class = MetricSerializer
class MetricsDetail(generics.RetrieveAPIView):
model = Metric
serializer_class = MetricSerializer
| from rest_framework.views import APIView
from rest_framework.reverse import reverse
from rest_framework.response import Response
from rest_framework import generics
from rest_framework import generics, status
from django.core.exceptions import ValidationError
from .models import *
from .serializers import *
from .formula import validate_formula
class MetricsBase(APIView):
def get(self, request, format=None):
"""
:type request: Request
:param request:
:return:
"""
result = {
"Metrics": reverse('metrics-create', request=request)
}
return Response(result)
class FormulaValidate(APIView):
def get(self, request):
if "formula" not in request.QUERY_PARAMS:
return Response("No formula provided")
try:
validate_formula(request.QUERY_PARAMS["formula"])
return Response(status=status.HTTP_204_NO_CONTENT)
except ValidationError as e:
return Response(e, status=status.HTTP_400_BAD_REQUEST)
class MetricsCreate(generics.CreateAPIView):
model = Metric
serializer_class = MetricSerializer
class MetricsDetail(generics.RetrieveAPIView):
model = Metric
serializer_class = MetricSerializer
|
Add option to render based on version | import Ember from 'ember';
import layout from './template';
import config from 'ember-get-config';
/**
* @module ember-osf
* @submodule components
*/
/**
* Render the provided url in an iframe via MFR
*
* Sample usage:
* ```handlebars
* {{file-renderer
* download=model.links.download
* width="800" height="1000" allowfullscreen=true}}
* ```
* @class file-renderer
*/
export default Ember.Component.extend({
layout,
download: null,
width: '100%',
height: '100%',
allowfullscreen: true,
version: null,
mfrUrl: Ember.computed('download', 'version', function() {
var base = config.OSF.renderUrl;
var download = this.get('download') + '?direct&mode=render&initialWidth=766';
if (this.get('version')) {
download += '&version=' + this.get('version');
}
var renderUrl = base + '?url=' + encodeURIComponent(download);
return renderUrl;
})
});
| import Ember from 'ember';
import layout from './template';
import config from 'ember-get-config';
/**
* @module ember-osf
* @submodule components
*/
/**
* Render the provided url in an iframe via MFR
*
* Sample usage:
* ```handlebars
* {{file-renderer
* download=model.links.download
* width="800" height="1000" allowfullscreen=true}}
* ```
* @class file-renderer
*/
export default Ember.Component.extend({
layout,
download: null,
width: '100%',
height: '100%',
allowfullscreen: true,
mfrUrl: Ember.computed('download', function() {
var base = config.OSF.renderUrl;
var download = this.get('download');
var renderUrl = base + '?url=' + encodeURIComponent(download + '?direct&mode=render&initialWidth=766');
return renderUrl;
})
});
|
Implement search listener on search button | // # Place all the behaviors and hooks related to the matching controller here.
// # All this logic will automatically be available in application.js.
// # You can use CoffeeScript in this file: http://coffeescript.org/
$(document).ready(function(){
bindSearchBySubmit();
bindSearchByButton();
})
var bindSearchBySubmit = function(){
$('form.navbar-form').on('submit', function(event){
event.preventDefault();
var data = $("#peopleSearchBar").val();
searchServer(data);
})
}
var bindSearchByButton = function(){
$('form.navbar-form').on('click','.glyphicon-search', function(event){
event.preventDefault();
var data = $("#peopleSearchBar").val();
searchServer(data);
})
}
var searchServer = function(data){
$.ajax({
url: 'search',
method: 'post',
dataType: 'html',
data: {search_input: data}
}).done(function(responseData){
displayResults(responseData);
unendorseListener();
})
}
var displayResults = function(responseData){
$('.tab-content').html(responseData)
}
| // # Place all the behaviors and hooks related to the matching controller here.
// # All this logic will automatically be available in application.js.
// # You can use CoffeeScript in this file: http://coffeescript.org/
$(document).ready(function(){
bindSearchBySubmit();
bindSearchByButton();
})
var bindSearchBySubmit = function(){
$('form.navbar-form').on('submit', function(event){
event.preventDefault();
var data = $("#peopleSearchBar").val();
searchServer(data);
})
}
var bindSearchByButton = function(){
$('form.navbar-form').on('.glyphicon-search', function(event){
event.preventDefault();
var data = $("#peopleSearchBar").val();
searchServer(data);
})
}
var searchServer = function(data){
$.ajax({
url: 'search',
method: 'post',
dataType: 'html',
data: {search_input: data}
}).done(function(responseData){
displayResults(responseData);
unendorseListener();
})
}
var displayResults = function(responseData){
$('.tab-content').html(responseData)
}
|
Comment out invalid propset examples. | /**
* Created by zsolt on 3/23/14.
*/
var person = {
firstName: 'Jimmy',
lastName: 'Smith',
get fullName() {
return this.firstName + ' ' + this.lastName;
}
// set fullName (name) {
// var words = name.toString().split(' ');
// this.firstName = words[0] || '';
// this.lastName = words[1] || '';
// }
};
var Person = function () {
};
Person.prototype.attributes = person;
Person.prototype = {
get name() {
return 's';
},
get fullName() {
return 'p';
},
set fullName(value) {
this.x = value;
}
};
var p = new Person();
// invalid but webstorm does not help
p.name = 's';
Object.defineProperty(person, 'age', {
get: function() {
return this.firstName + ' ' + this.lastName;
}
});
// invalid but webstorm does not help
person.age = 33;
var a1 = person.fullName;
// invalid and webstorm helps
//person.fullName = 33;
//person.fullName = 'Jack Franklin';
//Person.prototype.attributes.fullName = 4;
// performance considerations: http://jsperf.com/properties-implementation-in-javascript/2
var a = Person.prototype.attributes.fullName + 3;
//person.
console.log(person.firstName); // Jack
console.log(person.lastName); // Franklin | /**
* Created by zsolt on 3/23/14.
*/
var person = {
firstName: 'Jimmy',
lastName: 'Smith',
get fullName() {
return this.firstName + ' ' + this.lastName;
}
// set fullName (name) {
// var words = name.toString().split(' ');
// this.firstName = words[0] || '';
// this.lastName = words[1] || '';
// }
};
var Person = function () {
};
Person.prototype.attributes = person;
Person.prototype = {
get name() {
return 's';
},
get fullName() {
return 'p';
},
set fullName(value) {
this.x = value;
}
};
var p = new Person();
// invalid but webstorm does not help
p.name = 's';
Object.defineProperty(person, 'age', {
get: function() {
return this.firstName + ' ' + this.lastName;
}
});
// invalid but webstorm does not help
person.age = 33;
var a1 = person.fullName;
// invalid and webstorm helps
person.fullName = 33;
person.fullName = 'Jack Franklin';
Person.prototype.attributes.fullName = 4;
// performance considerations: http://jsperf.com/properties-implementation-in-javascript/2
var a = Person.prototype.attributes.fullName + 3;
//person.
console.log(person.firstName); // Jack
console.log(person.lastName); // Franklin |
Set environmental vars for rancher-compose to work | #!/usr/bin/env python
"""
Deploy builds to a Rancher orchestrated stack using rancher-compose
"""
import os
import drone
import subprocess
def main():
"""The main entrypoint for the plugin."""
payload = drone.plugin.get_input()
vargs = payload["vargs"]
# Required fields should raise an error
os.environ["RANCHER_URL"] = vargs['url']
os.environ["RANCHER_ACCESS_KEY"] = vargs['access_key']
os.environ["RANCHER_SECRET_KEY"] = vargs['secret_key']
# Optional fields
compose_file = vargs.get('compose_file', 'docker-compose.yml')
stack = vargs.get('stack', payload['repo']['name'])
services = vargs.get('services', '')
# Change directory
deploy_path = payload["workspace"]["path"]
os.chdir(deploy_path)
rc_args = [
"rancher-compose", "-f", compose_file, "-p", stack, "up", services,
]
subprocess.call(rc_args)
if __name__ == "__main__":
main()
| #!/usr/bin/env python
"""
Deploy builds to a Rancher orchestrated stack using rancher-compose
"""
import os
import drone
import subprocess
def main():
"""The main entrypoint for the plugin."""
payload = drone.plugin.get_input()
vargs = payload["vargs"]
# Required fields should raise an error
url, key, secret = vargs['url'], vargs['access_key'], vargs['secret_key']
# Optional fields
compose_file = vargs.get('compose_file', 'docker-compose.yml')
stack = vargs.get('stack', payload['repo']['name'])
services = vargs.get('services', '')
# Change directory
deploy_path = payload["workspace"]["path"]
os.chdir(deploy_path)
rc_args = [
"rancher-compose", "-f", compose_file, "-p", stack, "up", services,
]
subprocess.call(rc_args)
if __name__ == "__main__":
main()
|
Make the pretoucher touch further ahead for long delays on new chunks. | package net.openhft.chronicle.queue;
import net.openhft.chronicle.core.threads.EventHandler;
import net.openhft.chronicle.core.threads.HandlerPriority;
import net.openhft.chronicle.core.threads.InvalidEventHandlerException;
import net.openhft.chronicle.queue.impl.single.Pretoucher;
import net.openhft.chronicle.queue.impl.single.SingleChronicleQueue;
import org.jetbrains.annotations.NotNull;
public final class PretouchHandler implements EventHandler {
private final Pretoucher pretoucher;
private long lastRun = 0;
public PretouchHandler(final SingleChronicleQueue queue) {
this.pretoucher = new Pretoucher(queue);
}
@Override
public boolean action() throws InvalidEventHandlerException {
long now = System.currentTimeMillis();
// don't check too often.
if (now > lastRun + 100) {
pretoucher.execute();
lastRun = now;
}
return false;
}
@NotNull
@Override
public HandlerPriority priority() {
return HandlerPriority.MONITOR;
}
public void shutdown() {
pretoucher.shutdown();
}
} | package net.openhft.chronicle.queue;
import net.openhft.chronicle.core.threads.EventHandler;
import net.openhft.chronicle.core.threads.HandlerPriority;
import net.openhft.chronicle.core.threads.InvalidEventHandlerException;
import net.openhft.chronicle.queue.impl.single.Pretoucher;
import net.openhft.chronicle.queue.impl.single.SingleChronicleQueue;
import org.jetbrains.annotations.NotNull;
public final class PretouchHandler implements EventHandler {
private final Pretoucher pretoucher;
public PretouchHandler(final SingleChronicleQueue queue) {
this.pretoucher = new Pretoucher(queue);
}
@Override
public boolean action() throws InvalidEventHandlerException {
pretoucher.execute();
return false;
}
@NotNull
@Override
public HandlerPriority priority() {
return HandlerPriority.MONITOR;
}
public void shutdown() {
pretoucher.shutdown();
}
} |
Fix comment for extensions flag | // Copyright © 2017 shoarai
// The renfls renames files in a directory.
package main
import (
"flag"
"fmt"
"os"
"os/exec"
"strings"
"github.com/shoarai/renfls"
)
const toDir = "toSubDirsName"
// Flag
var ext string
var ignore bool
func main() {
// DEBUG:
// createTestDir()
flag.BoolVar(&ignore, "ignore", false, "bool flag")
flag.StringVar(&ext, "ext", "", "extensions splited by \",\"")
flag.Parse()
exts := strings.Split(ext, ",")
var err error
if !ignore {
// err = renfls.ToSubDirsNameExt(toDir, exts)
} else {
err = renfls.ToSubDirsNameIgnoreExt(toDir, exts)
}
if err != nil {
fmt.Println(err)
}
}
func createTestDir() {
os.RemoveAll(toDir)
exec.Command("cp", "-r", "testdata", toDir).Run()
}
| // Copyright © 2017 shoarai
// The renfls renames files in a directory.
package main
import (
"flag"
"fmt"
"os"
"os/exec"
"strings"
"github.com/shoarai/renfls"
)
const toDir = "toSubDirsName"
// Flag
var ext string
var ignore bool
func main() {
// DEBUG:
// createTestDir()
flag.BoolVar(&ignore, "ignore", false, "bool flag")
flag.StringVar(&ext, "ext", "", "extensions splited by \".\"")
flag.Parse()
exts := strings.Split(ext, ",")
var err error
if !ignore {
// err = renfls.ToSubDirsNameExt(toDir, exts)
} else {
err = renfls.ToSubDirsNameIgnoreExt(toDir, exts)
}
if err != nil {
fmt.Println(err)
}
}
func createTestDir() {
os.RemoveAll(toDir)
exec.Command("cp", "-r", "testdata", toDir).Run()
}
|
Set delay to zero for local development. | /*
* In order to prevent errors caused by e2e tests running too fast you can slow them down by calling the following
* function. Use higher values for slower tests.
*
* utils.delayPromises(30);
*
*/
var promisesDelay = 0;
function delayPromises(milliseconds) {
var executeFunction = browser.driver.controlFlow().execute;
browser.driver.controlFlow().execute = function() {
var args = arguments;
executeFunction.call(browser.driver.controlFlow(), function() {
return protractor.promise.delayed(milliseconds);
});
return executeFunction.apply(browser.driver.controlFlow(), args);
};
}
console.log("Set promises delay to " + promisesDelay + " ms.");
delayPromises(promisesDelay);
var ECWaitTime = 4500;
var shortRest = 200;
module.exports = {
ECWaitTime: ECWaitTime,
shortRest: shortRest
};
| /*
* In order to prevent errors caused by e2e tests running too fast you can slow them down by calling the following
* function. Use higher values for slower tests.
*
* utils.delayPromises(30);
*
*/
var promisesDelay = 50;
function delayPromises(milliseconds) {
var executeFunction = browser.driver.controlFlow().execute;
browser.driver.controlFlow().execute = function() {
var args = arguments;
executeFunction.call(browser.driver.controlFlow(), function() {
return protractor.promise.delayed(milliseconds);
});
return executeFunction.apply(browser.driver.controlFlow(), args);
};
}
console.log("Set promises delay to " + promisesDelay + " ms.");
delayPromises(promisesDelay);
var ECWaitTime = 4500;
var shortRest = 200;
module.exports = {
ECWaitTime: ECWaitTime,
shortRest: shortRest
};
|
Remove usage of prototype extensions
Addons should not assume existence of prototype extensions and are now disabled by default. | import Ember from 'ember';
const { computed, observer } = Ember;
export default Ember.Component.extend({
tagName: 'div',
attributeBindings: ['contenteditable'],
editable: true,
isUserTyping: false,
plaintext: false,
classNames: ['editable'],
contenteditable: computed('editable', function() {
var editable = this.get('editable');
return editable ? 'true' : undefined;
}),
didInsertElement: function() {
new MediumEditor(this.$(), this.get('options'));
return this.setContent();
},
focusOut: function() {
return this.set('isUserTyping', false);
},
keyDown: function(event) {
if (!event.metaKey) {
return this.set('isUserTyping', true);
}
},
input: function() {
if (this.get('plaintext')) {
return this.set('value', this.$().text());
} else {
return this.set('value', this.$().html());
}
},
valueDidChange: observer('value', function() {
if (this.$() && this.get('value') !== this.$().html()) {
this.setContent();
}
}),
setContent: function() {
if (this.$()) {
return this.$().html(this.get('value'));
}
}
});
| import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'div',
attributeBindings: ['contenteditable'],
editable: true,
isUserTyping: false,
plaintext: false,
classNames: ['editable'],
contenteditable: (function() {
var editable = this.get('editable');
return editable ? 'true' : undefined;
}).property('editable'),
didInsertElement: function() {
new MediumEditor(this.$(), this.get('options'));
return this.setContent();
},
focusOut: function() {
return this.set('isUserTyping', false);
},
keyDown: function(event) {
if (!event.metaKey) {
return this.set('isUserTyping', true);
}
},
input: function() {
if (this.get('plaintext')) {
return this.set('value', this.$().text());
} else {
return this.set('value', this.$().html());
}
},
valueDidChange: function() {
if (this.$() && this.get('value') !== this.$().html()) {
this.setContent();
}
}.observes('value'),
setContent: function() {
if (this.$()) {
return this.$().html(this.get('value'));
}
}
});
|
Use "plugins_dir" config option for added plugins directories | <?php
namespace Smarty\Service;
use Zend\ServiceManager\Factory\FactoryInterface;
use Interop\Container\ContainerInterface;
use Smarty\View\Renderer;
class RendererFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$config = $container->get('Configuration');
$config = $config['smarty'];
/** @var $pathResolver \Zend\View\Resolver\TemplatePathStack */
$pathResolver = clone $container->get('ViewTemplatePathStack');
$pathResolver->setDefaultSuffix($config['suffix']);
/** @var $resolver \Zend\View\Resolver\AggregateResolver */
$resolver = $container->get('ViewResolver');
$resolver->attach($pathResolver);
$engine = new \Smarty();
$engine->setCompileDir($config['compile_dir']);
$engine->setEscapeHtml($config['escape_html']);
$engine->setTemplateDir($pathResolver->getPaths()->toArray());
$engine->setCaching($config['caching']);
$engine->setCacheDir($config['cache_dir']);
$engine->addPluginsDir($config['plugins_dir']);
if (file_exists($config['config_file'])) {
$engine->configLoad($config['config_file']);
}
$renderer = new Renderer();
$renderer->setEngine($engine);
$renderer->setSuffix($config['suffix']);
$renderer->setResolver($resolver);
return $renderer;
}
}
| <?php
namespace Smarty\Service;
use Zend\ServiceManager\Factory\FactoryInterface;
use Interop\Container\ContainerInterface;
use Smarty\View\Renderer;
class RendererFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$config = $container->get('Configuration');
$config = $config['smarty'];
/** @var $pathResolver \Zend\View\Resolver\TemplatePathStack */
$pathResolver = clone $container->get('ViewTemplatePathStack');
$pathResolver->setDefaultSuffix($config['suffix']);
/** @var $resolver \Zend\View\Resolver\AggregateResolver */
$resolver = $container->get('ViewResolver');
$resolver->attach($pathResolver);
$engine = new \Smarty();
$engine->setCompileDir($config['compile_dir']);
$engine->setEscapeHtml($config['escape_html']);
$engine->setTemplateDir($pathResolver->getPaths()->toArray());
$engine->setCaching($config['caching']);
$engine->setCacheDir($config['cache_dir']);
if (file_exists($config['config_file'])) {
$engine->configLoad($config['config_file']);
}
$renderer = new Renderer();
$renderer->setEngine($engine);
$renderer->setSuffix($config['suffix']);
$renderer->setResolver($resolver);
return $renderer;
}
} |
Put JokeService in the right place alphabetically | from pal.services.bonapp_service import BonAppService
from pal.services.dictionary_service import DictionaryService
from pal.services.directory_service import DirectoryService
from pal.services.joke_service import JokeService
from pal.services.movie_service import MovieService
from pal.services.service import wrap_response
from pal.services.ultralingua_service import UltraLinguaService
from pal.services.weather_service import WeatherService
from pal.services.facebook_service import FacebookService
from pal.services.yelp_service import YelpService
from pal.services.wa_service import WAService
_SERVICE_CLASSES = [
BonAppService,
DictionaryService,
DirectoryService,
FacebookService,
JokeService,
MovieService,
UltraLinguaService,
WAService,
WeatherService,
YelpService,
]
_SERVICES = {cls.short_name(): cls() for cls in _SERVICE_CLASSES}
@wrap_response
def no_response():
return ('ERROR', "Sorry, I'm not sure what you mean.")
def get_all_service_names():
return _SERVICES.keys()
def get_service_by_name(name):
if name in _SERVICES:
return _SERVICES[name]
| from pal.services.bonapp_service import BonAppService
from pal.services.dictionary_service import DictionaryService
from pal.services.directory_service import DirectoryService
from pal.services.joke_service import JokeService
from pal.services.movie_service import MovieService
from pal.services.service import wrap_response
from pal.services.ultralingua_service import UltraLinguaService
from pal.services.weather_service import WeatherService
from pal.services.facebook_service import FacebookService
from pal.services.yelp_service import YelpService
from pal.services.wa_service import WAService
_SERVICE_CLASSES = [
BonAppService,
DictionaryService,
DirectoryService,
JokeService,
FacebookService,
MovieService,
UltraLinguaService,
WAService,
WeatherService,
YelpService,
]
_SERVICES = {cls.short_name(): cls() for cls in _SERVICE_CLASSES}
@wrap_response
def no_response():
return ('ERROR', "Sorry, I'm not sure what you mean.")
def get_all_service_names():
return _SERVICES.keys()
def get_service_by_name(name):
if name in _SERVICES:
return _SERVICES[name]
|
Change port for testing purposes | var gpio = require('onoff').Gpio;
var red = new gpio(16, 'out');
var green = new gpio(12, 'out');
var blue = new gpio(21, 'out');
var button = new gpio(25, 'in', 'both');
var express = require('express');
var app = express();
app.get('/', function(req, res){
res.send('Hi I changed this again!');
});
app.listen(3001, function(){
console.log('App listening on port 3001!');
})
// define the callback function
function light(err, state) {
console.log('Button pushed');
// check the state of the button
// 1 == pressed, 0 == not pressed
if(state == 1) {
// turn LED on
red.writeSync(1);
gree.writeSync(1);
blue.writeSync(1);
} else {
// turn LED off
red.writeSync(0);
gree.writeSync(0);
blue.writeSync(0)
}
}
// pass the callback function to the
// as the first argument to watch()
button.watch(light);
| var gpio = require('onoff').Gpio;
var red = new gpio(16, 'out');
var green = new gpio(12, 'out');
var blue = new gpio(21, 'out');
var button = new gpio(25, 'in', 'both');
var express = require('express');
var app = express();
app.get('/', function(req, res){
res.send('Hi I changed this again!');
});
app.listen(3000, function(){
console.log('App listening on port 3000!');
})
// define the callback function
function light(err, state) {
console.log('Button pushed');
// check the state of the button
// 1 == pressed, 0 == not pressed
if(state == 1) {
// turn LED on
red.writeSync(1);
gree.writeSync(1);
blue.writeSync(1);
} else {
// turn LED off
red.writeSync(0);
gree.writeSync(0);
blue.writeSync(0)
}
}
// pass the callback function to the
// as the first argument to watch()
button.watch(light);
|
Use new API correctly, v2... | #!/usr/bin/python3
'''
Run simulations with parameter samples.
'''
import model
countries = model.datasheet.get_country_list()
# Move these to the front.
countries_to_plot = ['United States of America',
'South Africa',
'Uganda',
'Nigeria',
'India',
'Rwanda']
for c in countries_to_plot:
countries.remove(c)
countries = countries_to_plot + countries
def _run_country(country, target):
print('Running {}, {!s}.'.format(country, target))
parametersamples = model.parameters.Samples(country)
multisim = model.simulation.MultiSim(parametersamples, target)
return multisim
def _main():
for country in countries:
for target in model.target.all_:
if not model.results.exists(country, target):
results = _run_country(country, target)
model.results.dump(results)
if __name__ == '__main__':
_main()
| #!/usr/bin/python3
'''
Run simulations with parameter samples.
'''
import model
countries = model.datasheet.get_country_list()
# Move these to the front.
countries_to_plot = ['United States of America',
'South Africa',
'Uganda',
'Nigeria',
'India',
'Rwanda']
for c in countries_to_plot:
countries.remove(c)
countries = countries_to_plot + countries
def _run_country(country, target):
print('Running {}, {!s}.'.format(country, target))
parametersamples = model.parameters.Samples(country)
multisim = model.multisim.MultiSim(parametersamples, target)
return multisim
def _main():
for country in countries:
for target in model.target.all_:
if not model.results.exists(country, target):
results = _run_country(country, target)
model.results.dump(results)
if __name__ == '__main__':
_main()
|
Add back daily NoAttendanceJediPush job | <?php
declare(strict_types=1);
namespace App\Console;
use App\Jobs\DailyDuesSummary;
use App\Jobs\WeeklyAttendance;
use App\Jobs\NoAttendanceJediPush;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array<string>
*/
protected $commands = [];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
*
* @return void
*/
protected function schedule(Schedule $schedule): void
{
$schedule->command('horizon:snapshot')->everyFiveMinutes();
$schedule->job(new WeeklyAttendance())->weekly()->sundays()->at('11:00');
$schedule->job(new DailyDuesSummary())->daily()->at('11:00');
$schedule->job(new NoAttendanceJediPush())->daily()->at('10:00');
}
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands(): void
{
$this->load(__DIR__.'/Commands');
include base_path('routes/console.php');
}
}
| <?php
declare(strict_types=1);
namespace App\Console;
use App\Jobs\DailyDuesSummary;
use App\Jobs\WeeklyAttendance;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array<string>
*/
protected $commands = [];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
*
* @return void
*/
protected function schedule(Schedule $schedule): void
{
$schedule->command('horizon:snapshot')->everyFiveMinutes();
$schedule->job(new WeeklyAttendance())->weekly()->sundays()->at('11:00');
$schedule->job(new DailyDuesSummary())->daily()->at('11:00');
}
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands(): void
{
$this->load(__DIR__.'/Commands');
include base_path('routes/console.php');
}
}
|
Allow loadenv to only run if env variables are not set | <?php
namespace Dara\Origins;
use PDO;
use Dotenv\Dotenv;
class Connection extends PDO
{
protected static $driver;
protected static $host;
protected static $dbname;
protected static $user;
protected static $pass;
/**
* Get environment values from .env file
*
* @return null
*/
public static function getEnv()
{
if (!isset(getenv('P_DRIVER'))) {
$dotEnv = new Dotenv($_SERVER['DOCUMENT_ROOT']);
$dotEnv->load();
}
self::$driver = getenv('P_DRIVER');
self::$host = getenv('P_HOST');
self::$dbname = getenv('P_DBNAME');
self::$user = getenv('P_USER');
self::$pass = getenv('P_PASS');
}
/**
* Create PDO connections
*
* @return PDO
*/
public static function connect()
{
self::getEnv();
return new PDO(self::$driver.':host='.self::$host.';dbname='.self::$dbname, self::$user, self::$pass);
}
} | <?php
namespace Dara\Origins;
use PDO;
use Dotenv\Dotenv;
class Connection extends PDO
{
protected static $driver;
protected static $host;
protected static $dbname;
protected static $user;
protected static $pass;
/**
* Get environment values from .env file
*
* @return null
*/
public static function getEnv()
{
$dotEnv = new Dotenv($_SERVER['DOCUMENT_ROOT']);
$dotEnv->load();
self::$driver = getenv('P_DRIVER');
self::$host = getenv('P_HOST');
self::$dbname = getenv('P_DBNAME');
self::$user = getenv('P_USER');
self::$pass = getenv('P_PASS');
}
/**
* Create PDO connections
*
* @return PDO
*/
public static function connect()
{
self::getEnv();
return new PDO(self::$driver.':host='.self::$host.';dbname='.self::$dbname, self::$user, self::$pass);
}
} |
Move conditional to chached data | var express = require('express');
var router = express.Router();
var nodemailer = require('nodemailer');
// create reusable transporter object using the default SMTP transport
var smtp = process.env.SMTPCREDENTIALS || '';
var transporter = nodemailer.createTransport(smtp);
var SECRET = process.env.SPASECRET || '';
router.post('/deliverforme', function(req, res, next) {
var data = req.body;
if (data.key !== SECRET) { res.status(400).send(); }
var sended_at = new Date(data.timestamp);
var received_at = new Date(Date.now());
var message = [data['form[content]'],
"\n\nEnviado em ",
sended_at.toString(),
". Processado em ",
received_at.toString()
].join(' ');
var mailOptions = {
to: 'kenner.hp@gmail.com',
from: [data['form[name]'],"<",data['form[email]'],">"].join(' '),
subject: data['form[subject]'],
text: message
};
transporter.sendMail(mailOptions, function(error, info){
if(error){
res.status(403).send(error);
}
res.send(info.response);
});
});
module.exports = router;
| var express = require('express');
var router = express.Router();
var nodemailer = require('nodemailer');
// create reusable transporter object using the default SMTP transport
var smtp = process.env.SMTPCREDENTIALS || '';
var transporter = nodemailer.createTransport(smtp);
var SECRET = process.env.SPASECRET || '';
router.post('/deliverforme', function(req, res, next) {
if (req.body.key !== SECRET) { res.status(400).send(); }
var data = req.body;
var sended_at = new Date(data.timestamp);
var received_at = new Date(Date.now());
var message = [data['form[content]'],
"\n\nEnviado em ",
sended_at.toString(),
". Processado em ",
received_at.toString()
].join(' ');
var mailOptions = {
to: 'kenner.hp@gmail.com',
from: [data['form[name]'],"<",data['form[email]'],">"].join(' '),
subject: data['form[subject]'],
text: message
};
transporter.sendMail(mailOptions, function(error, info){
if(error){
res.status(403).send(error);
}
res.send(info.response);
});
});
module.exports = router;
|
Add some session details for persistent state stuff | <?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
define('MAX_COMIC_STEPS', 10);
session_start();
require_once('libs/Smarty.class.php');
if (empty($_SESSION['comic_seed'])) $_SESSION['comic_seed'] = rand();
if (empty($_SESSION['comic_step'])) $_SESSION['comic_step'] = 0;
if (empty($_SESSION['questions_solved'])) $_SESSION['questions_solved'] = 0;
if (empty($_GET['type'])) $_GET['type'] = 'problem';
if (empty($_GET['randomseed'])) $_GET['randomseed'] = '1';
if (empty($_POST['userinput'])) $_POST['userinput'] = false;
$script_path = '/srv/http/fastmath/MathServer/server.py';
// call python script
ob_start();
system(sprintf("python2 %s %d %s %s", $script_path, escapeshellarg($_GET['randomseed']), escapeshellarg($_GET['type']), escapeshellarg($_POST['userinput'])));
$out = json_decode(ob_get_clean());
print_r($out);
// print out comic
// i.e. pass a seed to the comic generator script
$smarty->assign('comic', array('seed' => $_SESSION['comic_seed'], 'step' => $_SESSION['comic_step']));
// populate template
$smarty = new Smarty;
//$smarty->force_compile = true;
$smarty->debugging = true;
$smarty->caching = true;
$smarty->cache_lifetime = 120;
$smarty->assign("foo","bar");
$smarty->display('tpl/problem.tpl');
| <?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
require_once('libs/Smarty.class.php');
if (empty($_GET['type'])) $_GET['type'] = 'problem';
if (empty($_GET['randomseed'])) $_GET['randomseed'] = '1';
if (empty($_POST['userinput'])) $_POST['userinput'] = false;
$script_path = '/srv/http/fastmath/MathServer/server.py';
// call python script
ob_start();
system(sprintf("python2 %s %d %s %s", $script_path, escapeshellarg($_GET['randomseed']), escapeshellarg($_GET['type']), escapeshellarg($_POST['userinput'])));
$out = json_decode(ob_get_clean());
print_r($out);
// print out comic
// populate template
$smarty = new Smarty;
//$smarty->force_compile = true;
$smarty->debugging = true;
$smarty->caching = true;
$smarty->cache_lifetime = 120;
$smarty->assign("foo","bar");
$smarty->display('tpl/problem.tpl');
|
Add connect flash middleware setup | var express = require('express');
var logger = require('morgan');
var bodyParser = require('body-parser');
var session = require('express-session'); // compatible stores at https://github.com/expressjs/session#compatible-session-stores
var exphbs = require('express-handlebars');
var cookieParser = require('cookie-parser');
var flash = require('connect-flash');
var helmet = require('helmet');
var app = express();
//setup security ===============================================================
require('./app/lib/security-setup')(app, helmet);
// configuration ===============================================================
app.use(logger('dev')); // log every request to the console
// set up our express application ==============================================
// setup connect flash so we can sent messages
app.use(cookieParser('secretString'));
app.use(session({
secret: "@lHJr+JrSwv1W&J904@W%nmWf++K99pRBvk&wBaNAs4JTid1Ji",
resave: false,
saveUninitialized: true
}));
app.use(flash());
// Make the body object available on the request
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//set handlebars as default templating engine
app.engine('handlebars', exphbs({defaultLayout: 'layout'}));
app.set('view engine', 'handlebars');
// serve the static content ====================================================
app.use(express.static(__dirname + '/public'));
// set up global variables =====================================================
// routes ======================================================================
require('./app/routes.js')(app); // load our routes and pass in our app
// export so bin/www can launch ================================================
module.exports = app;
| var express = require('express');
var logger = require('morgan');
var bodyParser = require('body-parser');
var session = require('express-session'); // compatible stores at https://github.com/expressjs/session#compatible-session-stores
var exphbs = require('express-handlebars');
var cookieParser = require('cookie-parser');
var flash = require('connect-flash');
var helmet = require('helmet');
var app = express();
//setup security ===============================================================
require('./app/lib/security-setup')(app, helmet);
// configuration ===============================================================
app.use(logger('dev')); // log every request to the console
// set up our express application ==============================================
// Make the body object available on the request
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//set handlebars as default templating engine
app.engine('handlebars', exphbs({defaultLayout: 'layout'}));
app.set('view engine', 'handlebars');
// serve the static content ====================================================
app.use(express.static(__dirname + '/public'));
// set up global variables =====================================================
// routes ======================================================================
require('./app/routes.js')(app); // load our routes and pass in our app
// export so bin/www can launch ================================================
module.exports = app;
|
Use imageUuid instead of installPath
Signed-off-by: David Lee <15c338f3b79a63a0d5423e9c6562cd312918fe74@gmail.com> | package org.zstack.header.storage.backup;
import org.zstack.header.identity.Action;
import org.zstack.header.image.ImageConstant;
import org.zstack.header.message.APIMessage;
import org.zstack.header.message.APIParam;
@Action(category = ImageConstant.ACTION_CATEGORY)
public class APIExportImageFromBackupStorageMsg extends APIMessage implements BackupStorageMessage {
@APIParam(resourceType = BackupStorageVO.class, checkAccount = true, operationTarget = true)
private String backupStorageUuid;
@APIParam(nonempty = true, maxLength = 2048)
private String imageUuid;
@Override
public String getBackupStorageUuid() {
return backupStorageUuid;
}
public void setBackupStorageUuid(String backupStorageUuid) {
this.backupStorageUuid = backupStorageUuid;
}
public String getImageUuid() {
return imageUuid;
}
public void setImageUuid(String imageUuid) {
this.imageUuid = imageUuid;
}
}
| package org.zstack.header.storage.backup;
import org.zstack.header.identity.Action;
import org.zstack.header.image.ImageConstant;
import org.zstack.header.message.APIMessage;
import org.zstack.header.message.APIParam;
@Action(category = ImageConstant.ACTION_CATEGORY)
public class APIExportImageFromBackupStorageMsg extends APIMessage implements BackupStorageMessage {
@APIParam(resourceType = BackupStorageVO.class, checkAccount = true, operationTarget = true)
private String backupStorageUuid;
@APIParam(nonempty = true, maxLength = 2048)
private String installPath;
@Override
public String getBackupStorageUuid() {
return backupStorageUuid;
}
public void setBackupStorageUuid(String backupStorageUuid) {
this.backupStorageUuid = backupStorageUuid;
}
public String getInstallPath() {
return installPath;
}
public void setInstallPath(String installPath) {
this.installPath = installPath;
}
}
|
Add abstract method from interface | <?php
namespace Larium\Pay\Transaction;
use Larium\Pay\TransactionException;
trait Commit
{
/**
* @var bool
*/
private $committed = false;
abstract public function canCommit();
/**
* {@inheritdoc}
*/
public function commit()
{
if (!$this->canCommit()) {
throw TransactionExeption::unableToCommit();
}
$this->committed = true;
}
/**
* {@inheritdoc}
*/
public function isCommitted()
{
return $this->committed;
}
/**
* {@inheritdoc}
*/
public function allowChanges()
{
if ($this->isCommitted()) {
throw TransactionException::alreadyCommited();
}
return true;
}
}
| <?php
namespace Larium\Pay\Transaction;
use Larium\Pay\TransactionException;
trait Commit
{
/**
* @var bool
*/
private $committed = false;
/**
* {@inheritdoc}
*/
public function commit()
{
if (!$this->canCommit()) {
throw TransactionExeption::unableToCommit();
}
$this->committed = true;
}
/**
* {@inheritdoc}
*/
public function isCommitted()
{
return $this->committed;
}
/**
* {@inheritdoc}
*/
public function allowChanges()
{
if ($this->isCommitted()) {
throw TransactionException::alreadyCommited();
}
return true;
}
}
|
Add support for protocol redirects | #!/usr/bin/env node
'use strict'
var url = require('url')
var normalizeUrl = require('normalize-url')
var chalk = require('chalk')
var arg = normalizeUrl(process.argv[2])
var http = require('http')
var https = require('https')
var start = Date.now()
var hops = 0
follow(arg, start)
function follow (u, ms) {
var opts = url.parse(u)
opts.method = 'HEAD'
var protocol = opts.protocol === 'https:' ? https : http
var req = protocol.request(opts, function (res) {
var diff = Date.now() - ms
console.log(chalk.green('[' + res.statusCode + '] ') + chalk.gray(opts.method) + ' ' + u + chalk.cyan(' (' + diff + ' ms)'))
switch (res.statusCode) {
case 301:
case 303:
case 307:
hops++
follow(res.headers.location, Date.now())
break
default:
diff = Date.now() - start
console.log('Trace finished in ' + chalk.cyan(diff + ' ms') + ' using ' + chalk.cyan(hops + ' hops'))
process.exit(0)
}
})
req.end()
}
| #!/usr/bin/env node
'use strict'
var url = require('url')
var normalizeUrl = require('normalize-url')
var chalk = require('chalk')
var arg = normalizeUrl(process.argv[2])
var http = require(arg.indexOf('https://') === 0 ? 'https' : 'http')
var start = Date.now()
var hops = 0
follow(arg, start)
function follow (u, ms) {
var opts = url.parse(u)
opts.method = 'HEAD'
var req = http.request(opts, function (res) {
var diff = Date.now() - ms
console.log(chalk.green('[' + res.statusCode + '] ') + chalk.gray(opts.method) + ' ' + u + chalk.cyan(' (' + diff + ' ms)'))
switch (res.statusCode) {
case 301:
case 303:
case 307:
hops++
follow(res.headers.location, Date.now())
break
default:
diff = Date.now() - start
console.log('Trace finished in ' + chalk.cyan(diff + ' ms') + ' using ' + chalk.cyan(hops + ' hops'))
process.exit(0)
}
})
req.end()
}
|
Return empty JSON array if IncidentRepository is not yet initialized | package org.stagemonitor.alerting.alerter;
import java.io.IOException;
import java.util.Collections;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.stagemonitor.alerting.AlertingPlugin;
import org.stagemonitor.alerting.incident.IncidentRepository;
import org.stagemonitor.core.Stagemonitor;
import org.stagemonitor.core.util.JsonUtils;
@WebServlet(urlPatterns = "/stagemonitor/incidents")
public class IncidentServlet extends HttpServlet {
private final AlertingPlugin alertingPlugin;
public IncidentServlet() {
this(Stagemonitor.getConfiguration(AlertingPlugin.class));
}
public IncidentServlet(AlertingPlugin alertingPlugin) {
this.alertingPlugin = alertingPlugin;
}
/**
* GET /stagemonitor/incidents
*
* Returns all current incidents
*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
IncidentRepository incidentRepository = alertingPlugin.getIncidentRepository();
if (incidentRepository != null) {
JsonUtils.writeJsonToOutputStream(incidentRepository.getAllIncidents(), resp.getOutputStream());
} else {
JsonUtils.writeJsonToOutputStream(Collections.emptyList(), resp.getOutputStream());
}
}
}
| package org.stagemonitor.alerting.alerter;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.stagemonitor.alerting.AlertingPlugin;
import org.stagemonitor.alerting.incident.IncidentRepository;
import org.stagemonitor.core.Stagemonitor;
import org.stagemonitor.core.util.JsonUtils;
@WebServlet(urlPatterns = "/stagemonitor/incidents")
public class IncidentServlet extends HttpServlet {
private final IncidentRepository incidentRepository;
public IncidentServlet() {
this(Stagemonitor.getConfiguration(AlertingPlugin.class));
}
public IncidentServlet(AlertingPlugin alertingPlugin) {
this.incidentRepository = alertingPlugin.getIncidentRepository();
}
/**
* GET /stagemonitor/incidents
*
* Returns all current incidents
*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
JsonUtils.writeJsonToOutputStream(incidentRepository.getAllIncidents(), resp.getOutputStream());
}
}
|
Remove trailing whitespace in line 27 | package seedu.ezdo.commons.util;
import seedu.ezdo.model.todo.ReadOnlyTask;
//@@author A0139177W
/**
* Utility method for Recur
*/
public class RecurUtil {
/**
* Checks if a recurring status is valid with at least a start date and/or
* due date present in a task. Floating tasks should not have a recurring
* status.
* @param task
* @return false if the task is a floating task
* @return true otherwise
*/
public static boolean isRecurValid(ReadOnlyTask task) {
assert task != null;
String taskStartDate = task.getStartDate().toString();
String taskDueDate = task.getDueDate().toString();
final boolean isStartDateMissing = taskStartDate.isEmpty();
final boolean isDueDateMissing = taskDueDate.isEmpty();
final boolean isBothDatesMissing = isStartDateMissing && isDueDateMissing;
final boolean isRecurring = task.getRecur().isRecur();
if (isBothDatesMissing && isRecurring) {
return false;
}
return true;
}
}
| package seedu.ezdo.commons.util;
import seedu.ezdo.model.todo.ReadOnlyTask;
//@@author A0139177W
/**
* Utility method for Recur
*/
public class RecurUtil {
/**
* Checks if a recurring status is valid with at least a start date and/or
* due date present in a task. Floating tasks should not have a recurring
* status.
* @param task
* @return false if the task is a floating task
* @return true otherwise
*/
public static boolean isRecurValid(ReadOnlyTask task) {
assert task != null;
String taskStartDate = task.getStartDate().toString();
String taskDueDate = task.getDueDate().toString();
final boolean isStartDateMissing = taskStartDate.isEmpty();
final boolean isDueDateMissing = taskDueDate.isEmpty();
final boolean isBothDatesMissing = isStartDateMissing && isDueDateMissing;
final boolean isRecurring = task.getRecur().isRecur();
if (isBothDatesMissing && isRecurring) {
return false;
}
return true;
}
}
|
Use command-line argument to bind server address | import argparse
import zmq
from .databases import Databases
from .worker import Worker
parser = argparse.ArgumentParser("escalator")
parser.add_argument(
'--bind', default='tcp://*:4224',
help="Address to bind escalator server"
)
args = parser.parse_args()
context = zmq.Context()
back_uri = 'inproc://workers'
proxy = zmq.devices.ThreadDevice(
device_type=zmq.QUEUE, in_type=zmq.DEALER, out_type=zmq.ROUTER
)
proxy.bind_out(args.bind)
proxy.bind_in(back_uri)
proxy.start()
print('Starting escalator server on {}'.format(repr(args.bind)))
databases = Databases('dbs')
nb_workers = 8
workers = []
for i in range(nb_workers):
worker = Worker(databases, back_uri)
worker.daemon = True
worker.start()
workers.append(worker)
while proxy.launcher.isAlive():
try:
# If we join the process without a timeout we never
# get the chance to handle the exception
proxy.join(100)
except KeyboardInterrupt:
databases.close()
break
| import zmq
from .databases import Databases
from .worker import Worker
context = zmq.Context()
back_uri = 'inproc://workers'
proxy = zmq.devices.ThreadDevice(
device_type=zmq.QUEUE, in_type=zmq.DEALER, out_type=zmq.ROUTER
)
proxy.bind_out('tcp://*:4224')
proxy.bind_in(back_uri)
proxy.start()
databases = Databases('dbs')
nb_workers = 8
workers = []
for i in range(nb_workers):
worker = Worker(databases, back_uri)
worker.daemon = True
worker.start()
workers.append(worker)
while proxy.launcher.isAlive():
try:
# If we join the process without a timeout we never
# get the chance to handle the exception
proxy.join(100)
except KeyboardInterrupt:
databases.close()
break
|
Use Request and ResponseWriter creators in Server | // Copyright 2016 Marcel Gotsch. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package goserv
import (
"net/http"
)
type TLS struct {
CertFile, KeyFile string
}
type Server struct {
*Router
Addr string
TLS *TLS
}
func (s *Server) Listen(addr string, tls *TLS) error {
if tls != nil {
s.TLS = tls
return http.ListenAndServeTLS(addr, tls.CertFile, tls.KeyFile, s)
}
return http.ListenAndServe(addr, s)
}
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.Router.serveHTTP(newResponseWriter(w), newRequest(r))
}
func NewServer() *Server {
s := &Server{NewRouter(), "", nil}
s.ErrorHandler = StdErrorHandler
return s
}
| // Copyright 2016 Marcel Gotsch. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package goserv
import (
"net/http"
)
type TLS struct {
CertFile, KeyFile string
}
type Server struct {
*Router
Addr string
TLS *TLS
}
func (s *Server) Listen(addr string, tls *TLS) error {
if tls != nil {
s.TLS = tls
return http.ListenAndServeTLS(addr, tls.CertFile, tls.KeyFile, s)
}
return http.ListenAndServe(addr, s)
}
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
res := &responseWriter{w: w}
req := &Request{r, &Context{}, nil, nil, sanitizePath(r.URL.Path)}
s.Router.serveHTTP(res, req)
}
func NewServer() *Server {
s := &Server{NewRouter(), "", nil}
s.ErrorHandler = StdErrorHandler
return s
}
|
Use 2578 as port on example | const LocalDatabaseConnector = require('../shared/local-database-connector')
const os = require('os')
global.instanceId = os.hostname();
const SyncProcessManager = require('./sync-process-manager')
const manager = new SyncProcessManager();
LocalDatabaseConnector.forShared().then((db) => {
const {Account} = db;
Account.findAll().then((accounts) => {
if (accounts.length === 0) {
global.Logger.info(`Couldn't find any accounts to sync. Run this CURL command to auth one!`)
global.Logger.info(`curl -X POST -H "Content-Type: application/json" -d '{"email":"inboxapptest1@fastmail.fm", "name":"Ben Gotow", "provider":"imap", "settings":{"imap_username":"inboxapptest1@fastmail.fm","imap_host":"mail.messagingengine.com","imap_port":993,"smtp_host":"mail.messagingengine.com","smtp_port":0,"smtp_username":"inboxapptest1@fastmail.fm", "smtp_password":"trar2e","imap_password":"trar2e","ssl_required":true}}' "http://localhost:2578/auth?client_id=123"`)
}
manager.ensureAccountIDsInRedis(accounts.map(a => a.id)).then(() => {
manager.start();
})
});
});
global.manager = manager;
| const LocalDatabaseConnector = require('../shared/local-database-connector')
const os = require('os')
global.instanceId = os.hostname();
const SyncProcessManager = require('./sync-process-manager')
const manager = new SyncProcessManager();
LocalDatabaseConnector.forShared().then((db) => {
const {Account} = db;
Account.findAll().then((accounts) => {
if (accounts.length === 0) {
global.Logger.info(`Couldn't find any accounts to sync. Run this CURL command to auth one!`)
global.Logger.info(`curl -X POST -H "Content-Type: application/json" -d '{"email":"inboxapptest1@fastmail.fm", "name":"Ben Gotow", "provider":"imap", "settings":{"imap_username":"inboxapptest1@fastmail.fm","imap_host":"mail.messagingengine.com","imap_port":993,"smtp_host":"mail.messagingengine.com","smtp_port":0,"smtp_username":"inboxapptest1@fastmail.fm", "smtp_password":"trar2e","imap_password":"trar2e","ssl_required":true}}' "http://localhost:5100/auth?client_id=123"`)
}
manager.ensureAccountIDsInRedis(accounts.map(a => a.id)).then(() => {
manager.start();
})
});
});
global.manager = manager;
|
Add code for saving preferences correctly, but only for integers now | import ConfigParser
from gi.repository import Gtk
from pref_mapping import *
from var import *
def read_config_if_exists(filename):
if os.path.isfile(filename):
# Init config parser and read config
Config = ConfigParser.SafeConfigParser()
Config.read(filename)
section = "TorGTKprefs"
# Loop through options
options = Config.options(section)
for option in options:
value = Config.get(section, option)
print objs[pref_mappings[option]]
objs[pref_mappings[option]].set_value(int(value))
def write_config(filename):
# Open file
config_fd = open(filename, "w")
Config = ConfigParser.ConfigParser()
Config.add_section("TorGTKprefs")
# Write sections to file and close it
for key in pref_mappings:
Config.set("TorGTKprefs", key, objs[pref_mappings[key]].get_text())
Config.write(config_fd)
config_fd.close()
| import ConfigParser
from gi.repository import Gtk
from pref_mapping import *
from var import *
def read_config_if_exists(filename):
if os.path.isfile(filename):
# Init config parser and read config
Config = ConfigParser.SafeConfigParser()
Config.read(filename)
section = "TorGTKprefs"
# Loop through options
options = Config.options(section)
for option in options:
value = Config.get(section, option)
objs[pref_mappings[option]].set_text(value)
def write_config(filename):
# Open file
config_fd = open(filename, "w")
Config = ConfigParser.ConfigParser()
Config.add_section("TorGTKprefs")
# Write sections to file and close it
for key in pref_mappings:
Config.set("TorGTKprefs", key, objs[pref_mappings[key]].get_text())
Config.write(config_fd)
config_fd.close()
|
Add new relationship to Investment resource | import six
from .node import Node
@six.python_2_unicode_compatible
class Investment(Node):
"""Represents a Investment (investor-investment) on CrunchBase"""
KNOWN_PROPERTIES = [
'type',
'uuid',
'money_invested',
'money_invested_currency_code',
'money_invested_usd',
]
KNOWN_RELATIONSHIPS = [
'funding_round',
'invested_in',
'investors',
]
def __str__(self):
if self.money_invested:
return u'{invested}'.format(
self.money_invested
)
if hasattr(self, 'investors'):
return u'{investors}'.format(self.investors)
if self.type:
return u'{type}'.format(self.type)
return u'Investment'
def __repr__(self):
return self.__str__()
| import six
from .node import Node
@six.python_2_unicode_compatible
class Investment(Node):
"""Represents a Investment (investor-investment) on CrunchBase"""
KNOWN_PROPERTIES = [
'type',
'uuid',
'money_invested',
'money_invested_currency_code',
'money_invested_usd',
]
KNOWN_RELATIONSHIPS = [
'funding_round',
'invested_in',
]
def __str__(self):
return u'{series} {invested_in}'.format(
series=self.funding_round.series,
invested_in=self.invested_in.name,
)
def __repr__(self):
return self.__str__()
|
Return all poet attributes except password from create method | var _ = require('underscore');
module.exports = function(dbConfig) {
var db = require('./poemlab_database')(dbConfig);
return {
create: function(user_data, callback) {
var params = _.values(_.pick(user_data, ["name", "email", "password"]));
db.query("insert into poets (name, email, password) values ($1, $2, $3) " +
"returning id, name, email", params,
function(err, result) {
if (err) { return callback(err); }
callback(null, result.rows[0]);
}
);
},
read: function(user_id, callback) {
db.query("select * from poets where id = $1", [user_id], function(err, result) {
if (err) { return callback(err); }
callback(null, result.rows[0]);
});
},
destroy: function(user_id, callback) {
db.query("delete from poets where id = $1", [user_id], function(err, result) {
callback(err);
});
},
all: function(callback) {
db.query("select * from poets", [], function(err, result) {
if (err) { return callback(err); }
callback(null, result.rows);
});
}
};
};
| var _ = require('underscore');
module.exports = function(dbConfig) {
var db = require('./poemlab_database')(dbConfig);
return {
create: function(user_data, callback) {
var params = _.values(_.pick(user_data, ["name", "email", "password"]));
db.query("insert into poets (name, email, password) values ($1, $2, $3) returning id", params,
function(err, result) {
if (err) { return callback(err); }
var user = { id: result.rows[0].id };
callback(null, user);
}
);
},
read: function(user_id, callback) {
db.query("select * from poets where id = $1", [user_id], function(err, result) {
if (err) { return callback(err); }
callback(null, result.rows[0]);
});
},
destroy: function(user_id, callback) {
db.query("delete from poets where id = $1", [user_id], function(err, result) {
callback(err);
});
},
all: function(callback) {
db.query("select * from poets", [], function(err, result) {
if (err) { return callback(err); }
callback(null, result.rows);
});
}
};
};
|
Change set options to a different class to ensure that it cannot be accidentally used in place of the real internal property. | /*
* Copyright 2015 The OpenDCT Authors. 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.
*/
package opendct.config.options;
import opendct.nanohttpd.pojo.JsonOption;
public interface DeviceOptions {
/**
* Get all options available for this class.
*
* @return Returns an array of all options available within this class.
*/
public DeviceOption[] getOptions();
/**
* Set all options submitted into this class.
*
* @param deviceOptions The options to be set.
* @throws DeviceOptionException The first option to encounter an error will be returned in this
* exception.
*/
public void setOptions(JsonOption... deviceOptions) throws DeviceOptionException;
}
| /*
* Copyright 2015 The OpenDCT Authors. 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.
*/
package opendct.config.options;
public interface DeviceOptions {
/**
* Get all options available for this class.
*
* @return Returns an array of all options available within this class.
*/
public DeviceOption[] getOptions();
/**
* Set all options submitted into this class.
*
* @param deviceOptions The options to be set.
* @throws DeviceOptionException The first option to encounter an error will be returned in this
* exception.
*/
public void setOptions(DeviceOption... deviceOptions) throws DeviceOptionException;
}
|
Allow names with more than one word | package com.enjin.averian_roleplay.core;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class SetNameCommand implements CommandExecutor {
private AverianCore plugin;
public SetNameCommand(AverianCore plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (sender instanceof Player) {
if (args.length >= 1) {
StringBuilder nameBuilder = new StringBuilder();
for (int i = 0; i < args.length; i++) {
nameBuilder.append(args[i]);
nameBuilder.append(" ");
}
String name = nameBuilder.toString();
Player player = (Player) sender;
plugin.getCharacterCard(player).setName(name);
player.setDisplayName(name);
sender.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("messages.setname.success")));
} else {
sender.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("messages.setname.more-arguments-needed")));
}
} else {
sender.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("messages.setname.not-a-player")));
}
return true;
}
}
| package com.enjin.averian_roleplay.core;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class SetNameCommand implements CommandExecutor {
private AverianCore plugin;
public SetNameCommand(AverianCore plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (sender instanceof Player) {
if (args.length >= 1) {
Player player = (Player) sender;
plugin.getCharacterCard(player).setName(args[0]);
player.setDisplayName(args[0]);
player.setCustomName(args[0]);
player.setCustomNameVisible(true);
sender.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("messages.setname.success")));
} else {
sender.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("messages.setname.more-arguments-needed")));
}
} else {
sender.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("messages.setname.not-a-player")));
}
return true;
}
}
|
Make TOC footer more like Cover footer | @extends('layouts.master')
@section('title')
Claw & Quill: No. {{ $issue->number }}
@endsection
@section('content')
<header id="header">
<div><a class="image" href="/"><img src="/img/cnq-logo.png" alt="Claw & Quill"></a></div>
<h1>No. {{ $issue->number }} · {{ $issue->pub_date->toFormattedDateString() }}</h1>
</header>
<article class="toc">
@if ($issue->title)
<h1>{{ $issue->title }}</h1>
@endif
@foreach ($issue->storiesSorted() as $story)
<h2>{{ HTML::linkAction('IssueController@showStory', $story->title, [$issue->id, $story->slug]) }} <span class="author">{{ $story->author->getPreferredName() }}</span></h2>
{{ $story->getBlurb() }}
@endforeach
</article>
<footer class="toc">
<div class="pull-right">
<p>{{ HTML::linkAction('IssueController@getIndex', 'Issue Index') }} · {{ HTML::linkAction('AuthorController@getIndex', 'Author Index') }}</p>
<p><a href="http://twitter.com/clawandquill">Twitter</a> · {{ HTML::linkAction('HomeController@feed', 'Feed') }}</p>
</div>
<p>{{ HTML::link('/', 'Home') }}</p>
<p>© 2013 Claw & Quill · {{ HTML::linkRoute('page', 'CC BY-NC-SA', ['colophon']) }}</p>
</footer>
@endsection
| @extends('layouts.master')
@section('title')
Claw & Quill: No. {{ $issue->number }}
@endsection
@section('content')
<header id="header">
<div><a class="image" href="/"><img src="/img/cnq-logo.png" alt="Claw & Quill"></a></div>
<h1>No. {{ $issue->number }} · {{ $issue->pub_date->toFormattedDateString() }}</h1>
</header>
<article class="toc">
@if ($issue->title)
<h1>{{ $issue->title }}</h1>
@endif
@foreach ($issue->storiesSorted() as $story)
<h2>{{ HTML::linkAction('IssueController@showStory', $story->title, [$issue->id, $story->slug]) }} <span class="author">{{ $story->author->getPreferredName() }}</span></h2>
{{ $story->getBlurb() }}
@endforeach
</article>
<footer class="toc">
<p>{{ HTML::link('/', 'Home') }} · {{ HTML::linkAction('IssueController@getIndex', 'Issue Index') }}</p>
<p>Copyright 2013 Claw & Quill</p>
</footer>
@endsection
|
Update data chart controller to use route params | define(function() {
var DataChartController = function($rootScope, $routeParams, HubResource, HubSelectionService) {
var self = this
this.isLoaded = false
// Fake promise to get around ig data source
this.dataChart = HubResource.listDataPoints()
// Load data on selection change
$rootScope.$on('HubSelection', function(e, hub) {
self.dataChart = HubResource.listDataPoints({
user: $routeParams.user,
project: $routeParams.project,
hubId: hub._id,
}, function success(dataPoints, headers) {
self.isLoaded = true
})
})
}
DataChartController.$inject = ['$rootScope', '$routeParams', 'HubResource', 'HubSelectionService']
return DataChartController
})
| define(function() {
var DataChartController = function($rootScope, $q, HubResource, HubSelectionService) {
var self = this
this.isLoaded = false
// Fake promise to get around ig data source
this.dataChart = HubResource.listDataPoints()
// Load data on selection change
$rootScope.$on('HubSelection', function(e, hub) {
self.dataChart = HubResource.listDataPoints({
user: 'admin',
project: 'adminProject',
hubId: hub._id,
}, function success(dataPoints, headers) {
self.isLoaded = true
})
})
}
DataChartController.$inject = ['$rootScope', '$q', 'HubResource', 'HubSelectionService']
return DataChartController
})
|
Remove use of deprecated getTagsWithPrefix method | <?php
RequestHandler::$responseMode = 'csv';
RequestHandler::respond('projects', array(
'data' => array_map(function($Project) {
preg_match('/^\s*[^*#]\s*\w.*/m', $Project->README, $matches);
return array(
'name' => $Project->Title
,'description' => trim($matches[0])
,'link_url' => $Project->UsersUrl
,'code_url' => $Project->DevelopersUrl
,'tags' => implode(',',
array_map(
function($Tag) {
return $Tag->UnprefixedTitle;
}
,$Project->TopicTags
)
)
,'status' => $Project->Stage
);
}, Laddr\Project::getAll())
)); | <?php
RequestHandler::$responseMode = 'csv';
RequestHandler::respond('projects', array(
'data' => array_map(function($Project) {
preg_match('/^\s*[^*#]\s*\w.*/m', $Project->README, $matches);
return array(
'name' => $Project->Title
,'description' => trim($matches[0])
,'link_url' => $Project->UsersUrl
,'code_url' => $Project->DevelopersUrl
,'tags' => implode(',',
array_map(
function($Tag) {
return $Tag->UnprefixedTitle;
}
,Tag::getTagsWithPrefix($Project->Tags, 'topic')
)
)
,'status' => $Project->Stage
);
}, Laddr\Project::getAll())
)); |
Add long description for PyPI upload | #!/usr/bin/env python
#
# Author: Logan Gunthorpe <logang@deltatee.com>
# Copyright (c) Deltatee Enterprises Ltd. 2015, All rights reserved.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the License, or (at your option) any later version.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library.
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(name='pyft232',
version='0.8',
description="Python bindings to d2xx and libftdi to access FT232 chips with "
"the same interface as pyserial. Using this method gives easy access "
"to the additional features on the chip like CBUS GPIO.",
long_description=open('README.md', 'rt').read(),
long_description_content_type="text/markdown",
author='Logan Gunthorpe',
author_email='logang@deltatee.com',
packages=['ft232'],
install_requires=[
'pyusb >= 0.4',
'pyserial >= 2.5',
]
)
| #!/usr/bin/env python
#
# Author: Logan Gunthorpe <logang@deltatee.com>
# Copyright (c) Deltatee Enterprises Ltd. 2015, All rights reserved.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the License, or (at your option) any later version.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library.
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(name='pyft232',
version='0.8',
description="Python bindings to d2xx and libftdi to access FT232 chips with "
"the same interface as pyserial. Using this method gives easy access "
"to the additional features on the chip like CBUS GPIO.",
long_description=open('README.md', 'rt').read(),
author='Logan Gunthorpe',
author_email='logang@deltatee.com',
packages=['ft232'],
install_requires=[
'pyusb >= 0.4',
'pyserial >= 2.5',
]
)
|
Use sys.executable when invoking python interpreter from tests
When we only have python3 installed, the test for missing argument is
failing because there is no "python" executable. Use `sys.executable`
instead. Also set environment correctly, like done in 7024d3b36176. | # -*- coding: utf-8 -*-
"""
test_cookiecutter_invocation
----------------------------
Tests to make sure that cookiecutter can be called from the cli without
using the entry point set up for the package.
"""
import os
import pytest
import subprocess
import sys
from cookiecutter import utils
def test_should_raise_error_without_template_arg(monkeypatch, capfd):
monkeypatch.setenv('PYTHONPATH', '.')
with pytest.raises(subprocess.CalledProcessError):
subprocess.check_call([sys.executable, '-m', 'cookiecutter.cli'])
_, err = capfd.readouterr()
exp_message = 'Error: Missing argument "TEMPLATE".'
assert exp_message in err
@pytest.fixture
def project_dir(request):
"""Remove the rendered project directory created by the test."""
rendered_dir = 'fake-project-templated'
def remove_generated_project():
if os.path.isdir(rendered_dir):
utils.rmtree(rendered_dir)
request.addfinalizer(remove_generated_project)
return rendered_dir
@pytest.mark.usefixtures('clean_system')
def test_should_invoke_main(monkeypatch, project_dir):
monkeypatch.setenv('PYTHONPATH', '.')
subprocess.check_call([
sys.executable,
'-m',
'cookiecutter.cli',
'tests/fake-repo-tmpl',
'--no-input'
])
assert os.path.isdir(project_dir)
| # -*- coding: utf-8 -*-
"""
test_cookiecutter_invocation
----------------------------
Tests to make sure that cookiecutter can be called from the cli without
using the entry point set up for the package.
"""
import os
import pytest
import subprocess
import sys
from cookiecutter import utils
def test_should_raise_error_without_template_arg(capfd):
with pytest.raises(subprocess.CalledProcessError):
subprocess.check_call(['python', '-m', 'cookiecutter.cli'])
_, err = capfd.readouterr()
exp_message = 'Error: Missing argument "TEMPLATE".'
assert exp_message in err
@pytest.fixture
def project_dir(request):
"""Remove the rendered project directory created by the test."""
rendered_dir = 'fake-project-templated'
def remove_generated_project():
if os.path.isdir(rendered_dir):
utils.rmtree(rendered_dir)
request.addfinalizer(remove_generated_project)
return rendered_dir
@pytest.mark.usefixtures('clean_system')
def test_should_invoke_main(monkeypatch, project_dir):
monkeypatch.setenv('PYTHONPATH', '.')
subprocess.check_call([
sys.executable,
'-m',
'cookiecutter.cli',
'tests/fake-repo-tmpl',
'--no-input'
])
assert os.path.isdir(project_dir)
|
Include README in package cf. PyPA recommendation
http://python-packaging.readthedocs.io/en/latest/metadata.html#a-readme-long-description | import os
from setuptools import setup, find_packages
__version__ = '0.1'
HERE = os.path.dirname(__file__)
def readme():
with open('README.rst') as f:
return f.read()
setup(
name='rubberjack-cli',
version=__version__,
packages=find_packages(exclude=['test*']),
include_package_data=True,
zip_safe=True,
# metadata for upload to PyPI
author='LaterPay GmbH',
url='https://github.com/laterpay/rubberjack-cli',
description='RubberJack manages (AWS) Elastic Beanstalks',
long_description=readme(),
license='MIT',
keywords='aws',
install_requires=[
'boto',
'click',
],
classifiers=[
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.5",
],
entry_points={
'console_scripts': [
'rubberjack=rubberjackcli.click:rubberjack',
],
},
)
| import os
from setuptools import setup, find_packages
__version__ = '0.1'
HERE = os.path.dirname(__file__)
try:
long_description = open(os.path.join(HERE, 'README.rst')).read()
except:
long_description = None
setup(
name='rubberjack-cli',
version=__version__,
packages=find_packages(exclude=['test*']),
include_package_data=True,
zip_safe=True,
# metadata for upload to PyPI
author='LaterPay GmbH',
url='https://github.com/laterpay/rubberjack-cli',
description='RubberJack manages (AWS) Elastic Beanstalks',
long_description=long_description,
license='MIT',
keywords='aws',
install_requires=[
'boto',
'click',
],
classifiers=[
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.5",
],
entry_points={
'console_scripts': [
'rubberjack=rubberjackcli.click:rubberjack',
],
},
)
|
Make mailer test a bit more inclusive. | package authboss
import (
"bytes"
"strings"
"testing"
)
func TestMailer(t *testing.T) {
mailServer := &bytes.Buffer{}
config := NewConfig()
config.Mailer = LogMailer(mailServer)
config.Storer = mockStorer{}
Init(config)
err := SendMail(Email{
To: []string{"some@email.com", "a@a.com"},
ToNames: []string{"Jake", "Noname"},
From: "some@guy.com",
FromName: "Joseph",
ReplyTo: "an@email.com",
Subject: "Email!",
TextBody: "No html here",
HTMLBody: "<html>body</html>",
})
if err != nil {
t.Error(err)
}
if mailServer.Len() == 0 {
t.Error("It should have logged the e-mail.")
}
str := mailServer.String()
if !strings.Contains(str, "From: Joseph <some@guy.com>") {
t.Error("From line not present.")
}
if !strings.Contains(str, "To: Jake <some@email.com>, Noname <a@a.com>") {
t.Error("To line not present.")
}
if !strings.Contains(str, "No html here") {
t.Error("Text body not present.")
}
if !strings.Contains(str, "<html>body</html>") {
t.Error("Html body not present.")
}
}
| package authboss
import (
"bytes"
"strings"
"testing"
)
func TestMailer(t *testing.T) {
mailServer := &bytes.Buffer{}
config := NewConfig()
config.Mailer = LogMailer(mailServer)
config.Storer = mockStorer{}
Init(config)
err := SendMail(Email{
To: []string{"some@email.com", "a@a.com"},
ToNames: []string{"Jake", "Noname"},
From: "some@guy.com",
FromName: "Joseph",
ReplyTo: "an@email.com",
Subject: "Email!",
TextBody: "No html here",
HTMLBody: "<html>body</html>",
})
if err != nil {
t.Error(err)
}
if mailServer.Len() == 0 {
t.Error("It should have logged the e-mail.")
}
str := mailServer.String()
if !strings.Contains(str, "From: Joseph <some@guy.com>") {
t.Error("From line not present.")
}
if !strings.Contains(str, "To: Jake <some@email.com>, Noname <a@a.com>") {
t.Error("To line not present.")
}
}
|
Add 'active' class bindings for component that is added when Aviary Editor is launched and removed with Aviary's 'onClose' callback | import Ember from 'ember';
export default Ember.Component.extend({
aviaryApiClient: null, // injected
classNames: ['edit-icon'],
classNameBindings: ['featherActive:active'],
image: null,
url: null,
imageSelector: null,
closeOnSave: false,
featherActive: false,
imageToEdit: function() {
var imageNotSet = Ember.isEmpty(this.get('image'));
var selector = this.get('imageSelector');
return imageNotSet ? this.get('parentView').$(selector || 'img') : this.get('image');
}.property('parentView', 'image', 'imageSelector'),
click: function() {
var self = this;
var options = {
image: this.get('imageToEdit'),
url: this.get('url'),
onSave: function(imageId, src) {
self.send('onSave', imageId, src);
},
onClose: function() {
self.send('onClose');
}
};
this.aviaryApiClient.launch(options);
this.set('featherActive', true);
return false;
},
actions: {
onSave: function(imageId, src) {
this.sendAction('onSave', imageId, src);
var closeOnSave = this.get('closeOnSave');
var featherEditor = this.aviaryApiClient.get('featherEditor');
if(closeOnSave) { featherEditor.close(); }
},
onClose: function() {
this.set('featherActive', false);
}
}
});
| import Ember from 'ember';
export default Ember.Component.extend({
aviaryApiClient: null, // injected
classNames: ['edit-icon'],
image: null,
url: null,
imageSelector: null,
closeOnSave: false,
imageToEdit: function() {
var imageNotSet = Ember.isEmpty(this.get('image'));
var selector = this.get('imageSelector');
return imageNotSet ? this.get('parentView').$(selector || 'img') : this.get('image');
}.property('parentView', 'image', 'imageSelector'),
click: function() {
var self = this;
var options = {
image: this.get('imageToEdit'),
url: this.get('url'),
onSave: function(imageId, src) {
self.send('onSave', imageId, src);
}
};
this.aviaryApiClient.launch(options);
return false;
},
actions: {
onSave: function(imageId, src) {
this.sendAction('onSave', imageId, src);
var closeOnSave = this.get('closeOnSave');
var featherEditor = this.aviaryApiClient.get('featherEditor');
if(closeOnSave) { featherEditor.close(); }
}
}
});
|
Add reporting unit URL to region serializer. | import json
from rest_framework import serializers
from django.core.urlresolvers import reverse
from landscapesim.models import Region
class ReportingUnitSerializer(serializers.Serializer):
type = serializers.SerializerMethodField()
properties = serializers.SerializerMethodField()
geometry = serializers.SerializerMethodField()
class Meta:
fields = ('type', 'geometry', 'properties',)
def get_type(self, obj):
return 'Feature'
def get_geometry(self, obj):
return json.loads(obj.polygon.json)
def get_properties(self, obj):
return {
'id': obj.id,
'unit_id': obj.unit_id,
'name': obj.name
}
class RegionSerializer(serializers.ModelSerializer):
url = serializers.SerializerMethodField()
class Meta:
model = Region
fields = ('id', 'name', 'url')
def get_url(self, obj):
return reverse('region-reporting-units', args=[obj.id])
| import json
from rest_framework import serializers
from landscapesim.models import Region
class ReportingUnitSerializer(serializers.Serializer):
type = serializers.SerializerMethodField()
properties = serializers.SerializerMethodField()
geometry = serializers.SerializerMethodField()
class Meta:
fields = ('type', 'geometry', 'properties',)
def get_type(self, obj):
return 'Feature'
def get_geometry(self, obj):
return json.loads(obj.polygon.json)
def get_properties(self, obj):
return {
'id': obj.id,
'unit_id': obj.unit_id,
'name': obj.name
}
class RegionSerializer(serializers.ModelSerializer):
class Meta:
model = Region
fields = ('id', 'name')
|
Set campaign and region to null by default
Campaign and region are getting passed down by the dashboard view
from the dropdowns, so there is no need to provide defaults in the
NCO dashboard component. | 'use strict';
module.exports = {
template: require('./nco.html'),
data: function () {
return {
region : null,
campaign: null,
overview: [{
title : 'Influencer',
indicators: [164,165,166,167],
chart : 'chart-bar'
}, {
title : 'Information Source',
indicators: [164,165,166,167],
chart : 'chart-bar'
}, {
title : 'Reasons for Missed',
indicators: [164,165,166,167],
chart : 'chart-bar'
}, {
title : 'Reasons for Absence',
indicators: [164,165,166,167],
chart : 'chart-bar'
}, {
title : 'Reasons for NC',
indicators: [164,165,166,167],
chart : 'chart-bar'
}, {
title : 'NC Resolved by',
indicators: [164,165,166,167],
chart : 'chart-bar'
}]
};
},
components: {
}
};
| 'use strict';
module.exports = {
template: require('./nco.html'),
data: function () {
return {
region : 12907,
campaign: true, // Trick with-indicator into loading without a campaign
overview: [{
title : 'Influencer',
indicators: [164,165,166,167],
chart : 'chart-bar'
}, {
title : 'Information Source',
indicators: [164,165,166,167],
chart : 'chart-bar'
}, {
title : 'Reasons for Missed',
indicators: [164,165,166,167],
chart : 'chart-bar'
}, {
title : 'Reasons for Absence',
indicators: [164,165,166,167],
chart : 'chart-bar'
}, {
title : 'Reasons for NC',
indicators: [164,165,166,167],
chart : 'chart-bar'
}, {
title : 'NC Resolved by',
indicators: [164,165,166,167],
chart : 'chart-bar'
}]
};
},
components: {
}
};
|
Add missing import of `Path` | """
byceps.config_defaults
~~~~~~~~~~~~~~~~~~~~~~
Default configuration values
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from datetime import timedelta
from pathlib import Path
# database connection
SQLALCHEMY_ECHO = False
# Disable Flask-SQLAlchemy's tracking of object modifications.
SQLALCHEMY_TRACK_MODIFICATIONS = False
# job queue
JOBS_ASYNC = True
# metrics
METRICS_ENABLED = False
# RQ dashboard (for job queue)
RQ_DASHBOARD_ENABLED = False
RQ_POLL_INTERVAL = 2500
WEB_BACKGROUND = 'white'
# login sessions
PERMANENT_SESSION_LIFETIME = timedelta(14)
# localization
LOCALE = 'de_DE.UTF-8'
LOCALES_FORMS = ['de']
TIMEZONE = 'Europe/Berlin'
# static content files path
PATH_DATA = Path('./data')
# home page
ROOT_REDIRECT_TARGET = None
ROOT_REDIRECT_STATUS_CODE = 307
# shop
SHOP_ORDER_EXPORT_TIMEZONE = 'Europe/Berlin'
| """
byceps.config_defaults
~~~~~~~~~~~~~~~~~~~~~~
Default configuration values
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from datetime import timedelta
# database connection
SQLALCHEMY_ECHO = False
# Disable Flask-SQLAlchemy's tracking of object modifications.
SQLALCHEMY_TRACK_MODIFICATIONS = False
# job queue
JOBS_ASYNC = True
# metrics
METRICS_ENABLED = False
# RQ dashboard (for job queue)
RQ_DASHBOARD_ENABLED = False
RQ_POLL_INTERVAL = 2500
WEB_BACKGROUND = 'white'
# login sessions
PERMANENT_SESSION_LIFETIME = timedelta(14)
# localization
LOCALE = 'de_DE.UTF-8'
LOCALES_FORMS = ['de']
TIMEZONE = 'Europe/Berlin'
# static content files path
PATH_DATA = Path('./data')
# home page
ROOT_REDIRECT_TARGET = None
ROOT_REDIRECT_STATUS_CODE = 307
# shop
SHOP_ORDER_EXPORT_TIMEZONE = 'Europe/Berlin'
|
Fix crashing error caused when network_console isn't accessible. | <?php
namespace Dan\Core;
use Dan\Events\Event;
use Illuminate\Support\ServiceProvider;
class ExceptionServiceProvider extends ServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
events()->subscribe('console.exception')
->priority(Event::VeryHigh)
->handler(function (\Throwable $exception) {
$to = formatLocation(config('dan.network_console'));
$file = relativePath($exception->getFile());
if (empty($to)) {
return;
}
$to['channel']->message("Exception was thrown. {$exception->getMessage()} - On line {$exception->getLine()} of {$file}");
});
}
} | <?php
namespace Dan\Core;
use Dan\Events\Event;
use Illuminate\Support\ServiceProvider;
class ExceptionServiceProvider extends ServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
events()->subscribe('console.exception')
->priority(Event::VeryHigh)
->handler(function (\Throwable $exception) {
$to = formatLocation(config('dan.network_console'));
$file = relativePath($exception->getFile());
$to['channel']->message("Exception was thrown. {$exception->getMessage()} - On line {$exception->getLine()} of {$file}");
});
}
} |
Convert percentage to a value between 0 and 1 | #!/usr/bin/env python3
import psutil
import os
import time
def create_bar(filled):
low = '.'
high = '|'
if filled > 1:
low = str(int(filled))
high = str(int(filled + 1))
filled = filled - int(filled)
filled = int(filled * 10)
if filled < 5:
color = "green"
elif filled < 8:
color = "yellow"
else:
color = "red"
bar = '#[fg=' + color + ']['
bar += high * filled
bar += low * (10 - filled)
bar += ']#[fg=default]'
return bar
while True:
meminfo = psutil.virtual_memory()
numcpus = psutil.cpu_count()
with open(os.path.expanduser("~/.memblock"), "w") as memblock:
memblock.write(create_bar((meminfo.total - meminfo.available) / meminfo.total))
with open(os.path.expanduser("~/.cpuutilblock"), "w") as cpuutilblock:
cpuutilblock.write(create_bar(psutil.cpu_percent() / 100))
time.sleep(20)
| #!/usr/bin/env python
import psutil
import os
import time
def create_bar(filled):
low = '.'
high = '|'
if filled > 1:
low = str(int(filled))
high = str(int(filled + 1))
filled = filled - int(filled)
filled = int(filled * 10)
if filled < 5:
color = "green"
elif filled < 8:
color = "yellow"
else:
color = "red"
bar = '#[fg=' + color + ']['
bar += high * filled
bar += low * (10 - filled)
bar += ']#[fg=default]'
return bar
while True:
meminfo = psutil.virtual_memory()
numcpus = psutil.cpu_count()
with open(os.path.expanduser("~/.memblock"), "w") as memblock:
memblock.write(create_bar((meminfo.total - meminfo.available) / meminfo.total))
with open(os.path.expanduser("~/.cpuutilblock"), "w") as cpuutilblock:
cpuutilblock.write(create_bar(psutil.cpu_percent()))
time.sleep(20)
|
Fix insert() method for related models. | <?php namespace Laravel\Database\Eloquent\Relationships;
use Laravel\Database\Eloquent\Model;
class Has_One_Or_Many extends Relationship {
/**
* Insert a new record for the association.
*
* @param Model|array $attributes
* @return bool
*/
public function insert($attributes)
{
if ($attributes instanceof Model)
{
$attributes->set_attribute($this->foreign_key(), $this->base->get_key());
return $attributes->save();
}
else
{
$attributes[$this->foreign_key()] = $this->base->get_key();
return $this->model->create($attributes);
}
}
/**
* Update a record for the association.
*
* @param array $attributes
* @return bool
*/
public function update(array $attributes)
{
if ($this->model->timestamps())
{
$attributes['updated_at'] = new \DateTime;
}
return $this->table->update($attributes);
}
/**
* Set the proper constraints on the relationship table.
*
* @return void
*/
protected function constrain()
{
$this->table->where($this->foreign_key(), '=', $this->base->get_key());
}
/**
* Set the proper constraints on the relationship table for an eager load.
*
* @param array $results
* @return void
*/
public function eagerly_constrain($results)
{
$this->table->where_in($this->foreign_key(), $this->keys($results));
}
} | <?php namespace Laravel\Database\Eloquent\Relationships;
use Laravel\Database\Eloquent\Model;
class Has_One_Or_Many extends Relationship {
/**
* Insert a new record for the association.
*
* @param Model|array $attributes
* @return bool
*/
public function insert($attributes)
{
$attributes = ($attributes instanceof Model) ? $attributes->attributes : $attributes;
$attributes[$this->foreign_key()] = $this->base->get_key();
return $this->model->create($attributes);
}
/**
* Update a record for the association.
*
* @param array $attributes
* @return bool
*/
public function update(array $attributes)
{
if ($this->model->timestamps())
{
$attributes['updated_at'] = new \DateTime;
}
return $this->table->update($attributes);
}
/**
* Set the proper constraints on the relationship table.
*
* @return void
*/
protected function constrain()
{
$this->table->where($this->foreign_key(), '=', $this->base->get_key());
}
/**
* Set the proper constraints on the relationship table for an eager load.
*
* @param array $results
* @return void
*/
public function eagerly_constrain($results)
{
$this->table->where_in($this->foreign_key(), $this->keys($results));
}
} |
Add a fallback redirect in case an error occurs
In case something goes wrong while adding new minutes,
the user is now redirected to something that most
likely exists. Should be extended to redirect the
user to an error page that explains what happened.
Or the meetingseries/:_id page with a flash message/
modal box, that explains what happened.
Important: Really redirect the user, otherwise the
minutesadd/:_id page will be re-rendered because
minutesAdd changes the meeting series document.
Re-rendering potentially causes re-adding of new
minutes which might trap the user in an endless loop,
creating numerous new minutes. | import { MeetingSeries } from '/imports/meetingseries'
Router.configure({
// set default application template for all routes
layoutTemplate: 'appLayout'
});
Router.route('/', {name: 'home'});
Router.route('/meetingseries/:_id', function () {
var meetingSeriesID = this.params._id;
this.render('meetingSeriesDetails', {data: meetingSeriesID});
});
Router.route('/minutesadd/:_id', function () {
let meetingSeriesID = this.params._id;
ms = new MeetingSeries(meetingSeriesID);
let id;
ms.addNewMinutes(newMinutesID => {
id = newMinutesID;
});
// callback should have been called by now
if (id) {
this.redirect('/minutesedit/' + id);
} else {
// todo: use error page
this.redirect('/meetingseries/' + meetingSeriesID);
}
});
Router.route('/minutesedit/:_id', function () {
var minutesID = this.params._id;
this.render('minutesedit', {data: minutesID});
});
| import { MeetingSeries } from '/imports/meetingseries'
Router.configure({
// set default application template for all routes
layoutTemplate: 'appLayout'
});
Router.route('/', {name: 'home'});
Router.route('/meetingseries/:_id', function () {
var meetingSeriesID = this.params._id;
this.render('meetingSeriesDetails', {data: meetingSeriesID});
});
Router.route('/minutesadd/:_id', function () {
let meetingSeriesID = this.params._id;
ms = new MeetingSeries(meetingSeriesID);
let id = '';
ms.addNewMinutes(newMinutesID => {
id = newMinutesID;
});
this.redirect('/minutesedit/' + id);
});
Router.route('/minutesedit/:_id', function () {
var minutesID = this.params._id;
this.render('minutesedit', {data: minutesID});
});
|
Adjust limited mouse based camera movement |
var GNOVEL = GNOVEL || {};
(function() {
"use strict";
/**
* @class MouseMovedCamera
* If created, will enable effect of mouse moved camera (small shift in the camera's direction vector according to mouse movement)
* @param {[GNOVEL.Gnovel]} gnovel
* @constructor
*/
var MouseMovedCamera = function(gnovel) {
this._gnovel = gnovel;
document.addEventListener('mousemove', function(event) {onDocumentMouseMove(event, gnovel);}, false);
};
function onDocumentMouseMove( event, gnovelObj ) {
var mouseX = -( event.clientX - window.innerWidth / 2 ) / 4;
var mouseY = ( event.clientY - window.innerHeight / 2 ) / 4;
var camera = gnovelObj.getCamera();
camera.position.x += ( mouseX - camera.position.x ) * .005;
camera.position.y += ( mouseY - camera.position.y ) * .005;
camera.position.x = THREE.Math.clamp(camera.position.x, -60, 60);
camera.position.y = THREE.Math.clamp(camera.position.y, -18, 18);
console.log(mouseY + " " + camera.position.y);
camera.lookAt(new THREE.Vector3(0, 0, 400));
};
GNOVEL.MouseMovedCamera = MouseMovedCamera;
}()); |
var GNOVEL = GNOVEL || {};
(function() {
"use strict";
/**
* @class MouseMovedCamera
* If created, will enable effect of mouse moved camera (small shift in the camera's direction vector according to mouse movement)
* @param {[GNOVEL.Gnovel]} gnovel
* @constructor
*/
var MouseMovedCamera = function(gnovel) {
this._gnovel = gnovel;
document.addEventListener('mousemove', function(event) {onDocumentMouseMove(event, gnovel);}, false);
};
function onDocumentMouseMove( event, gnovelObj ) {
var mouseX = -( event.clientX - window.innerWidth / 2 ) / 4;
var mouseY = ( event.clientY - window.innerHeight / 2 ) / 4;
var camera = gnovelObj.getCamera();
camera.position.x += ( mouseX - camera.position.x ) * .005;
camera.position.y += ( mouseY - camera.position.y ) * .005;
camera.position.x = THREE.Math.clamp(camera.position.x, -60, 60);
camera.position.y = THREE.Math.clamp(camera.position.y, -40, 40);
console.log(mouseY + " " + camera.position.y);
camera.lookAt(new THREE.Vector3(0, 0, 400));
};
GNOVEL.MouseMovedCamera = MouseMovedCamera;
}()); |
Remove OperationalError and ProgrammingError imports | # -*- coding: utf-8 -*-
# Generated by Django 1.11.22 on 2019-10-31 16:33
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('ratechecker', '0001_initial'),
]
operations = [
migrations.AlterUniqueTogether(
name='fee',
unique_together=set([]),
),
migrations.RemoveField(
model_name='fee',
name='plan',
),
migrations.DeleteModel(
name='Fee',
),
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.11.22 on 2019-10-31 16:33
from __future__ import unicode_literals
from django.db import migrations, OperationalError, ProgrammingError
class Migration(migrations.Migration):
dependencies = [
('ratechecker', '0001_initial'),
]
operations = [
migrations.AlterUniqueTogether(
name='fee',
unique_together=set([]),
),
migrations.RemoveField(
model_name='fee',
name='plan',
),
migrations.DeleteModel(
name='Fee',
),
]
|
Remove vet check for desktop notifications in AppTokenUtil. | const AppTokenUtil = {
getAppTokensBasedOnQuery: getAppTokensBasedOnQuery
};
function getAppTokensBasedOnQuery(query, desktopAppId) {
let userDisabledMap = new Map();
let userIdsSet = new Set();
let appTokens = Push.appTokens.find(query).fetch();
if (!appTokens.length) {
return [];
}
if (desktopAppId) {
return appTokens;
}
appTokens.forEach(function (appToken) {
if (appToken.userId) {
userIdsSet.add(appToken.userId);
}
});
let vet = GlobalVets.findOne({appIdentifier: appTokens[0].appName});
if (!vet) {
return [];
}
let users = Meteor.users.find({_id: {$in: [...userIdsSet]}}).fetch();
users.forEach(user => {
let isUserDisabled = user.accountDisabledPerVet && user.accountDisabledPerVet[vet._id];
userDisabledMap.set(user._id, isUserDisabled);
});
return appTokens.filter(appToken => {
return !(appToken.userId && userDisabledMap.get(appToken.userId));
});
}
export {AppTokenUtil};
| const AppTokenUtil = {
getAppTokensBasedOnQuery: getAppTokensBasedOnQuery
};
function getAppTokensBasedOnQuery(query, desktopAppId) {
let userDisabledMap = new Map();
let userIdsSet = new Set();
let appTokens = Push.appTokens.find(query).fetch();
if (!appTokens.length) {
return [];
}
appTokens.forEach(function (appToken) {
if (appToken.userId) {
userIdsSet.add(appToken.userId);
}
});
let vet = GlobalVets.findOne({appIdentifier: appTokens[0].appName});
if (!vet && desktopAppId) {
vet = GlobalVets.findOne({_id: desktopAppId});
}
if (!vet) {
console.log(`Couldn't find vet for id ${desktopAppId} or app identifier ${appTokens[0].appName}`);
return false;
}
let users = Meteor.users.find({_id: {$in: [...userIdsSet]}}).fetch();
users.forEach(user => {
let isUserDisabled = user.accountDisabledPerVet && user.accountDisabledPerVet[vet._id];
userDisabledMap.set(user._id, isUserDisabled);
});
return appTokens.filter(appToken => {
return !(appToken.userId && userDisabledMap.get(appToken.userId));
});
}
export {AppTokenUtil};
|
Remove default param on slm locale for redirect error | <?php
/**
* SlmLocale Configuration
*
* If you have a ./config/autoload/ directory set up for your project, you can
* drop this config file in it and change the values as you wish.
*/
$settings = array(
/**
* Default locale
*
* Some good description here. Default is something
*
* Accepted is something else
*/
//'default' => 'en-US',
/**
* Supported locales
*
* Some good description here. Default is something
*
* Accepted is something else
*/
'supported' => array('en', 'ar'),
/**
* Aliases for locales
*
* Some good description here. Default is something
*
* Accepted is something else
*/
'aliases' => array('ar' => 'ar-IQ', 'en' => 'en-US'),
/**
* Strategies
*
* Some good description here. Default is something
*
* Accepted is something else
*/
'strategies' => array('uripath', 'acceptlanguage'),
/**
* Throw exception when no locale is found
*
* Some good description here. Default is something
*
* Accepted is something else
*/
//'throw_exception' => false,
/**
* End of SlmLocale configuration
*/
);
/**
* You do not need to edit below this line
*/
return array(
'slm_locale' => $settings
);
| <?php
/**
* SlmLocale Configuration
*
* If you have a ./config/autoload/ directory set up for your project, you can
* drop this config file in it and change the values as you wish.
*/
$settings = array(
/**
* Default locale
*
* Some good description here. Default is something
*
* Accepted is something else
*/
'default' => '',
/**
* Supported locales
*
* Some good description here. Default is something
*
* Accepted is something else
*/
'supported' => array('', 'ar'),
/**
* Aliases for locales
*
* Some good description here. Default is something
*
* Accepted is something else
*/
'aliases' => array('ar' => 'ar-IQ', '' => 'en-US'),
/**
* Strategies
*
* Some good description here. Default is something
*
* Accepted is something else
*/
'strategies' => array('uripath', 'acceptlanguage'),
/**
* Throw exception when no locale is found
*
* Some good description here. Default is something
*
* Accepted is something else
*/
//'throw_exception' => false,
/**
* End of SlmLocale configuration
*/
);
/**
* You do not need to edit below this line
*/
return array(
'slm_locale' => $settings
);
|
Update provider test to ensure default credentials were found. | package softlayer
import (
"testing"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/terraform"
)
var testAccProviders map[string]terraform.ResourceProvider
var testAccProvider *schema.Provider
func init() {
testAccProvider = Provider().(*schema.Provider)
testAccProviders = map[string]terraform.ResourceProvider{
"softlayer": testAccProvider,
}
}
func TestProvider(t *testing.T) {
if err := Provider().(*schema.Provider).InternalValidate(); err != nil {
t.Fatalf("err: %s", err)
}
}
func TestProvider_impl(t *testing.T) {
var _ terraform.ResourceProvider = Provider()
}
func testAccPreCheck(t *testing.T) {
for _, param := range []string{"username", "api_key", "endpoint_url"} {
value, _ := testAccProvider.Schema[param].DefaultFunc()
if value == "" {
t.Fatalf("A SoftLayer %s was not found. Read gopherlayer docs for how to configure this.", param)
}
}
}
| package softlayer
import (
"os"
"testing"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/terraform"
)
var testAccProviders map[string]terraform.ResourceProvider
var testAccProvider *schema.Provider
func init() {
testAccProvider = Provider().(*schema.Provider)
testAccProviders = map[string]terraform.ResourceProvider{
"softlayer": testAccProvider,
}
}
func TestProvider(t *testing.T) {
if err := Provider().(*schema.Provider).InternalValidate(); err != nil {
t.Fatalf("err: %s", err)
}
}
func TestProvider_impl(t *testing.T) {
var _ terraform.ResourceProvider = Provider()
}
func testAccPreCheck(t *testing.T) {
if v := os.Getenv("SOFTLAYER_USERNAME"); v == "" {
t.Fatal("SOFTLAYER_USERNAME must be set for acceptance tests")
}
if v := os.Getenv("SOFTLAYER_API_KEY"); v == "" {
t.Fatal("SOFTLAYER_API_KEY must be set for acceptance tests")
}
}
|
Add twig global var Facebook app id info | <?php
/*
* 이 컨트롤러를 상속받아 구현하는 컨트롤러는 Twig 템플릿 엔진을 기본으로 로드함
*/
class MY_Controller extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('twig');
$this->load->helper('url');
$this->config->load('facebook');
// Twig 관련 글로벌 설정은 이곳 또는 application/libraries/Twig.php 에 작성
$this->twig->addGlobal('session', $_SESSION);
$this->twig->addGlobal('facebook_app_id', $this->config->item('app_id'));
if ($this->accountlib->is_login() === false) {
redirect('/account/login');
} elseif ($this->accountlib->is_auth() === false) {
redirect('/account/not_authenticated');
}
}
}
if (!class_exists('API_Controller')) {
require_once APPPATH . 'core/API_Controller.php';
}
| <?php
/*
* 이 컨트롤러를 상속받아 구현하는 컨트롤러는 Twig 템플릿 엔진을 기본으로 로드함
*/
class MY_Controller extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('twig');
$this->load->helper('url');
// Twig 관련 글로벌 설정은 이곳 또는 application/libraries/Twig.php 에 작성
$this->twig->addGlobal('session', $_SESSION);
if ($this->accountlib->is_login() === false) {
redirect('/account/login');
} elseif ($this->accountlib->is_auth() === false) {
redirect('/account/not_authenticated');
}
}
}
if (!class_exists('API_Controller')) {
require_once APPPATH . 'core/API_Controller.php';
}
|
Add license meta for pypi
Add license meta for pypi. | from setuptools import setup
setup(
name='guzzle_sphinx_theme',
version='0.7.11',
description='Sphinx theme used by Guzzle.',
long_description=open('README.rst').read(),
author='Michael Dowling',
author_email='mtdowling@gmail.com',
url='https://github.com/guzzle/guzzle_sphinx_theme',
packages=['guzzle_sphinx_theme'],
include_package_data=True,
install_requires=['Sphinx>1.3'],
license="MIT",
classifiers=(
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
),
)
| from setuptools import setup
setup(
name='guzzle_sphinx_theme',
version='0.7.11',
description='Sphinx theme used by Guzzle.',
long_description=open('README.rst').read(),
author='Michael Dowling',
author_email='mtdowling@gmail.com',
url='https://github.com/guzzle/guzzle_sphinx_theme',
packages=['guzzle_sphinx_theme'],
include_package_data=True,
install_requires=['Sphinx>1.3'],
classifiers=(
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
),
)
|
Add uniform API for public body widgets | from django import forms
from django.utils.translation import ugettext_lazy as _
from froide.helper.form_utils import JSONMixin
from .models import PublicBody
from .widgets import PublicBodySelect
class PublicBodyForm(JSONMixin, forms.Form):
publicbody = forms.ModelChoiceField(
queryset=PublicBody.objects.all(),
widget=PublicBodySelect,
label=_("Search for a topic or a public body:")
)
def as_data(self):
data = super(PublicBodyForm, self).as_data()
if self.is_bound and self.is_valid():
data['cleaned_data'] = self.cleaned_data
return data
def get_publicbodies(self):
if self.is_valid():
return [self.cleaned_data['publicbody']]
return []
class MultiplePublicBodyForm(JSONMixin, forms.Form):
publicbody = forms.ModelMultipleChoiceField(
queryset=PublicBody.objects.all(),
label=_("Search for a topic or a public body:")
)
def get_publicbodies(self):
if self.is_valid():
return self.cleaned_data['publicbody']
return []
| from django import forms
from django.utils.translation import ugettext_lazy as _
from froide.helper.form_utils import JSONMixin
from .models import PublicBody
from .widgets import PublicBodySelect
class PublicBodyForm(JSONMixin, forms.Form):
publicbody = forms.ModelChoiceField(
queryset=PublicBody.objects.all(),
widget=PublicBodySelect,
label=_("Search for a topic or a public body:")
)
def as_data(self):
data = super(PublicBodyForm, self).as_data()
if self.is_bound and self.is_valid():
data['cleaned_data'] = self.cleaned_data
return data
class MultiplePublicBodyForm(JSONMixin, forms.Form):
publicbody = forms.ModelMultipleChoiceField(
queryset=PublicBody.objects.all(),
label=_("Search for a topic or a public body:")
)
|
Use static properties for the sub-items | "use strict"
import Context from "./context"
import ShadowTree from "./shadowtree"
import PHPStrictError from "./phpstricterror"
class Lint {
static get PHPStrictError() {
return PHPStrictError
}
static get ShadowTree() {
return ShadowTree
}
constructor(tree, filename = null, namespace = []) {
Object.assign(
this,
{
filename: filename,
namespace: namespace,
tree: tree,
}
);
}
check() {
return ShadowTree.Node.typed(this.tree).check(new Context());
}
static check(tree, filename = null) {
var l = new Lint(tree, filename);
return l.check();
}
};
module.exports = Lint;
| "use strict"
import Context from "./context"
import ShadowTree from "./shadowtree"
class Lint {
constructor(tree, filename = null, namespace = []) {
Object.assign(
this,
{
filename: filename,
namespace: namespace,
tree: tree,
}
);
}
check() {
return ShadowTree.Node.typed(this.tree).check(new Context());
}
static check(tree, filename = null) {
var l = new Lint(tree, filename);
return l.check();
}
};
import PHPStrictError from "./phpstricterror"
Lint.PHPStrictError = PHPStrictError
Lint.ShadowTree = ShadowTree
module.exports = Lint;
|
Remove hack by only importing when configured | import logging
from airflow import configuration
from airflow.executors.base_executor import BaseExecutor
from airflow.executors.local_executor import LocalExecutor
from airflow.executors.sequential_executor import SequentialExecutor
from airflow.utils import AirflowException
_EXECUTOR = configuration.get('core', 'EXECUTOR')
if _EXECUTOR == 'LocalExecutor':
DEFAULT_EXECUTOR = LocalExecutor()
elif _EXECUTOR == 'CeleryExecutor':
from airflow.executors.celery_executor import CeleryExecutor
DEFAULT_EXECUTOR = CeleryExecutor()
elif _EXECUTOR == 'SequentialExecutor':
DEFAULT_EXECUTOR = SequentialExecutor()
elif _EXECUTOR == 'MesosExecutor':
from airflow.contrib.executors.mesos_executor import MesosExecutor
DEFAULT_EXECUTOR = MesosExecutor()
else:
# Loading plugins
from airflow.plugins_manager import executors as _executors
for _executor in _executors:
globals()[_executor.__name__] = _executor
if _EXECUTOR in globals():
DEFAULT_EXECUTOR = globals()[_EXECUTOR]()
else:
raise AirflowException("Executor {0} not supported.".format(_EXECUTOR))
logging.info("Using executor " + _EXECUTOR)
| import logging
from airflow import configuration
from airflow.executors.base_executor import BaseExecutor
from airflow.executors.local_executor import LocalExecutor
from airflow.executors.sequential_executor import SequentialExecutor
# TODO Fix this emergency fix
try:
from airflow.executors.celery_executor import CeleryExecutor
except:
pass
try:
from airflow.contrib.executors.mesos_executor import MesosExecutor
except:
pass
from airflow.utils import AirflowException
_EXECUTOR = configuration.get('core', 'EXECUTOR')
if _EXECUTOR == 'LocalExecutor':
DEFAULT_EXECUTOR = LocalExecutor()
elif _EXECUTOR == 'CeleryExecutor':
DEFAULT_EXECUTOR = CeleryExecutor()
elif _EXECUTOR == 'SequentialExecutor':
DEFAULT_EXECUTOR = SequentialExecutor()
elif _EXECUTOR == 'MesosExecutor':
DEFAULT_EXECUTOR = MesosExecutor()
else:
# Loading plugins
from airflow.plugins_manager import executors as _executors
for _executor in _executors:
globals()[_executor.__name__] = _executor
if _EXECUTOR in globals():
DEFAULT_EXECUTOR = globals()[_EXECUTOR]()
else:
raise AirflowException("Executor {0} not supported.".format(_EXECUTOR))
logging.info("Using executor " + _EXECUTOR)
|
Remove duplicate case from switch | // created to start cleaning up "window" interaction
//
window.show = function(id) {
window.hideall();
runHooks("paneChanged", id);
switch(id) {
case 'all':
case 'faction':
case 'alerts':
window.chat.show(id);
break;
case 'debug':
window.debug.console.show();
break;
case 'map':
window.smartphone.mapButton.click();
$('#portal_highlight_select').show();
$('#farm_level_select').show();
break;
case 'info':
window.smartphone.sideButton.click();
break;
}
if (typeof android !== 'undefined' && android && android.switchToPane) {
android.switchToPane(id);
}
}
window.hideall = function() {
$('#chatcontrols, #chat, #chatinput, #sidebartoggle, #scrollwrapper, #updatestatus, #portal_highlight_select').hide();
$('#farm_level_select').hide();
$('#map').css('visibility', 'hidden');
$('.ui-tooltip').remove();
}
| // created to start cleaning up "window" interaction
//
window.show = function(id) {
window.hideall();
runHooks("paneChanged", id);
switch(id) {
case 'all':
case 'faction':
case 'alerts':
window.chat.show(id);
break;
case 'alerts':
window.chat.show('alerts');
break;
case 'debug':
window.debug.console.show();
break;
case 'map':
window.smartphone.mapButton.click();
$('#portal_highlight_select').show();
$('#farm_level_select').show();
break;
case 'info':
window.smartphone.sideButton.click();
break;
}
if (typeof android !== 'undefined' && android && android.switchToPane) {
android.switchToPane(id);
}
}
window.hideall = function() {
$('#chatcontrols, #chat, #chatinput, #sidebartoggle, #scrollwrapper, #updatestatus, #portal_highlight_select').hide();
$('#farm_level_select').hide();
$('#map').css('visibility', 'hidden');
$('.ui-tooltip').remove();
}
|
Fix asset `asyncErrorHandling`, use valid global instance of `wTools` |
require( 'wTesting' );
// const _ = require( 'wTools' );
const _ = _globals_.testing.wTools;
_.include( 'wConsequence' );
//
function asyncErrorHandling( test )
{
_.Consequence.UncaughtTimeOut = 1;
let con = new _.Consequence().take( null )
// /*
// In first case error is handled right after creation and tester has time to perform the check.
// This case can be commented out.
// */
//
// .then( () =>
// {
// test.case = 'catch handler before test check'
// let ready = new _.Consequence().error( 'Test' );
// ready.catch( ( err ) =>
// {
// _.errAttend( err )
// throw err;
// })
// return test.shouldThrowErrorOfAnyKind( ready );
// })
/*
In second case error is not handled right after creation and
uncaught async error is thrown before tester perform the check
This case doesn't work as expected.
*/
.then( () =>
{
test.case = 'no catch handler before test check';
let ready = new _.Consequence().error( 'Test' );
debugger;
return test.shouldThrowErrorAsync( ready );
})
/* */
return con;
}
//
const Proto =
{
name : 'AsyncErrorHandling',
tests :
{
asyncErrorHandling
}
}
//
const Self = wTestSuite( Proto );
if( typeof module !== 'undefined' && !module.parent )
wTester.test( Self.name );
|
require( 'wTesting' );
const _ = require( 'wTools' );
_.include( 'wConsequence' );
//
function asyncErrorHandling( test )
{
_.Consequence.UncaughtTimeOut = 1;
let con = new _.Consequence().take( null )
// /*
// In first case error is handled right after creation and tester has time to perform the check.
// This case can be commented out.
// */
//
// .then( () =>
// {
// test.case = 'catch handler before test check'
// let ready = new _.Consequence().error( 'Test' );
// ready.catch( ( err ) =>
// {
// _.errAttend( err )
// throw err;
// })
// return test.shouldThrowErrorOfAnyKind( ready );
// })
/*
In second case error is not handled right after creation and
uncaught async error is thrown before tester perform the check
This case doesn't work as expected.
*/
.then( () =>
{
test.case = 'no catch handler before test check';
let ready = new _.Consequence().error( 'Test' );
debugger;
return test.shouldThrowErrorAsync( ready );
})
/* */
return con;
}
//
const Proto =
{
name : 'AsyncErrorHandling',
tests :
{
asyncErrorHandling
}
}
//
const Self = wTestSuite( Proto );
if( typeof module !== 'undefined' && !module.parent )
wTester.test( Self.name );
|
Return the json from the parser method | from bs4 import BeautifulSoup
from requests.auth import HTTPBasicAuth
import requests
import json
def parse_content():
rs = requests.get('http://soundspectra.com/admin/', auth=HTTPBasicAuth('admin', 'h@ckm3'))
html_data = rs.text
soup = BeautifulSoup(html_data)
details = {'stream_details' : []}
details_list = []
alt = 1
key = None
for td in soup.find_all('td'):
if alt:
if td.get('width') and td.get('width') == '130':
key = td.text
alt = not alt
elif not alt:
if td.get('class') and td.get('class')[0] == 'streamdata':
alt = not alt
value = td.text
d = {key.encode("utf-8") : value.encode("utf-8")}
details_list.append(d)
details['stream_details'] = details_list
return details
if __name__ == '__main__':
details = parse_content()
print details
| from bs4 import BeautifulSoup
from requests.auth import HTTPBasicAuth
import requests
import json
def parse_content():
rs = requests.get('http://soundspectra.com/admin/', auth=HTTPBasicAuth('admin', 'h@ckm3'))
html_data = rs.text
soup = BeautifulSoup(html_data)
details = {'stream_details' : []}
details_list = []
alt = 1
key = None
for td in soup.find_all('td'):
if alt:
if td.get('width') and td.get('width') == '130':
key = td.text
alt = not alt
elif not alt:
if td.get('class') and td.get('class')[0] == 'streamdata':
alt = not alt
value = td.text
d = {key.encode("utf-8") : value.encode("utf-8")}
details_list.append(d)
details['stream_details'] = details_list
print details
if __name__ == '__main__':
parse_content() |
Use the src directory instead of the src/levels directory as the cwd. | # Copyright 2013 Daniel Stokes, Mitchell Stokes
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import os
from bge import logic
def init():
if ".." not in sys.path:
os.chdir(logic.expandPath("//../"))
sys.path.append(".")
try:
from scripts.state import StartupState, DefaultState
from scripts.framework.state import StateSystem
if ('dostartup' in sys.argv):
logic.state_system = StateSystem(StartupState)
else:
print("Skipping startup")
logic.state_system = StateSystem(DefaultState)
except:
import traceback
traceback.print_exc()
logic.state_system = None
def run():
try:
logic.state_system
except AttributeError:
init()
if not logic.state_system:
return
logic.state_system.update()
| # Copyright 2013 Daniel Stokes, Mitchell Stokes
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import os
from bge import logic
def init():
if ".." not in sys.path:
os.chdir(logic.expandPath("//"))
sys.path.append("..")
try:
from scripts.state import StartupState, DefaultState
from scripts.framework.state import StateSystem
if ('dostartup' in sys.argv):
logic.state_system = StateSystem(StartupState)
else:
print("Skipping startup")
logic.state_system = StateSystem(DefaultState)
except:
import traceback
traceback.print_exc()
logic.state_system = None
def run():
try:
logic.state_system
except AttributeError:
init()
if not logic.state_system:
return
logic.state_system.update()
|
Set default isPremium=true on Account/Plan to happify sqlite | <?php
namespace Application\Migrations;
use SimplyTestable\BaseMigrationsBundle\Migration\BaseMigration,
Doctrine\DBAL\Schema\Schema;
/**
* Auto-generated Migration: Please modify to your need!
*/
class Version20130607130241_add_AccountPlan_isPremium extends BaseMigration
{
public function up(Schema $schema)
{
$this->statements['mysql'] = array(
"ALTER TABLE AccountPlan ADD isPremium TINYINT(1) NOT NULL"
);
$this->statements['sqlite'] = array(
"ALTER TABLE AccountPlan ADD isPremium TINYINT(1) NOT NULL DEFAULT 1",
);
parent::up($schema);
}
public function down(Schema $schema)
{
$this->addCommonStatement("ALTER TABLE AccountPlan DROP isPremium");
parent::down($schema);
}
}
| <?php
namespace Application\Migrations;
use SimplyTestable\BaseMigrationsBundle\Migration\BaseMigration,
Doctrine\DBAL\Schema\Schema;
/**
* Auto-generated Migration: Please modify to your need!
*/
class Version20130607130241_add_AccountPlan_isPremium extends BaseMigration
{
public function up(Schema $schema)
{
$this->statements['mysql'] = array(
"ALTER TABLE AccountPlan ADD isPremium TINYINT(1) NOT NULL"
);
$this->statements['sqlite'] = array(
"ALTER TABLE AccountPlan ADD isPremium TINYINT(1) NOT NULL",
);
parent::up($schema);
}
public function down(Schema $schema)
{
$this->addCommonStatement("ALTER TABLE AccountPlan DROP isPremium");
parent::down($schema);
}
}
|
Remove the dependecy of QtGui from a test located in QtNetwork. | import unittest
from PySide.QtCore import *
from PySide.QtNetwork import *
from helper import UsesQCoreApplication
from httpd import TestServer
class testAuthenticationSignal(UsesQCoreApplication):
def setUp(self):
super(testAuthenticationSignal, self).setUp()
self.httpd = TestServer(secure=True)
self.httpd.start()
self._resultOk = False
def tearDown(self):
self.httpd.shutdown()
del self.httpd
super(testAuthenticationSignal, self).tearDown()
def onAuthRequest(self, hostname, port, auth):
self.assert_(isinstance(auth, QAuthenticator))
self._resultOk = True
self.app.quit()
def testwaitSignal(self):
http = QHttp()
http.setHost("localhost", self.httpd.port())
http.connect(SIGNAL("authenticationRequired(const QString&, quint16, QAuthenticator*)"), self.onAuthRequest)
path = QUrl.toPercentEncoding("/index.html", "!$&'()*+,;=:@/")
data = http.get(path)
self.app.exec_()
self.assert_(self._resultOk)
if __name__ == '__main__':
unittest.main()
| import unittest
from PySide.QtCore import *
from PySide.QtNetwork import *
from helper import UsesQApplication
from httpd import TestServer
class testAuthenticationSignal(UsesQApplication):
def setUp(self):
super(testAuthenticationSignal, self).setUp()
self.httpd = TestServer(secure=True)
self.httpd.start()
self._resultOk = False
def tearDown(self):
self.httpd.shutdown()
del self.httpd
super(testAuthenticationSignal, self).tearDown()
def onAuthRequest(self, hostname, port, auth):
self.assert_(isinstance(auth, QAuthenticator))
self._resultOk = True
self.app.quit()
def testwaitSignal(self):
http = QHttp()
http.setHost("localhost", self.httpd.port())
http.connect(SIGNAL("authenticationRequired(const QString&, quint16, QAuthenticator*)"), self.onAuthRequest)
path = QUrl.toPercentEncoding("/index.html", "!$&'()*+,;=:@/")
data = http.get(path)
self.app.exec_()
self.assert_(self._resultOk)
if __name__ == '__main__':
unittest.main()
|
Include queued date in MQ messages | from tapiriik.database import db
from tapiriik.messagequeue import mq
from tapiriik.sync import Sync
from datetime import datetime
from pymongo.read_preferences import ReadPreference
import kombu
import time
Sync.InitializeWorkerBindings()
producer = kombu.Producer(Sync._channel, Sync._exchange)
while True:
queueing_at = datetime.utcnow()
users = db.users.find(
{
"NextSynchronization": {"$lte": datetime.utcnow()}
},
{
"_id": True,
"SynchronizationHostRestriction": True
},
read_preference=ReadPreference.PRIMARY
)
scheduled_ids = set()
for user in users:
producer.publish({"user_id": str(user["_id"]), "queued_at": queueing_at}, routing_key=user["SynchronizationHostRestriction"] if "SynchronizationHostRestriction" in user and user["SynchronizationHostRestriction"] else "")
scheduled_ids.add(user["_id"])
print("Scheduled %d users at %s" % (len(scheduled_ids), datetime.utcnow()))
db.users.update({"_id": {"$in": list(scheduled_ids)}}, {"$set": {"QueuedAt": queueing_at}, "$unset": {"NextSynchronization": True}}, multi=True)
time.sleep(1)
| from tapiriik.database import db
from tapiriik.messagequeue import mq
from tapiriik.sync import Sync
from datetime import datetime
from pymongo.read_preferences import ReadPreference
import kombu
import time
Sync.InitializeWorkerBindings()
producer = kombu.Producer(Sync._channel, Sync._exchange)
while True:
queueing_at = datetime.utcnow()
users = db.users.find(
{
"NextSynchronization": {"$lte": datetime.utcnow()}
},
{
"_id": True,
"SynchronizationHostRestriction": True
},
read_preference=ReadPreference.PRIMARY
)
scheduled_ids = set()
for user in users:
producer.publish(str(user["_id"]), routing_key=user["SynchronizationHostRestriction"] if "SynchronizationHostRestriction" in user and user["SynchronizationHostRestriction"] else "")
scheduled_ids.add(user["_id"])
print("Scheduled %d users at %s" % (len(scheduled_ids), datetime.utcnow()))
db.users.update({"_id": {"$in": list(scheduled_ids)}}, {"$set": {"QueuedAt": queueing_at}, "$unset": {"NextSynchronization": True}}, multi=True)
time.sleep(1)
|
Use tests from spec (extended for nested example) | 'use strict'
const jsonPointer = require('../lib')
const expect = require('chai').expect
const testDoc = {
foo: ['bar', 'baz'],
person: { name: { firstName: 'bob' } },
'': 0,
'a/b': 1,
'c%d': 2,
'e^f': 3,
'g|h': 4,
'i\\j': 5,
'k\"l': 6,
' ': 7,
'm~n': 8
}
it('dereferences root document', function () {
const pointer = ''
const result = jsonPointer.get(testDoc, pointer)
expect(result).to.deep.equal(testDoc)
})
it('dereferences first level node', function () {
const pointer = '/foo'
const result = jsonPointer.get(testDoc, pointer)
expect(result).to.deep.equal(['bar', 'baz'])
})
it('dereferences nested node', function () {
const pointer = 'person/name/firstName'
const result = jsonPointer.get(testDoc, pointer)
expect(result).to.deep.equal('bob')
})
it('dereferences array elements', function () {
const pointer = '/foo/0'
const result = jsonPointer.get(testDoc, pointer)
expect(result).to.be.deep.equal('bar')
})
| 'use strict'
const jsonPointer = require('../lib')
const expect = require('chai').expect
it('dereferences root document', function () {
const doc = {
name: {
firstName: 'Joe',
secondName: 'Smith'
}
}
const pointer = ''
const result = jsonPointer.get(doc, pointer)
expect(result).to.deep.equal(doc)
})
it('dereferences first level node', function () {
const doc = {
name: {
firstName: 'Joe',
secondName: 'Smith'
}
}
const pointer = 'name'
const result = jsonPointer.get(doc, pointer)
expect(result).to.deep.equal(doc.name)
})
it('dereferences nested node', function () {
const doc = {
person: {
name: {
firstName: 'Joe',
secondName: 'Smith'
}
}
}
const pointer = 'person/name/firstName'
const result = jsonPointer.get(doc, pointer)
expect(result).to.deep.equal(doc.person.name.firstName)
})
|
Update WIND to new loader format | define(['mac/roman'], function(macintoshRoman) {
'use strict';
return function(item) {
return item.getBytes().then(function(bytes) {
var dataDV = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
var dataObject = {
initialRectangle: {
top: dataDV.getInt16(0, false),
left: dataDV.getInt16(2, false),
bottom: dataDV.getInt16(4, false),
right: dataDV.getInt16(6, false),
},
definitionID: dataDV.getInt16(8, false),
visible: dataDV.getInt16(10, false),
closeBox: dataDV.getInt16(12, false),
referenceConstant: dataDV.getInt32(14, false),
};
dataObject.title = macintoshRoman(bytes, 19, bytes[18]);
var pos = 19 + bytes[18];
if (pos+2 <= bytes.length) {
dataObject.positioning = dataDV.getInt16(pos);
}
item.setDataObject(dataObject);
});
};
});
| define(['mac/roman'], function(macintoshRoman) {
'use strict';
return function(resource) {
var dataDV = new DataView(resource.data.buffer, resource.data.byteOffset, resource.data.byteLength);
resource.dataObject = {
initialRectangle: {
top: dataDV.getInt16(0, false),
left: dataDV.getInt16(2, false),
bottom: dataDV.getInt16(4, false),
right: dataDV.getInt16(6, false),
},
definitionID: dataDV.getInt16(8, false),
visible: dataDV.getInt16(10, false),
closeBox: dataDV.getInt16(12, false),
referenceConstant: dataDV.getInt32(14, false),
};
resource.dataObject.title = macintoshRoman(resource.data, 19, resource.data[18]);
var pos = 19 + resource.data[18];
if (pos+2 <= resource.data.length) {
resource.dataObject.positioning = dataDV.getInt16(pos);
}
};
});
|
Use dictionary lookup only once | from __future__ import absolute_import
import six
from sentry.api.serializers import Serializer, register
from sentry.models import Commit, CommitFileChange
from sentry.api.serializers.models.release import get_users_for_commits
@register(CommitFileChange)
class CommitFileChangeSerializer(Serializer):
def get_attrs(self, item_list, user):
commits = Commit.objects.filter(id__in=[f.commit_id for f in item_list]).select_related('author')
author_objs = get_users_for_commits(commits)
commits_by_id = {commit.id: commit for commit in commits}
result = {}
for item in item_list:
commit = commits_by_id[item.commit_id]
result[item] = {
'user': author_objs.get(commit.author_id, {}),
'message': commit.message
}
return result
def serialize(self, obj, attrs, user):
return {
'id': six.text_type(obj.id),
'org_id': obj.organization_id,
'author': attrs.get('user', {}),
'commit_message': attrs.get('message', ''),
'filename': obj.filename,
'type': obj.type
}
| from __future__ import absolute_import
import six
from sentry.api.serializers import Serializer, register
from sentry.models import Commit, CommitFileChange
from sentry.api.serializers.models.release import get_users_for_commits
@register(CommitFileChange)
class CommitFileChangeSerializer(Serializer):
def get_attrs(self, item_list, user):
commits = Commit.objects.filter(id__in=[f.commit_id for f in item_list]).select_related('author')
author_objs = get_users_for_commits(commits)
commits_by_id = {commit.id: commit for commit in commits}
result = {}
for item in item_list:
result[item] = {
'user': author_objs.get(commits_by_id[item.commit_id].author_id, {}),
'message': commits_by_id[item.commit_id].message
}
return result
def serialize(self, obj, attrs, user):
return {
'id': six.text_type(obj.id),
'org_id': obj.organization_id,
'author': attrs.get('user', {}),
'commit_message': attrs.get('message', ''),
'filename': obj.filename,
'type': obj.type
}
|
Comment out dotenv for heroku deployment | 'use strict';
var express = require('express');
var routes = require('./app/routes/index.js');
var mongoose = require('mongoose');
var passport = require('passport');
var session = require('express-session');
var bodyParser = require('body-parser')
var app = express();
// require('dotenv').load();
require('./app/config/passport')(passport);
mongoose.connect(process.env.MONGO_URI);
mongoose.Promise = global.Promise;
// Configure server to parse JSON for us
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use('/controllers', express.static(process.cwd() + '/app/controllers'));
app.use('/public', express.static(process.cwd() + '/public'));
app.use(session({
secret: 'secretClementine',
resave: false,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
routes(app, passport);
var port = process.env.PORT || 8080;
app.listen(port, function () {
console.log('Node.js listening on port ' + port + '...');
});
| 'use strict';
var express = require('express');
var routes = require('./app/routes/index.js');
var mongoose = require('mongoose');
var passport = require('passport');
var session = require('express-session');
var bodyParser = require('body-parser')
var app = express();
require('dotenv').load();
require('./app/config/passport')(passport);
mongoose.connect(process.env.MONGO_URI);
mongoose.Promise = global.Promise;
// Configure server to parse JSON for us
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use('/controllers', express.static(process.cwd() + '/app/controllers'));
app.use('/public', express.static(process.cwd() + '/public'));
app.use(session({
secret: 'secretClementine',
resave: false,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
routes(app, passport);
var port = process.env.PORT || 8080;
app.listen(port, function () {
console.log('Node.js listening on port ' + port + '...');
});
|
CRM-4573: Add ability to save multiple values for patch API | <?php
namespace Oro\Bundle\EntityBundle\Tests\Functional\DataFixtures;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Oro\Bundle\OrganizationBundle\Entity\BusinessUnit;
class LoadBusinessUnitData extends AbstractFixture implements ContainerAwareInterface
{
/** @var ContainerInterface */
protected $container;
/**
* {@inheritdoc}
*/
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
/**
* {@inheritdoc}
*/
public function load(ObjectManager $manager)
{
$organization = $manager->getRepository('OroOrganizationBundle:Organization')->getFirst();
$businessUnit = new BusinessUnit();
$businessUnit->setOrganization($organization);
$businessUnit->setName('TestBusinessUnit');
$manager->persist($businessUnit);
$this->setReference('TestBusinessUnit', $businessUnit);
$manager->flush();
}
}
|
<?php
namespace Oro\Bundle\EntityBundle\Tests\Functional\DataFixtures;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Oro\Bundle\OrganizationBundle\Entity\BusinessUnit;
class LoadBusinessUnitData extends AbstractFixture implements ContainerAwareInterface
{
/** @var ContainerInterface */
protected $container;
/**
* {@inheritdoc}
*/
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
/**
* {@inheritdoc}
*/
public function load(ObjectManager $manager)
{
$organization = $manager->getRepository('OroOrganizationBundle:Organization')->getFirst();
$businessUnit = new BusinessUnit();
$businessUnit->setOrganization($organization);
$businessUnit->setName('TestBusinessUnit');
$manager->persist($businessUnit);
$this->setReference('TestBusinessUnit', $businessUnit);
$manager->flush();
}
}
|
Fix bug of adding the id to the resulting data | import json
from lettuce import step, world
@step(u'post "([^"]*)" records?')
def post_record(step, model_name):
world.path = '/data/%s' % str(model_name.lower())
for record in step.hashes:
data = json.dumps(record)
world.response = world.browser.post(world.path, params=data, status='*')
@step(u'obtain a record id')
def obtain_a_record_id(step):
assert 'id' in world.response.json
@step(u'retrieve the "([^"]*)" records')
def retrieve_records(step, model_name):
world.path = '/data/%s' % str(model_name.lower())
world.response = world.browser.get(world.path, status='*')
@step(u'results are :')
def results_are(step):
results = world.response.json['data']
assert len(results) >= len(step.hashes)
for i, result in enumerate(results):
step.hashes[i]['id'] = result['id'] # We cannot guess it
assert result == step.hashes[i]
| import json
from lettuce import step, world
@step(u'post "([^"]*)" records?')
def post_record(step, model_name):
world.path = '/data/%s' % str(model_name.lower())
for record in step.hashes:
data = json.dumps(record)
world.response = world.browser.post(world.path, params=data, status='*')
@step(u'obtain a record id')
def obtain_a_record_id(step):
assert 'id' in world.response.json
@step(u'retrieve the "([^"]*)" records')
def retrieve_records(step, model_name):
world.path = '/data/%s' % str(model_name.lower())
world.response = world.browser.get(world.path, status='*')
@step(u'results are :')
def results_are(step):
results = world.response.json['data']
assert len(results) >= len(step.hashes)
for i, result in enumerate(results):
assert result == step.hashes[i]
|
Add one more empty line to end of import to adjust to H306 | #!/usr/bin/env python
import argparse
import sys
import cv2
import numpy
import six.moves.cPickle as pickle
parser = argparse.ArgumentParser(description='Compute images mean array')
parser.add_argument('dataset', help='Path to training image-label list file')
parser.add_argument('--output', '-o', default='mean.npy',
help='path to output mean array')
args = parser.parse_args()
sum_image = None
count = 0
for line in open(args.dataset):
filepath = line.strip().split()[0]
image = cv2.imread(filepath)
image = image[:, :, [2, 1, 0]].transpose(2, 0, 1)
if sum_image is None:
sum_image = numpy.ndarray(image.shape, dtype=numpy.float32)
sum_image[:] = image
else:
sum_image += image
count += 1
sys.stderr.write('\r{}'.format(count))
sys.stderr.flush()
sys.stderr.write('\n')
mean = sum_image / count
pickle.dump(mean, open(args.output, 'wb'), -1)
| #!/usr/bin/env python
import argparse
import sys
import cv2
import numpy
import six.moves.cPickle as pickle
parser = argparse.ArgumentParser(description='Compute images mean array')
parser.add_argument('dataset', help='Path to training image-label list file')
parser.add_argument('--output', '-o', default='mean.npy',
help='path to output mean array')
args = parser.parse_args()
sum_image = None
count = 0
for line in open(args.dataset):
filepath = line.strip().split()[0]
image = cv2.imread(filepath)
image = image[:, :, [2, 1, 0]].transpose(2, 0, 1)
if sum_image is None:
sum_image = numpy.ndarray(image.shape, dtype=numpy.float32)
sum_image[:] = image
else:
sum_image += image
count += 1
sys.stderr.write('\r{}'.format(count))
sys.stderr.flush()
sys.stderr.write('\n')
mean = sum_image / count
pickle.dump(mean, open(args.output, 'wb'), -1)
|
Disable DB vacuum cleanup step and it was not the root cause of the
problem. | package com.vaguehope.onosendai.update;
import android.content.Intent;
import com.vaguehope.onosendai.images.HybridBitmapCache;
import com.vaguehope.onosendai.storage.AttachmentStorage;
import com.vaguehope.onosendai.storage.DbBindingService;
import com.vaguehope.onosendai.util.LogWrapper;
/*
* TODO move this class?
*/
public class CleanupService extends DbBindingService {
protected static final LogWrapper LOG = new LogWrapper("CS");
public CleanupService () {
super("OnosendaiCleanupService", LOG);
}
@Override
protected void doWork (final Intent i) {
try {
AttachmentStorage.cleanTempOutputDir(this); // FIXME what if attachment in use in Outbox?
HybridBitmapCache.cleanCacheDir(this);
if (!waitForDbReady()) return;
// getDb().vacuum();
LOG.i("Clean up complete.");
}
catch (final Exception e) { // NOSONAR want to log all errors.
LOG.e("Clean up failed.", e);
}
}
}
| package com.vaguehope.onosendai.update;
import android.content.Intent;
import com.vaguehope.onosendai.images.HybridBitmapCache;
import com.vaguehope.onosendai.storage.AttachmentStorage;
import com.vaguehope.onosendai.storage.DbBindingService;
import com.vaguehope.onosendai.util.LogWrapper;
/*
* TODO move this class?
*/
public class CleanupService extends DbBindingService {
protected static final LogWrapper LOG = new LogWrapper("CS");
public CleanupService () {
super("OnosendaiCleanupService", LOG);
}
@Override
protected void doWork (final Intent i) {
try {
AttachmentStorage.cleanTempOutputDir(this); // FIXME what if attachment in use in Outbox?
HybridBitmapCache.cleanCacheDir(this);
if (!waitForDbReady()) return;
getDb().vacuum();
LOG.i("Clean up complete.");
}
catch (final Exception e) { // NOSONAR want to log all errors.
LOG.e("Clean up failed.", e);
}
}
}
|
Add cDatePublic to indexed page list | <?
/**
*
* A wrapper class for results from the search engine, allowing for abstraction in case search engines are changed in the future.
* @package Utilities
* @subpackage Search
*/
defined('C5_EXECUTE') or die("Access Denied.");
class Concrete5_Library_IndexedPageList extends PageList {
protected $indexModeSimple = false;
public function setSimpleIndexMode($indexModeSimple) {
$this->indexModeSimple = $indexModeSimple;
}
public function getPage() {
if ($this->indexModeSimple) {
$this->sortBy('cDatePublic', 'desc');
} else {
$this->sortByMultiple('cIndexScore desc', 'cDatePublic desc');
}
$r = parent::getPage();
$results = array();
foreach($r as $c) {
$results[] = array('cID' => $c->getCollectionID(), 'cName' => $c->getCollectionName(), 'cDescription' => $c->getCollectionDescription(), 'score' => $c->getPageIndexScore(), 'cPath' => $c->getCollectionPath(), 'content' => $c->getPageIndexContent(), 'cDatePublic' => $c->getCollectionDatePublic());
}
return $results;
}
} | <?
/**
*
* A wrapper class for results from the search engine, allowing for abstraction in case search engines are changed in the future.
* @package Utilities
* @subpackage Search
*/
defined('C5_EXECUTE') or die("Access Denied.");
class Concrete5_Library_IndexedPageList extends PageList {
protected $indexModeSimple = false;
public function setSimpleIndexMode($indexModeSimple) {
$this->indexModeSimple = $indexModeSimple;
}
public function getPage() {
if ($this->indexModeSimple) {
$this->sortBy('cDatePublic', 'desc');
} else {
$this->sortByMultiple('cIndexScore desc', 'cDatePublic desc');
}
$r = parent::getPage();
$results = array();
foreach($r as $c) {
$results[] = array('cID' => $c->getCollectionID(), 'cName' => $c->getCollectionName(), 'cDescription' => $c->getCollectionDescription(), 'score' => $c->getPageIndexScore(), 'cPath' => $c->getCollectionPath(), 'content' => $c->getPageIndexContent());
}
return $results;
}
} |
Add a conditional to check whther 'arg' is a byte | # IdeaScaly
# Copyright 2015 Jorge Saldivar
# See LICENSE for details.
import six
import dateutil.parser
def parse_datetime(str_date):
try:
date_is = dateutil.parser.parse(str_date)
return date_is
except:
return None
def parse_html_value(html):
return html[html.find('>')+1:html.rfind('<')]
def parse_a_href(atag):
start = atag.find('"') + 1
end = atag.find('"', start)
return atag[start:end]
def convert_to_utf8_str(arg):
# written by Michael Norton (http://docondev.blogspot.com/)
if isinstance(arg, bytes):
arg = arg.decode('ascii')
if isinstance(arg, six.text_type):
arg = arg.encode('utf-8')
elif not isinstance(arg, bytes):
arg = six.text_type(arg).encode('utf-8')
return arg
def import_simplejson():
try:
import simplejson as json
except ImportError:
try:
import json # Python 2.6+
except ImportError:
raise ImportError("Can't load a json library")
return json | # IdeaScaly
# Copyright 2015 Jorge Saldivar
# See LICENSE for details.
import six
import dateutil.parser
def parse_datetime(str_date):
try:
date_is = dateutil.parser.parse(str_date)
return date_is
except:
return None
def parse_html_value(html):
return html[html.find('>')+1:html.rfind('<')]
def parse_a_href(atag):
start = atag.find('"') + 1
end = atag.find('"', start)
return atag[start:end]
def convert_to_utf8_str(arg):
# written by Michael Norton (http://docondev.blogspot.com/)
if isinstance(arg, six.text_type):
arg = arg.encode('utf-8')
elif not isinstance(arg, bytes):
arg = six.text_type(arg).encode('utf-8')
return arg
def import_simplejson():
try:
import simplejson as json
except ImportError:
try:
import json # Python 2.6+
except ImportError:
raise ImportError("Can't load a json library")
return json |
Update the importer to use the places service | from datetime import timedelta
import httplib
from tempfile import TemporaryFile
from zipfile import ZipFile
from celery.schedules import schedule
from molly.apps.places.parsers.naptan import NaptanParser
class NaptanImporter(object):
IMPORTER_NAME = 'naptan'
IMPORT_SCHEDULE = schedule(run_every=timedelta(weeks=1))
HTTP_HOST = "www.dft.gov.uk"
REMOTE_PATH = "/NaPTAN/snapshot/NaPTANxml.zip"
def __init__(self, config):
self._http_connection = httplib.HTTPConnection(self.HTTP_HOST)
self._url = "http://%s%s" % (self.HTTP_HOST, self.REMOTE_PATH)
def _get_file_from_url(self):
temporary = TemporaryFile()
self._http_connection.request('GET', self._url)
temporary.write(self._http_connection.getresponse().read())
return ZipFile(temporary).open('NaPTAN.xml')
def load(self):
parser = NaptanParser()
for stop in parser.import_from_file(self._get_file_from_url(), self._url):
self.poi_service.add_or_update(stop)
Provider = NaptanImporter
| from datetime import timedelta
import httplib
from tempfile import TemporaryFile
from zipfile import ZipFile
from celery.schedules import schedule
from molly.apps.places.parsers.naptan import NaptanParser
class NaptanImporter(object):
IMPORTER_NAME = 'naptan'
IMPORT_SCHEDULE = schedule(run_every=timedelta(weeks=1))
HTTP_HOST = "www.dft.gov.uk"
REMOTE_PATH = "/NaPTAN/snapshot/NaPTANxml.zip"
def __init__(self, config):
self._http_connection = httplib.HTTPConnection(self.HTTP_HOST)
self._url = "http://%s%s" % (self.HTTP_HOST, self.REMOTE_PATH)
def _get_file_from_url(self):
temporary = TemporaryFile()
self._http_connection.request('GET', self._url)
temporary.write(self._http_connection.getresponse().read())
return ZipFile(temporary).open('NaPTAN.xml')
def load(self):
parser = NaptanParser()
for stop in parser.import_from_file(self._get_file_from_url(), self._url):
self.stop_service.insert_and_merge(stop)
Provider = NaptanImporter
|
Use node-style callbacks in through2 | 'use strict';
var defaults = require('defaults'),
through = require('through2'),
getLicenseTemplate = require('./lib/licenseTemplateStore').get,
prefixStream = require('./lib/prefixStream');
module.exports = function(type, options) {
var opts = defaults(options, {
year: new Date().getFullYear(),
license: type
});
var licenseKey = options.tiny ? 'tiny' : type.toLowerCase();
function license(file, encoding, callback) {
if (file.isNull()) {
return callback(null, file);
}
getLicenseTemplate(licenseKey, function(err, template) {
if (err) {
return callback(err);
}
if (file.isBuffer()) {
file.contents = new Buffer(template(opts) + file.contents);
}
if (file.isStream()) {
file.contents = file.contents.pipe(prefixStream(template(opts)));
}
return callback(null, file);
});
}
return through.obj(license);
};
| 'use strict';
var defaults = require('defaults'),
through = require('through2'),
getLicenseTemplate = require('./lib/licenseTemplateStore').get,
prefixStream = require('./lib/prefixStream');
module.exports = function(type, options) {
var opts = defaults(options, {
year: new Date().getFullYear(),
license: type
});
var licenseKey = options.tiny ? 'tiny' : type.toLowerCase();
function license(file, encoding, callback) {
/*jshint validthis:true */
if (file.isNull()) {
this.push(file);
return callback();
}
getLicenseTemplate(licenseKey, function(err, template) {
if (err) {
return callback(err);
}
if (file.isBuffer()) {
file.contents = new Buffer(template(opts) + file.contents);
}
if (file.isStream()) {
file.contents = file.contents.pipe(prefixStream(template(opts)));
}
this.push(file);
return callback();
}.bind(this));
}
return through.obj(license);
};
|
Fix requirejs for other locations than apps/ | /* global requirejs */
/**
* Mail
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @copyright Christoph Wurst 2015, 2016
*/
(function() {
'use strict';
requirejs.config({
baseUrl: './../../../apps/mail/js',
paths: {
/**
* Libraries
*/
backbone: 'vendor/backbone/backbone',
'backbone.radio': 'vendor/backbone.radio/build/backbone.radio',
davclient: 'vendor/davclient.js/lib/client',
domready: 'vendor/domReady/domReady',
'es6-promise': 'vendor/es6-promise/es6-promise.min',
handlebars: 'vendor/handlebars/handlebars',
ical: 'vendor/ical.js/build/ical.min',
marionette: 'vendor/backbone.marionette/lib/backbone.marionette',
underscore: 'vendor/underscore/underscore',
text: 'vendor/text/text'
},
shim: {
davclient: {
exports: 'dav'
},
ical: {
exports: 'ICAL'
}
}
});
// avoid optimization errors
requirejs.config({
baseUrl: OC.linkTo('mail', 'js')
});
require([
'app',
'notification'
]);
})();
| /* global requirejs */
/**
* Mail
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @copyright Christoph Wurst 2015, 2016
*/
(function() {
'use strict';
requirejs.config({
baseUrl: './../../../apps/mail/js',
paths: {
/**
* Libraries
*/
backbone: 'vendor/backbone/backbone',
'backbone.radio': 'vendor/backbone.radio/build/backbone.radio',
davclient: 'vendor/davclient.js/lib/client',
domready: 'vendor/domReady/domReady',
'es6-promise': 'vendor/es6-promise/es6-promise.min',
handlebars: 'vendor/handlebars/handlebars',
ical: 'vendor/ical.js/build/ical.min',
marionette: 'vendor/backbone.marionette/lib/backbone.marionette',
underscore: 'vendor/underscore/underscore',
text: 'vendor/text/text'
},
shim: {
davclient: {
exports: 'dav'
},
ical: {
exports: 'ICAL'
}
}
});
require([
'app',
'notification'
]);
})();
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.