text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
FIX: Set up RunEngine with required metadata.
|
from bluesky.examples import *
from bluesky.tests.utils import setup_test_run_engine
from matplotlib import pyplot as plt
from xray_vision.backend.mpl.cross_section_2d import CrossSection
import numpy as np
import filestore.api as fsapi
import time as ttime
from filestore.handlers import NpyHandler
fsapi.register_handler('npy', NpyHandler)
def stepscan(motor, det):
for i in np.linspace(-5, 5, 75):
yield Msg('create')
yield Msg('set', motor, i)
yield Msg('trigger', det)
yield Msg('read', motor)
yield Msg('read', det)
yield Msg('save')
ic = LiveImage('det_2d')
table_callback = LiveTable(fields=[motor._name, det_2d._name])
RE = setup_test_run_engine()
RE(stepscan(motor, det_2d), subs={'event': ic, 'all': table_callback}, beamline_id='c08i')
|
from bluesky.examples import *
from bluesky.standard_config import RE
from matplotlib import pyplot as plt
from xray_vision.backend.mpl.cross_section_2d import CrossSection
import numpy as np
import filestore.api as fsapi
import time as ttime
from filestore.handlers import NpyHandler
fsapi.register_handler('npy', NpyHandler)
def stepscan(motor, det):
for i in np.linspace(-5, 5, 75):
yield Msg('create')
yield Msg('set', motor, i)
yield Msg('trigger', det)
yield Msg('read', motor)
yield Msg('read', det)
yield Msg('save')
ic = LiveImage('det_2d')
table_callback = LiveTable(fields=[motor._name, det_2d._name])
RE(stepscan(motor, det_2d), subs={'event': ic, 'all': table_callback}, beamline_id='c08i')
|
Stop reactotron saga monitor. Fix redux-logger.
|
import { createStore, applyMiddleware, compose } from 'redux'
import createSagaMiddleware from 'redux-saga'
import rootReducer from 'rootReducer'
import rootSaga from 'sagas'
import { extend } from 'lodash'
const middlewares = []
const sagaAdditionalMiddlewares = []
if (process.env.NODE_ENV === 'development') {
const { createLogger } = require('redux-logger')
// const sagaMonitor = console.tron.createSagaMonitor()
const logger = createLogger({
predicate: (a, b) => true,
collapsed: (a, b) => true
})
middlewares.push(logger)
// sagaAdditionalMiddlewares.push({sagaMonitor})
}
const sagaMiddleware = createSagaMiddleware(...sagaAdditionalMiddlewares)
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const createTheStore =
process.env.NODE_ENV === 'development'
? createStore
: createStore
middlewares.push(sagaMiddleware)
export default () => {
const store = createTheStore(
rootReducer,
composeEnhancers(applyMiddleware(...middlewares)),
)
sagaMiddleware.run(rootSaga)
return store
}
|
import { createStore, applyMiddleware, compose } from 'redux'
import createSagaMiddleware from 'redux-saga'
import rootReducer from 'rootReducer'
import rootSaga from 'sagas'
import { extend } from 'lodash'
const middlewares = []
const sagaAdditionalMiddlewares = []
if (process.env.NODE_ENV === 'development') {
const createLogger = require('redux-logger')
const sagaMonitor = console.tron.createSagaMonitor()
const logger = createLogger({
predicate: (a, b) => true,
collapsed: (a, b) => true
})
middlewares.push(logger)
sagaAdditionalMiddlewares.push({sagaMonitor})
}
const sagaMiddleware = createSagaMiddleware(...sagaAdditionalMiddlewares)
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const createTheStore =
process.env.NODE_ENV === 'development'
? console.tron.createStore
: createStore
middlewares.push(sagaMiddleware)
export default () => {
const store = createTheStore(
rootReducer,
composeEnhancers(applyMiddleware(...middlewares)),
)
sagaMiddleware.run(rootSaga)
return store
}
|
Fix issue with close icon not appearing
|
import React, { useCallback } from 'react';
import { useDocked } from 'openfin-react-hooks';
import { snapAndDock } from 'openfin-layouts';
import './Titlebar.css';
export default () => {
const isDocked = useDocked();
const onMinimizeClick = useCallback(async () => {
const currentWindow = await window.fin.Window.getCurrent();
currentWindow.minimize();
}, []);
const onCloseClick = useCallback(async () => {
const currentWindow = await window.fin.Window.getCurrent();
currentWindow.close();
}, []);
const onUndockClick = useCallback(async () => {
await snapAndDock.undockWindow();
}, []);
return (
<div className="titlebar-container">
<div className="icons-container">
<div className="button-icon minimize" onClick={onMinimizeClick} title="Minimize"> </div>
{isDocked && <div className="button-icon undock" onClick={onUndockClick} title="Undock"> </div>}
<div className="button-icon close" onClick={onCloseClick} title="Close"> </div>
</div>
</div>
)
}
|
import React, { useCallback } from 'react';
import { useDocked } from 'openfin-react-hooks';
import { snapAndDock } from 'openfin-layouts';
import './Titlebar.css';
export default () => {
const isDocked = useDocked();
const onMinimizeClick = useCallback(async () => {
const currentWindow = await window.fin.Window.getCurrent();
currentWindow.minimize();
}, []);
const onCloseClick = useCallback(async () => {
const currentWindow = await window.fin.Window.getCurrent();
currentWindow.close();
}, []);
const onUndockClick = useCallback(async () => {
await snapAndDock.undockWindow();
}, []);
return (
<div className="titlebar-container">
<div className="icons-container">
<div className="button-icon minimize" onClick={onMinimizeClick} title="Minimize"> </div>
{isDocked && <div className="button-icon undock" onClick={onUndockClick} title="Undock"> </div>}
<div className="button-icon close-icon" onClick={onCloseClick} title="Close"> </div>
</div>
</div>
)
}
|
Fix unit test messing up the transaction on Oracle
Since the unit test is skipped anyway for Oracle, the dropTable() call
should be skipped as well to avoid having a leftover transaction and
cause further transactions to be nested and break the next test suites
requiring transactions.
|
<?php
/**
* Copyright (c) 2014 Thomas Müller <deepdiver@owncloud.com>
* This file is licensed under the Affero General Public License version 3 or
* later.
* See the COPYING-README file.
*/
namespace Test\DB;
class MDB2SchemaManager extends \PHPUnit_Framework_TestCase {
public function tearDown() {
// do not drop the table for Oracle as it will create a bogus transaction
// that will break the following test suites requiring transactions
if (\OC::$server->getConfig()->getSystemValue('dbtype', 'sqlite') === 'oci') {
return;
}
\OC_DB::dropTable('table');
}
public function testAutoIncrement() {
if (\OC::$server->getConfig()->getSystemValue('dbtype', 'sqlite') === 'oci') {
$this->markTestSkipped('Adding auto increment columns in Oracle is not supported.');
}
$connection = \OC_DB::getConnection();
$manager = new \OC\DB\MDB2SchemaManager($connection);
$manager->createDbFromStructure(__DIR__ . '/ts-autoincrement-before.xml');
$connection->executeUpdate('insert into `*PREFIX*table` values (?)', array('abc'));
$connection->executeUpdate('insert into `*PREFIX*table` values (?)', array('abc'));
$connection->executeUpdate('insert into `*PREFIX*table` values (?)', array('123'));
$connection->executeUpdate('insert into `*PREFIX*table` values (?)', array('123'));
$manager->updateDbFromStructure(__DIR__ . '/ts-autoincrement-after.xml');
$this->assertTrue(true);
}
}
|
<?php
/**
* Copyright (c) 2014 Thomas Müller <deepdiver@owncloud.com>
* This file is licensed under the Affero General Public License version 3 or
* later.
* See the COPYING-README file.
*/
namespace Test\DB;
class MDB2SchemaManager extends \PHPUnit_Framework_TestCase {
public function tearDown() {
\OC_DB::dropTable('table');
}
public function testAutoIncrement() {
if (\OC::$server->getConfig()->getSystemValue('dbtype', 'sqlite') === 'oci') {
$this->markTestSkipped('Adding auto increment columns in Oracle is not supported.');
}
$connection = \OC_DB::getConnection();
$manager = new \OC\DB\MDB2SchemaManager($connection);
$manager->createDbFromStructure(__DIR__ . '/ts-autoincrement-before.xml');
$connection->executeUpdate('insert into `*PREFIX*table` values (?)', array('abc'));
$connection->executeUpdate('insert into `*PREFIX*table` values (?)', array('abc'));
$connection->executeUpdate('insert into `*PREFIX*table` values (?)', array('123'));
$connection->executeUpdate('insert into `*PREFIX*table` values (?)', array('123'));
$manager->updateDbFromStructure(__DIR__ . '/ts-autoincrement-after.xml');
$this->assertTrue(true);
}
}
|
Use DrawableCompat to tint drawables
|
package io.github.hidroh.materialistic;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.view.Menu;
/**
* Helper to tint menu items for activities and fragments
*/
public class MenuTintDelegate {
private int mTextColorPrimary;
/**
* Callback that should be triggered after activity has been created
* @param context activity context
*/
public void onActivityCreated(Context context) {
mTextColorPrimary = ContextCompat.getColor(context,
AppUtils.getThemedResId(context, android.R.attr.textColorPrimary));
}
/**
* Callback that should be triggered after menu has been inflated
* @param menu inflated menu
*/
public void onOptionsMenuCreated(Menu menu) {
for (int i = 0; i < menu.size(); i++) {
Drawable drawable = menu.getItem(i).getIcon();
if (drawable == null) {
continue;
}
drawable = DrawableCompat.wrap(drawable);
DrawableCompat.setTint(drawable, mTextColorPrimary);
}
}
}
|
package io.github.hidroh.materialistic;
import android.content.Context;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.view.Menu;
/**
* Helper to tint menu items for activities and fragments
*/
public class MenuTintDelegate {
private int mTextColorPrimary;
/**
* Callback that should be triggered after activity has been created
* @param context activity context
*/
public void onActivityCreated(Context context) {
mTextColorPrimary = ContextCompat.getColor(context,
AppUtils.getThemedResId(context, android.R.attr.textColorPrimary));
}
/**
* Callback that should be triggered after menu has been inflated
* @param menu inflated menu
*/
public void onOptionsMenuCreated(Menu menu) {
for (int i = 0; i < menu.size(); i++) {
Drawable drawable = menu.getItem(i).getIcon();
if (drawable == null) {
continue;
}
drawable.mutate().setColorFilter(mTextColorPrimary, PorterDuff.Mode.SRC_IN);
}
}
}
|
Use `->prepare()` instead of `->prepareStatement() in LastActivityCronjob
|
<?php
namespace wcf\system\cronjob;
use wcf\data\cronjob\Cronjob;
use wcf\system\WCF;
/**
* Updates the last activity timestamp in the user table.
*
* @author Marcel Werk
* @copyright 2001-2021 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core\System\Cronjob
*/
class LastActivityCronjob extends AbstractCronjob
{
/**
* @inheritDoc
*/
public function execute(Cronjob $cronjob)
{
parent::execute($cronjob);
$sql = "UPDATE wcf1_user user_table,
wcf1_session session
SET user_table.lastActivityTime = session.lastActivityTime
WHERE user_table.userID = session.userID
AND session.userID IS NOT NULL";
$statement = WCF::getDB()->prepare($sql);
$statement->execute();
}
}
|
<?php
namespace wcf\system\cronjob;
use wcf\data\cronjob\Cronjob;
use wcf\system\WCF;
/**
* Updates the last activity timestamp in the user table.
*
* @author Marcel Werk
* @copyright 2001-2021 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core\System\Cronjob
*/
class LastActivityCronjob extends AbstractCronjob
{
/**
* @inheritDoc
*/
public function execute(Cronjob $cronjob)
{
parent::execute($cronjob);
$sql = "UPDATE wcf" . WCF_N . "_user user_table,
wcf" . WCF_N . "_session session
SET user_table.lastActivityTime = session.lastActivityTime
WHERE user_table.userID = session.userID
AND session.userID IS NOT NULL";
$statement = WCF::getDB()->prepareStatement($sql);
$statement->execute();
}
}
|
Handle empty values for shape commands
|
export default function parse(input) {
let c = '';
let i = 0;
let temp = '';
let result = {};
let key = '';
let value = '';
while ((c = input[i++]) !== undefined) {
if (c == ':') {
key = temp;
temp = '';
continue;
}
if (c == ';') {
value = temp;
temp = '';
if (key.length && value.length) {
result[key] = value;
}
key = value = '';
continue;
}
if (/\S/.test(c)) {
temp += c;
}
}
if (key.length && temp.length) {
result[key] = temp;
}
return result;
}
|
export default function parse(input) {
let c = '';
let i = 0;
let temp = '';
let result = {};
let key = '';
let value = '';
while ((c = input[i++]) !== undefined) {
if (c == ':') {
key = temp;
temp = '';
continue;
}
if (c == ';') {
value = temp;
temp = '';
if (key.length && value.length) {
result[key] = value;
key = value = '';
continue;
}
}
if (/\S/.test(c)) {
temp += c;
}
}
if (key.length && temp.length) {
result[key] = temp;
}
return result;
}
|
Allow serving from absolute paths.
|
#!/usr/bin/env node
'use strict'
require('./splash')()
const path = require('path')
const flags = require('commander')
const markserv = require(path.join(__dirname, 'server'))
const pkg = require(path.join('..', 'package.json'))
const cwd = process.cwd()
flags.dir = cwd
flags.version(pkg.version)
.usage('<file/dir>')
.option('-p, --port [type]', 'HTTP port [port]', 8642)
.option('-l, --livereloadport [type]', 'LiveReload port [livereloadport]', 35729)
.option('-i, --silent [type]', 'Silent (no logs to CLI)', false)
.option('-a, --address [type]', 'Serve on ip/address [address]', 'localhost')
.option('-v, --verbose', 'verbose output')
.action(serverPath => {
flags.$pathProvided = true
if (flags.dir[0] === '/') {
flags.dir = serverPath
} else {
flags.dir = path.normalize(path.join(cwd, serverPath))
}
}).parse(process.argv)
markserv.init(flags)
|
#!/usr/bin/env node
'use strict'
require('./splash')()
const path = require('path')
const flags = require('commander')
const markserv = require(path.join(__dirname, 'server'))
const pkg = require(path.join('..', 'package.json'))
const cwd = process.cwd()
flags.dir = cwd
flags.version(pkg.version)
.usage('<file/dir>')
.option('-p, --port [type]', 'HTTP port [port]', 8642)
.option('-l, --livereloadport [type]', 'LiveReload port [livereloadport]', 35729)
.option('-i, --silent [type]', 'Silent (no logs to CLI)', false)
.option('-a, --address [type]', 'Serve on ip/address [address]', 'localhost')
.option('-v, --verbose', 'verbose output')
.action(serverPath => {
flags.$pathProvided = true
if (flags.dir[0] !== '/') {
flags.dir = path.normalize(path.join(cwd, serverPath))
}
}).parse(process.argv)
markserv.init(flags)
|
Edit handler fix is backwards incompatible with Wagtail <= 0.8
|
#!/usr/bin/env python
"""
Install wagtailnews using setuptools
"""
from wagtailnews import __version__
with open('README.rst', 'r') as f:
readme = f.read()
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name='wagtailnews',
version=__version__,
description='News / blog plugin for the Wagtail CMS',
long_description=readme,
author='Tim Heap',
author_email='tim@takeflight.com.au',
url='https://bitbucket.org/takeflight/wagtailnews',
install_requires=['wagtail>=0.9'],
zip_safe=False,
license='BSD License',
packages=find_packages(),
include_package_data=True,
package_data={},
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
'License :: OSI Approved :: BSD License',
],
)
|
#!/usr/bin/env python
"""
Install wagtailnews using setuptools
"""
from wagtailnews import __version__
with open('README.rst', 'r') as f:
readme = f.read()
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name='wagtailnews',
version=__version__,
description='News / blog plugin for the Wagtail CMS',
long_description=readme,
author='Tim Heap',
author_email='tim@takeflight.com.au',
url='https://bitbucket.org/takeflight/wagtailnews',
install_requires=['wagtail>=0.7'],
zip_safe=False,
license='BSD License',
packages=find_packages(),
include_package_data=True,
package_data={ },
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
'License :: OSI Approved :: BSD License',
],
)
|
Remove vim header from source files
trivialfix
Change-Id: I6ccd551bc5cec8f5a682502b0a6e99a6d02cad3b
|
# Copyright 2013 Hewlett-Packard Development Company, L.P.
# 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.
import fixtures
from mox3 import mox
from mox3 import stubout
class MoxStubout(fixtures.Fixture):
"""Deal with code around mox and stubout as a fixture."""
def setUp(self):
super(MoxStubout, self).setUp()
self.mox = mox.Mox()
self.stubs = stubout.StubOutForTesting()
self.addCleanup(self.mox.UnsetStubs)
self.addCleanup(self.stubs.UnsetAll)
self.addCleanup(self.stubs.SmartUnsetAll)
self.addCleanup(self.mox.VerifyAll)
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 Hewlett-Packard Development Company, L.P.
# 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.
import fixtures
from mox3 import mox
from mox3 import stubout
class MoxStubout(fixtures.Fixture):
"""Deal with code around mox and stubout as a fixture."""
def setUp(self):
super(MoxStubout, self).setUp()
self.mox = mox.Mox()
self.stubs = stubout.StubOutForTesting()
self.addCleanup(self.mox.UnsetStubs)
self.addCleanup(self.stubs.UnsetAll)
self.addCleanup(self.stubs.SmartUnsetAll)
self.addCleanup(self.mox.VerifyAll)
|
Add check for trigger before running zig zag animation
|
import gsap from 'gsap';
import ScrollTrigger from 'gsap/ScrollTrigger';
gsap.registerPlugin(ScrollTrigger);
function zigZag (trigger) {
gsap.timeline({
scrollTrigger: {
trigger,
start: 'top 75%',
end: 'bottom 50%',
toggleActions: 'play none none reverse'
}
})
.to('.js-zag', { y: 0, x: 0, stagger: 0.2, duration: 0.2, delay: 0.5, ease: 'sine.inOut' })
.add('end')
.to('.js-zig-end', { width: '100%', duration: 0.3, ease: 'sine.Out' }, 'end')
.to('.js-zig-label-1', { x: 0, opacity: 1, duration: 0.2, delay: 0.1, ease: 'sine.Out' }, 'end')
.to('.js-zig-label-2', { x: 0, opacity: 1, duration: 0.2, delay: 0.2, ease: 'sine.Out' }, 'end')
.to('.js-work-item', { y: 0, opacity: 1, duration: 0.25, stagger: 0.15, ease: 'sine.inOut' });
}
export default function () {
const trigger = document.querySelector('#js-zig-zag');
if (trigger) {
zigZag(trigger);
}
}
|
import gsap from 'gsap';
import ScrollTrigger from 'gsap/ScrollTrigger';
gsap.registerPlugin(ScrollTrigger);
function zigZag () {
gsap.timeline({
scrollTrigger: {
trigger: '.zig-zag',
start: 'top 75%',
end: 'bottom 50%',
toggleActions: 'play none none reverse'
}
})
.to('.js-zag', { y: 0, x: 0, stagger: 0.2, duration: 0.2, delay: 0.5, ease: 'sine.inOut' })
.add('end')
.to('.js-zig-end', { width: '100%', duration: 0.3, ease: 'sine.Out' }, 'end')
.to('.js-zig-label-1', { x: 0, opacity: 1, duration: 0.2, delay: 0.1, ease: 'sine.Out' }, 'end')
.to('.js-zig-label-2', { x: 0, opacity: 1, duration: 0.2, delay: 0.2, ease: 'sine.Out' }, 'end')
.to('.js-work-item', { y: 0, opacity: 1, duration: 0.25, stagger: 0.15, ease: 'sine.inOut' });
}
export default function () {
zigZag();
}
|
Update the proxy list examples
|
"""
Proxy Server "Phone Book".
Simplify running browser tests through a proxy server
by adding your frequently-used proxies here.
Now you can do something like this on the command line:
"pytest SOME_TEST.py --proxy=proxy1"
Format of PROXY_LIST server entries:
* "ip_address:port" OR "username:password@ip_address:port"
* "server:port" OR "username:password@server:port"
(Do NOT include the http:// or https:// in your proxy string!)
Example proxies in PROXY_LIST below are not guaranteed to be active or secure.
If you don't already have a proxy server to connect to,
you can try finding one from one of following sites:
* https://www.us-proxy.org/
* https://hidemy.name/en/proxy-list/
"""
PROXY_LIST = {
"example1": "45.133.182.18:18080", # (Example) - set your own proxy here
"example2": "95.174.67.50:18080", # (Example) - set your own proxy here
"example3": "83.97.23.90:18080", # (Example) - set your own proxy here
"example4": "82.200.233.4:3128", # (Example) - set your own proxy here
"proxy1": None,
"proxy2": None,
"proxy3": None,
"proxy4": None,
"proxy5": None,
}
|
"""
Proxy Server "Phone Book".
Simplify running browser tests through a proxy server
by adding your frequently-used proxies here.
Now you can do something like this on the command line:
"pytest SOME_TEST.py --proxy=proxy1"
Format of PROXY_LIST server entries:
* "ip_address:port" OR "username:password@ip_address:port"
* "server:port" OR "username:password@server:port"
(Do NOT include the http:// or https:// in your proxy string!)
Example proxies in PROXY_LIST below are not guaranteed to be active or secure.
If you don't already have a proxy server to connect to,
you can try finding one from one of following sites:
* https://www.us-proxy.org/
* https://hidemy.name/en/proxy-list/
"""
PROXY_LIST = {
"example1": "46.28.229.75:3128", # (Example) - set your own proxy here
"example2": "82.200.233.4:3128", # (Example) - set your own proxy here
"example3": "128.199.214.87:3128", # (Example) - set your own proxy here
"proxy1": None,
"proxy2": None,
"proxy3": None,
"proxy4": None,
"proxy5": None,
}
|
Make sure ~/.ipfs exists. Convert to ES6.
|
'use strict';
var fs = require('fs');
var path = require('path');
var async = require('asyncawait/async');
var await = require('asyncawait/await');
var Promise = require('bluebird');
var ipfsdCtl = require('ipfsd-ctl');
const getUserHome = () => {
return process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'];
};
const ipfsPath = path.resolve(getUserHome() + '/.ipfs');
if(!fs.existsSync(ipfsPath))
fs.mkdirSync(ipfsPath);
const startIpfs = async (() => {
let ipfs, nodeInfo;
try {
const ipfsNode = Promise.promisify(ipfsdCtl.local.bind(ipfsPath))
const ipfsd = await (ipfsNode());
const start = Promise.promisify(ipfsd.startDaemon.bind(ipfsd));
ipfs = await (start());
const getId = Promise.promisify(ipfs.id);
nodeInfo = await (getId())
} catch(e) {
console.log("Error initializing ipfs daemon:", e);
return null;
}
return { daemon: ipfs, nodeInfo: nodeInfo };
});
module.exports = async(() => {
return await(startIpfs());
});
|
'use strict';
var path = require('path');
var async = require('asyncawait/async');
var await = require('asyncawait/await');
var Promise = require('bluebird');
var ipfsdCtl = require('ipfsd-ctl');
let getUserHome = () => {
return process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'];
};
let ipfsPath = path.resolve(getUserHome() + '/.ipfs');
var startIpfs = async (() => {
let ipfs, nodeInfo;
try {
var ipfsNode = Promise.promisify(ipfsdCtl.local.bind(ipfsPath))
var ipfsd = await (ipfsNode());
var start = Promise.promisify(ipfsd.startDaemon.bind(ipfsd));
ipfs = await (start());
var getId = Promise.promisify(ipfs.id);
nodeInfo = await (getId())
} catch(e) {
console.log("Error initializing ipfs daemon:", e);
return null;
}
return { daemon: ipfs, nodeInfo: nodeInfo };
});
module.exports = async(() => {
return await(startIpfs());
});
|
Simplify regex in url matching
|
from django.conf.urls import url
from modelview import views
from oeplatform import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^(?P<sheettype>[\w\d_]+)s/$', views.listsheets, {}, name='modellist'),
url(r'^overview/$', views.overview, {}),
url(r'^(?P<sheettype>[\w\d_]+)s/add/$', views.FSAdd.as_view(), {'method':'add'}, name='modellist'),
url(r'^(?P<sheettype>[\w\d_]+)s/download/$', views.model_to_csv, {}, name='index'),
url(r'^(?P<sheettype>[\w\d_]+)s/(?P<model_name>[\d]+)/$', views.show, {}, name='index'),
url(r'^(?P<sheettype>[\w\d_]+)s/(?P<model_name>[\d]+)/edit/$', views.editModel, {}, name='index'),
url(r'^(?P<sheettype>[\w\d_]+)s/(?P<pk>[\d]+)/update/$', views.FSAdd.as_view(), {'method':'update'}, name='index'),
]
|
from django.conf.urls import url
from modelview import views
from oeplatform import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^(?P<sheettype>[\w\d_]+)s/$', views.listsheets, {}, name='modellist'),
url(r'^overview/$', views.overview, {}),
url(r'^(?P<sheettype>[\w\d_]+)s/add/$', views.FSAdd.as_view(), {'method':'add'}, name='modellist'),
url(r'^(?P<sheettype>[\w\d_]+)s/download/$', views.model_to_csv, {}, name='index'),
url(r'^(?P<sheettype>[\w\d_]+)s/(?P<model_name>[\w\d_]+)/$', views.show, {}, name='index'),
url(r'^(?P<sheettype>[\w\d_]+)s/(?P<model_name>[\w\d_]+)/edit/$', views.editModel, {}, name='index'),
url(r'^(?P<sheettype>[\w\d_]+)s/(?P<pk>[\w\d_]+)/update/$', views.FSAdd.as_view(), {'method':'update'}, name='index'),
]
|
Fix previously uncaught phpcs error
|
<?php
declare(strict_types=1);
namespace Documents;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
/**
* @ODM\Document
*/
class Developer
{
/** @ODM\Id */
private $id;
/** @ODM\Field(type="string") */
private $name;
/** @ODM\ReferenceMany(targetDocument=Project::class, cascade="all") */
private $projects;
public function __construct($name, ?Collection $projects = null)
{
$this->name = $name;
$this->projects = $projects ?? new ArrayCollection();
}
public function getId()
{
return $this->id;
}
public function getProjects()
{
return $this->projects;
}
}
|
<?php
declare(strict_types=1);
namespace Documents;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
/**
* @ODM\Document
*/
class Developer
{
/** @ODM\Id */
private $id;
/** @ODM\Field(type="string") */
private $name;
/** @ODM\ReferenceMany(targetDocument=Project::class, cascade="all") */
private $projects;
public function __construct($name, ?Collection $projects = null)
{
$this->name = $name;
$this->projects = $projects === null ? new ArrayCollection() : $projects;
}
public function getId()
{
return $this->id;
}
public function getProjects()
{
return $this->projects;
}
}
|
Read exactly 43 bytes from watch
More and it hangs forever at present
Less and it will not read whole record
See https://github.com/docker/pinata/issues/766
Signed-off-by: Justin Cormack <af64ee19f04db9509cb02b0e470e11e5402ef9b3@docker.com>
|
package main
import (
"flag"
"io/ioutil"
"log"
"os"
"strconv"
"syscall"
)
var (
path string
pidfile string
)
func init() {
flag.StringVar(&path, "path", "/Database/branch/master/watch/com.docker.driver.amd64-linux.node/etc.node/docker.node/daemon.json.node/tree.live", "path of the file to watch")
flag.StringVar(&pidfile, "pidfile", "/run/docker.pid", "pidfile for process to signal")
}
func main() {
log.SetFlags(0)
flag.Parse()
watch, err := os.Open(path)
if err != nil {
log.Fatalln("Failed to open file", path, err)
}
// 43 bytes is the record size of the watch
buf := make([]byte, 43)
for {
_, err := watch.Read(buf)
if err != nil {
log.Fatalln("Error reading watch file", err)
}
bytes, err := ioutil.ReadFile(pidfile)
pidstring := string(bytes[:])
if err != nil {
pid, err := strconv.Atoi(pidstring)
if err != nil {
syscall.Kill(pid, syscall.SIGHUP)
}
}
}
}
|
package main
import (
"flag"
"io/ioutil"
"log"
"os"
"strconv"
"syscall"
)
var (
path string
pidfile string
)
func init() {
flag.StringVar(&path, "path", "/Database/branch/master/watch/com.docker.driver.amd64-linux.node/etc.node/docker.node/daemon.json.node/tree.live", "path of the file to watch")
flag.StringVar(&pidfile, "pidfile", "/run/docker.pid", "pidfile for process to signal")
}
func main() {
log.SetFlags(0)
flag.Parse()
watch, err := os.Open(path)
if err != nil {
log.Fatalln("Failed to open file", path, err)
}
buf := make([]byte, 512)
for {
_, err := watch.Read(buf)
if err != nil {
log.Fatalln("Error reading watch file", err)
}
bytes, err := ioutil.ReadFile(pidfile)
pidstring := string(bytes[:])
if err != nil {
pid, err := strconv.Atoi(pidstring)
if err != nil {
syscall.Kill(pid, syscall.SIGHUP)
}
}
}
}
|
Refactor reference to audio as a variable
|
// makes cat appear from the left
function appear() {
$('.cat').velocity({translateX: '-1000px'}, {duration: 1, display: 'hidden'});
$('.cat').velocity({translateX: '100px'}, {duration: 500, display: 'visible'});
}
$(function() {
// audio
var nyansong = document.getElementById('nyansong');
appear();
// controls audio playback
Mousetrap.bind('a', function() {
nyansong.play();
});
Mousetrap.bind('m', function() {
nyansong.pause();
});
Mousetrap.bind('up', function() {
nyansong.volume+=0.1;
});
Mousetrap.bind('down', function() {
nyansong.volume-=0.1;
});
// displays number of trips cat has taken
var trips = 0;
function incrementTrips() {
trips++;
$('p').velocity({
opacity: 1
},{
duration: 2000
});
$('.counter')[0].textContent = trips;
console.log(trips);
}
$('html').click(function() {
// makes cat fly away to the right then return from left
$('.cat').velocity({
// properties and values
translateX: '5000px'
}, {
// options
duration: 500,
complete: function() {
appear();
incrementTrips();
}
});
});
});
|
// makes cat appear from the left
function appear() {
$('.cat').velocity({translateX: '-1000px'}, {duration: 1, display: 'hidden'});
$('.cat').velocity({translateX: '100px'}, {duration: 500, display: 'visible'});
}
$(function() {
appear();
// controls audio playback
Mousetrap.bind('a', function() {
document.getElementById('nyansong').play();
});
Mousetrap.bind('m', function() {
document.getElementById('nyansong').pause();
});
Mousetrap.bind('up', function() {
document.getElementById('nyansong').volume+=0.1;
});
Mousetrap.bind('down', function() {
document.getElementById('nyansong').volume-=0.1;
});
// displays number of trips cat has taken
var trips = 0;
function incrementTrips() {
trips++;
$('p').velocity({
opacity: 1
},{
duration: 2000
});
$('.counter')[0].textContent = trips;
console.log(trips);
}
$('html').click(function() {
// makes cat fly away to the right then return from left
$('.cat').velocity({
// properties and values
translateX: '5000px'
}, {
// options
duration: 500,
complete: function() {
appear();
incrementTrips();
}
});
});
});
|
Change default view to VerticalDetailView to retain preexisting FObjectProperty view rendering behaviour
|
/**
* @license
* Copyright 2019 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
package: 'foam.u2.view',
name: 'FObjectPropertyView',
extends: 'foam.u2.view.ModeAltView',
documentation: 'A view for foam.core.FObjectProperty properties.',
requires: [
'foam.u2.CitationView',
'foam.u2.detail.VerticalDetailView'
],
properties: [
{
name: 'readView',
value: { class: 'foam.u2.detail.VerticalDetailView' }
},
{
name: 'writeView',
factory: function() {
return {
class: 'foam.u2.view.FObjectView',
of: this.prop.of
}
}
}
],
});
|
/**
* @license
* Copyright 2019 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
package: 'foam.u2.view',
name: 'FObjectPropertyView',
extends: 'foam.u2.view.ModeAltView',
documentation: 'A view for foam.core.FObjectProperty properties.',
requires: [
'foam.u2.CitationView',
'foam.u2.detail.VerticalDetailView'
],
properties: [
{
name: 'readView',
value: { class: 'foam.u2.CitationView' }
},
{
name: 'writeView',
factory: function() {
return {
class: 'foam.u2.view.FObjectView',
of: this.prop.of
}
}
}
],
});
|
Add check for leading zeroes.
|
#!/usr/bin/env python
""" Some tools for dealing with reversible numbers for problem 145 from Project Euler.
https://projecteuler.net/problem=145
"""
def is_odd(num):
""" Check if an integer is odd. """
if num % 2 != 0:
return True
else:
return False
def is_reversible(num):
""" Check if a number is reversible given the above definition. """
num_str = str(num)
rev_str = "".join(reversed(num_str))
if int(rev_str[0]) == 0:
return False
total = num + int(rev_str)
for digit in str(total):
if not is_odd(int(digit)):
return False
return True
if __name__ == "__main__":
# check some odd and even numbers
assert is_odd(1), "1 should be odd"
assert not is_odd(2), "2 should not be odd"
assert not is_odd(100), "100 should not be odd"
assert is_odd(10001), "10001 should be odd"
# check the example reversible numbers
assert is_reversible(36), "36 should be reversible"
assert is_reversible(63), "63 should be reversible"
assert is_reversible(409), "409 should be reversible"
assert is_reversible(904), "904 should be reversible"
assert not is_reversible(10), "10 should not be reversible. (leading zero.)"
print "all assertions passed"
|
#!/usr/bin/env python
""" Some tools for dealing with reversible numbers for problem 145 from Project Euler.
https://projecteuler.net/problem=145
"""
def is_odd(num):
""" Check if an integer is odd. """
if num % 2 != 0:
return True
else:
return False
def is_reversible(num):
""" Check if a number is reversible given the above definition. """
num_str = str(num)
rev_num = int("".join(reversed(num_str)))
total = num + rev_num
for digit in str(total):
if not is_odd(int(digit)):
return False
return True
if __name__ == "__main__":
# check some odd and even numbers
assert is_odd(1), "1 should be odd"
assert not is_odd(2), "2 should not be odd"
assert not is_odd(100), "100 should not be odd"
assert is_odd(10001), "10001 should be odd"
# check the example reversible numbers
assert is_reversible(36), "36 should be reversible"
assert is_reversible(63), "63 should be reversible"
assert is_reversible(409), "409 should be reversible"
assert is_reversible(904), "904 should be reversible"
print "all assertions passed"
|
Support Stylus blocks in Vue single-file components
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jack Brewer
# Copyright (c) 2015 Jack Brewer
#
# License: MIT
"""This module exports the Stylint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Stylint(NodeLinter):
"""Provides an interface to stylint."""
npm_name = 'stylint'
syntax = ('stylus', 'vue')
selectors = {'vue': 'source.stylus.embedded.html'}
cmd = 'stylint @ *'
executable = 'stylint'
version_requirement = '>= 1.5.0'
regex = r'''(?xi)
# Comments show example output for each line of a Stylint warning
# /path/to/file/example.styl
^.*$\s*
# 177:24 colors warning hexidecimal color should be a variable
^(?P<line>\d+):?(?P<col>\d+)?\s*((?P<warning>warning)|(?P<error>error))\s*(?P<message>.+)$\s*
'''
multiline = True
error_stream = util.STREAM_STDOUT
tempfile_suffix = 'styl'
config_file = ('--config', '.stylintrc', '~')
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jack Brewer
# Copyright (c) 2015 Jack Brewer
#
# License: MIT
"""This module exports the Stylint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Stylint(NodeLinter):
"""Provides an interface to stylint."""
npm_name = 'stylint'
syntax = 'stylus'
cmd = 'stylint @ *'
executable = 'stylint'
version_requirement = '>= 1.5.0'
regex = r'''(?xi)
# Comments show example output for each line of a Stylint warning
# /path/to/file/example.styl
^.*$\s*
# 177:24 colors warning hexidecimal color should be a variable
^(?P<line>\d+):?(?P<col>\d+)?\s*((?P<warning>warning)|(?P<error>error))\s*(?P<message>.+)$\s*
'''
multiline = True
error_stream = util.STREAM_STDOUT
tempfile_suffix = 'styl'
config_file = ('--config', '.stylintrc', '~')
|
Order by tagId in hipster paging, for robust tests
|
<?php
class Denkmal_Paging_Tag_Venue_Hipster extends Denkmal_Paging_Tag_Abstract {
/**
* @param Denkmal_Model_Venue $venue
* @param DateTime|null $createdMin
*/
public function __construct(Denkmal_Model_Venue $venue, DateTime $createdMin = null) {
if ($createdMin == null) {
$createdMin = (new DateTime())->sub(new DateInterval('PT1H'));
}
$join = 'JOIN `denkmal_model_message` m ON `m`.`id` = `denkmal_model_tag_model`.`modelId` ';
$join .= 'AND `denkmal_model_tag_model`.`modelType` = ' . Denkmal_Model_Message::getTypeStatic();
$group = '`denkmal_model_tag_model`.`tagId`';
$where = '`m`.`venue` = ' . $venue->getId();
$where .= ' AND `m`.`created` > ' . $createdMin->getTimestamp();
$order = '`m`.`created` DESC, `denkmal_model_tag_model`.tagId ASC';
$source = new CM_PagingSource_Sql('`denkmal_model_tag_model`.tagId', 'denkmal_model_tag_model', $where, $order, $join, $group);
$source->enableCache();
parent::__construct($source);
}
}
|
<?php
class Denkmal_Paging_Tag_Venue_Hipster extends Denkmal_Paging_Tag_Abstract {
/**
* @param Denkmal_Model_Venue $venue
* @param DateTime|null $createdMin
*/
public function __construct(Denkmal_Model_Venue $venue, DateTime $createdMin = null) {
if ($createdMin == null) {
$createdMin = (new DateTime())->sub(new DateInterval('PT1H'));
}
$join = 'JOIN `denkmal_model_message` m ON `m`.`id` = `denkmal_model_tag_model`.`modelId` ';
$join .= 'AND `denkmal_model_tag_model`.`modelType` = ' . Denkmal_Model_Message::getTypeStatic();
$group = '`denkmal_model_tag_model`.`tagId`';
$where = '`m`.`venue` = ' . $venue->getId();
$where .= ' AND `m`.`created` > ' . $createdMin->getTimestamp();
$source = new CM_PagingSource_Sql('`denkmal_model_tag_model`.tagId', 'denkmal_model_tag_model', $where, '`m`.`created` DESC', $join, $group);
$source->enableCache();
parent::__construct($source);
}
}
|
Add support to author field can be object or string
|
'use strict'
const glob = require('glob')
const prependFile = require('prepend-file')
const pkg = require(`${process.cwd()}/package.json`)
const getAuthorName = value => {
if (typeof value === 'string') return value.split('<')[0].trim()
if (value instanceof Object && typeof value.name === 'string') return value.name
return ''
}
function banner (options = {}) {
options.name = options.name || pkg.name || 'unknown'
options.tag = options.tag || pkg.version || '0.0.0'
options.homepage = options.homepage || pkg.homepage || `https://npm.com/${options.name}`
options.license = options.license || pkg.license
options.author = options.author || getAuthorName(pkg.author)
options.year = options.year || new Date().getFullYear()
const template = options.template || `/*!
* ${options.name.charAt(0).toUpperCase() + options.name.slice(1)} v${options.tag}
* ${options.homepage}
*
* Copyright (c) ${options.year} ${options.author}
*${options.license ? ` Licensed under the ${options.license} license\n *` : ''}/\n
`
if (!options.source) {
throw new Error(`File not found!`)
} else {
glob(options.source, (err, files) => {
if (err) throw err
files.map(file => prependFile.sync(file, template))
process.exit(0)
})
}
}
module.exports = banner
|
'use strict'
const glob = require('glob')
const prependFile = require('prepend-file')
const pkg = require(`${process.cwd()}/package.json`)
function banner (options = {}) {
options.name = options.name || pkg.name || 'unknown'
options.tag = options.tag || pkg.version || '0.0.0'
options.homepage = options.homepage || pkg.homepage || `https://npm.com/${options.name}`
options.license = options.license || pkg.license
options.author = options.author || pkg.author.split('<')[0].trim() || ''
options.year = options.year || new Date().getFullYear()
const template = options.template || `/*!
* ${options.name.charAt(0).toUpperCase() + options.name.slice(1)} v${options.tag}
* ${options.homepage}
*
* Copyright (c) ${options.year} ${options.author}
*${options.license ? ` Licensed under the ${options.license} license\n *` : ''}/\n
`
if (!options.source) {
throw new Error(`File not found!`)
} else {
glob(options.source, (err, files) => {
if (err) throw err
files.map(file => prependFile.sync(file, template))
process.exit(0)
})
}
}
module.exports = banner
|
Use an independent controller instead of link
For testability (<3 Angular)
|
'use strict';
angular.module('ddsApp').directive('droitEligiblesList', function() {
return {
restrict: 'E',
templateUrl: 'partials/droits-eligibles-list.html',
scope: {
list: '='
},
controller: 'droitEligiblesListCtrl',
};
});
angular.module('ddsApp').controller('droitEligiblesListCtrl', function($scope) {
$scope.isNumber = _.isNumber;
$scope.isString = _.isString;
$scope.round = function(droit) {
if (! droit.unit && droit.roundToNearest10 !== false) {
return Math.round(droit.montant / 10) * 10;
} else {
return Math.round(droit.montant);
}
};
});
|
'use strict';
angular.module('ddsApp').directive('droitEligiblesList', function() {
return {
restrict: 'E',
templateUrl: 'partials/droits-eligibles-list.html',
scope: {
list: '='
},
link: function(scope) {
scope.isNumber = _.isNumber;
scope.isString = _.isString;
scope.round = function(droit) {
if (! droit.unit && droit.roundToNearest10 !== false) {
return Math.round(droit.montant / 10) * 10;
} else {
return Math.round(droit.montant);
}
};
}
};
});
|
Change PHP error matching regex
On my system (OS X 10.7 w/stock PHP 5.3.8), the PHP lint frequently
misses errors due to over-specificity in the regex. This one is
catching them.
|
# -*- coding: utf-8 -*-
# php.py - sublimelint package for checking php files
import re
from base_linter import BaseLinter
CONFIG = {
'language': 'php',
'executable': 'php',
'lint_args': ('-l', '-d display_errors=On')
}
class Linter(BaseLinter):
def parse_errors(self, view, errors, lines, errorUnderlines, violationUnderlines, warningUnderlines, errorMessages, violationMessages, warningMessages):
for line in errors.splitlines():
match = re.match(r'^Parse error:\s*(?P<error>.+?)\s+in\s+.+?\s*line\s+(?P<line>\d+)', line)
if match:
error, line = match.group('error'), match.group('line')
self.add_message(int(line), lines, error, errorMessages)
|
# -*- coding: utf-8 -*-
# php.py - sublimelint package for checking php files
import re
from base_linter import BaseLinter
CONFIG = {
'language': 'php',
'executable': 'php',
'lint_args': ('-l', '-d display_errors=On')
}
class Linter(BaseLinter):
def parse_errors(self, view, errors, lines, errorUnderlines, violationUnderlines, warningUnderlines, errorMessages, violationMessages, warningMessages):
for line in errors.splitlines():
match = re.match(r'^Parse error:\s*syntax error,\s*(?P<error>.+?)\s+in\s+.+?\s*line\s+(?P<line>\d+)', line)
if match:
error, line = match.group('error'), match.group('line')
self.add_message(int(line), lines, error, errorMessages)
|
Add rule selector to console warning
|
var postcss = require('postcss');
module.exports = postcss.plugin('postcss-property-lookup', propertyLookup);
function propertyLookup() {
return function(css, result) {
css.eachRule(function(rule) {
rule.replaceValues(/@([a-z-]+)(\s?)/g, { fast: '@' }, function(orig, prop, space) {
var replacementVal;
rule.eachDecl(prop, function(decl) {
replacementVal = decl.value;
});
if (replacementVal) {
return replacementVal + space;
} else {
result.warn('Unable to find property ' + orig + ' in ' + rule.selector, { node: rule });
return '';
}
});
});
};
}
|
var postcss = require('postcss');
module.exports = postcss.plugin('postcss-property-lookup', propertyLookup);
function propertyLookup() {
return function(css, result) {
css.eachRule(function(rule) {
rule.replaceValues(/@([a-z-]+)(\s?)/g, { fast: '@' }, function(orig, prop, space) {
var replacementVal;
rule.eachDecl(prop, function(decl) {
replacementVal = decl.value;
});
if (replacementVal) {
return replacementVal + space;
} else {
result.warn('Unable to find property ' + orig, { node: rule });
return '';
}
});
});
};
}
|
Fix relocation of hash information on startup of cluster interface
|
/*jslint indent: 2, nomen: true, maxlen: 100, white: true, */
/*global window, $, Backbone, document */
(function() {
"use strict";
$.get("cluster/amIDispatcher", function(data) {
if (!data) {
var url = window.location.origin;
url += window.location.pathname;
url = url.replace("cluster", "index");
window.location.replace(url);
}
});
window.location.hash = "";
$(document).ready(function() {
window.App = new window.ClusterRouter();
Backbone.history.start();
if(window.App.clusterPlan.get("plan")) {
if(window.App.clusterPlan.isAlive()) {
window.App.showCluster();
} else {
window.App.handleClusterDown();
}
} else {
window.App.planScenario();
}
window.App.handleResize();
});
}());
|
/*jslint indent: 2, nomen: true, maxlen: 100, white: true, */
/*global window, $, Backbone, document */
(function() {
"use strict";
$.get("cluster/amIDispatcher", function(data) {
if (!data) {
var url = window.location.origin;
url += window.location.pathname;
url = url.replace("cluster", "index");
window.location.replace(url);
}
});
$(document).ready(function() {
window.App = new window.ClusterRouter();
Backbone.history.start();
window.App.navigate("", {trigger: true});
if(window.App.clusterPlan.get("plan")) {
if(window.App.clusterPlan.isAlive()) {
window.App.showCluster();
} else {
window.App.handleClusterDown();
}
} else {
window.App.planScenario();
}
window.App.handleResize();
});
}());
|
Update
ServiceProvider to singleton registration
|
<?php
namespace Edujugon\Skeleton\Providers;
use Edujugon\Skeleton\Skeleton;
use Illuminate\Support\ServiceProvider;
class SkeletonServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
$config_path = function_exists('config_path') ? config_path('skeleton.php') : 'skeleton.php';
$this->publishes([
__DIR__.'/../Config/config.php' => $config_path,
], 'config');
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->app->singleton('skeleton', function ($app) {
return new Skeleton();
});
}
}
|
<?php
namespace Edujugon\Skeleton\Providers;
use Edujugon\Skeleton\Skeleton;
use Illuminate\Support\ServiceProvider;
class SkeletonServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
$config_path = function_exists('config_path') ? config_path('skeleton.php') : 'skeleton.php';
$this->publishes([
__DIR__.'/../Config/config.php' => $config_path,
], 'config');
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->app['skeleton'] = $this->app->share(function($app)
{
return new Skeleton;
});
}
}
|
Adjust test for new functionality.
|
from django.test import TestCase
from django_tablib import ModelDataset, Field
from .models import TestModel
class DjangoTablibTestCase(TestCase):
def setUp(self):
TestModel.objects.create(field1='value')
def test_declarative_fields(self):
class TestModelDataset(ModelDataset):
field1 = Field(header='Field 1')
field2 = Field(attribute='field1')
class Meta:
model = TestModel
data = TestModelDataset()
self.assertEqual(len(data.headers), 3)
self.assertTrue('id' in data.headers)
self.assertFalse('field1' in data.headers)
self.assertTrue('field2' in data.headers)
self.assertTrue('Field 1' in data.headers)
self.assertEqual(data[0][0], data[0][1])
|
from django.test import TestCase
from django_tablib import ModelDataset, Field
from .models import TestModel
class DjangoTablibTestCase(TestCase):
def setUp(self):
TestModel.objects.create(field1='value')
def test_declarative_fields(self):
class TestModelDataset(ModelDataset):
field1 = Field(header='Field 1')
field2 = Field(attribute='field1')
class Meta:
model = TestModel
data = TestModelDataset()
self.assertEqual(len(data.headers), 2)
self.assertTrue('id' not in data.headers)
self.assertFalse('field1' in data.headers)
self.assertTrue('field2' in data.headers)
self.assertTrue('Field 1' in data.headers)
self.assertEqual(data[0][0], data[0][1])
|
Move to self over static
|
<?php
/**
* @codingStandardsIgnoreStart
*
* @author Barney Hanlon <barney@shrikeh.net>
* @copyright Barney Hanlon 2017
* @license https://opensource.org/licenses/MIT
*
* @codingStandardsIgnoreEnd
*/
namespace Shrikeh\GuzzleMiddleware\TimerLogger\Formatter\Traits;
use Exception;
/**
* Trait FormatterStartExceptionTrait.
*/
trait FormatterExceptionTrait
{
/**
* @param \Exception|null $e An optional previous Exception
*
* @return static
*/
public static function msg(
Exception $e = null
) {
return new static(
self::MSG_MESSAGE,
self::MSG_CODE,
$e
);
}
/**
* @param \Exception|null $e An optional previous Exception
*
* @return static
*/
public static function level(
Exception $e = null
) {
return new static(
self::LEVEL_MESSAGE,
self::LEVEL_CODE,
$e
);
}
}
|
<?php
/**
* @codingStandardsIgnoreStart
*
* @author Barney Hanlon <barney@shrikeh.net>
* @copyright Barney Hanlon 2017
* @license https://opensource.org/licenses/MIT
*
* @codingStandardsIgnoreEnd
*/
namespace Shrikeh\GuzzleMiddleware\TimerLogger\Formatter\Traits;
use Exception;
/**
* Trait FormatterStartExceptionTrait.
*/
trait FormatterExceptionTrait
{
/**
* @param \Exception|null $e An optional previous Exception
*
* @return static
*/
public static function msg(
Exception $e = null
) {
return new static(
static::MSG_MESSAGE,
static::MSG_CODE,
$e
);
}
/**
* @param \Exception|null $e An optional previous Exception
*
* @return static
*/
public static function level(
Exception $e = null
) {
return new static(
static::LEVEL_MESSAGE,
static::LEVEL_CODE,
$e
);
}
}
|
Fix runtime exception in tuple execution
|
package aya.entities;
import java.util.ArrayList;
import java.util.EmptyStackException;
import aya.exceptions.AyaRuntimeException;
import aya.obj.Obj;
import aya.obj.block.Block;
public class Tuple {
Block[] elements;
/**
* Tuples will not need to be resized during runtime
* @param blocks
*/
public Tuple(Block[] blocks) {
elements = blocks;
}
/**
* evals each of the blocks and returns an array containing each
* of the results
* @return
*/
public ArrayList<Obj> evalToResults() {
ArrayList<Obj> out = new ArrayList<Obj>(elements.length);
for (int i = 0; i < elements.length; i++) {
Block b = elements[i].duplicate();
try {
b.eval();
} catch (EmptyStackException e) {
throw new AyaRuntimeException("Empty Stack in tuple");
}
out.add(b.pop());
}
return out;
}
public String toString() {
String s = "(";
for(int i = 0; i < elements.length; i++) {
if(i!=0) {
s += ", ";
}
s += elements[i].toString(false);
}
return s + ")";
}
}
|
package aya.entities;
import java.util.ArrayList;
import java.util.EmptyStackException;
import aya.obj.Obj;
import aya.obj.block.Block;
public class Tuple {
Block[] elements;
/**
* Tuples will not need to be resized during runtime
* @param blocks
*/
public Tuple(Block[] blocks) {
elements = blocks;
}
/**
* evals each of the blocks and returns an array containing each
* of the results
* @return
*/
public ArrayList<Obj> evalToResults() {
ArrayList<Obj> out = new ArrayList<Obj>(elements.length);
for (int i = 0; i < elements.length; i++) {
Block b = elements[i].duplicate();
try {
b.eval();
} catch (EmptyStackException e) {
throw new RuntimeException("Empty Stack in tuple");
}
out.add(b.pop());
}
return out;
}
public String toString() {
String s = "(";
for(int i = 0; i < elements.length; i++) {
if(i!=0) {
s += ", ";
}
s += elements[i].toString(false);
}
return s + ")";
}
}
|
Fix gulp clean task to not read files before sending them before deletion.
|
'use strict';
var gulp = require('gulp');
var config = require('./_config.js');
var paths = config.paths;
var $ = config.plugins;
var istanbul = require('browserify-istanbul');
gulp.task('clean', function () {
return gulp.src(paths.tmp, { read: false })
.pipe($.rimraf());
});
gulp.task('build', ['index.html', 'js', 'css']);
gulp.task('index.html', function () {
return gulp.src(paths.app + '/index.jade')
.pipe($.jade({
pretty: true
}))
.pipe(gulp.dest(paths.tmp));
});
gulp.task('jade', function () {
return gulp.src(paths.app + '/*.html')
.pipe(gulp.dest(paths.tmp));
});
gulp.task('js', function () {
return gulp.src(paths.app + '/js/main.js', { read: false })
.pipe($.browserify({
transform: [istanbul],
debug: true
}))
.pipe(gulp.dest(paths.tmp + '/js'));
});
gulp.task('css', function () {
// FIXME
return gulp.src('mama');
});
|
'use strict';
var gulp = require('gulp');
var config = require('./_config.js');
var paths = config.paths;
var $ = config.plugins;
var istanbul = require('browserify-istanbul');
gulp.task('clean', function () {
return gulp.src(paths.tmp, {read: true})
.pipe($.rimraf());
});
gulp.task('build', ['index.html', 'js', 'css']);
gulp.task('index.html', function () {
return gulp.src(paths.app + '/index.jade')
.pipe($.jade({
pretty: true
}))
.pipe(gulp.dest(paths.tmp));
});
gulp.task('jade', function () {
return gulp.src(paths.app + '/*.html')
.pipe(gulp.dest(paths.tmp));
});
gulp.task('js', function () {
return gulp.src(paths.app + '/js/main.js', { read: false })
.pipe($.browserify({
transform: [istanbul],
debug: true
}))
.pipe(gulp.dest(paths.tmp + '/js'));
});
gulp.task('css', function () {
// FIXME
return gulp.src('mama');
});
|
Remove the DOM at the right time
|
const assign = require('object-assign');
const find = require('array-find');
const drop = require('this-drop');
export default (tape) => {
const tapeCss = (...args) => {
// Determine arguments – based on
// https://github.com/substack/tape/blob/aadcf4a9/lib/test.js .
const name = find(args, (arg) => typeof arg === 'string');
const options = find(args, (arg) => typeof arg === 'object') || {};
const callback = find(args, (arg) => typeof arg === 'function');
const {dom} = options;
const document = (
options.document ||
(typeof window !== 'undefined' && window.document) ||
null
);
// TODO: Throw if there’s no `document`;
const wrappedCallback = (is) => {
if (dom) {
document.body.appendChild(dom);
is.on('end', () => document.body.removeChild(dom));
}
callback(is);
};
tape(
name,
options::drop(['dom']),
wrappedCallback
);
};
assign(tapeCss, tape);
return tapeCss;
};
|
const assign = require('object-assign');
const find = require('array-find');
const drop = require('this-drop');
export default (tape) => {
const tapeCss = (...args) => {
// Determine arguments – based on
// https://github.com/substack/tape/blob/aadcf4a9/lib/test.js .
const name = find(args, (arg) => typeof arg === 'string');
const options = find(args, (arg) => typeof arg === 'object') || {};
const callback = find(args, (arg) => typeof arg === 'function');
const {dom} = options;
const document = (
options.document ||
(typeof window !== 'undefined' && window.document) ||
null
);
// TODO: Throw if there’s no `document`;
const wrappedCallback = (is) => {
if (dom) document.body.appendChild(dom);
callback(is);
if (dom) document.body.removeChild(dom);
};
tape(
name,
options::drop(['dom']),
wrappedCallback
);
};
assign(tapeCss, tape);
return tapeCss;
};
|
Sort by order of descending length for phrase mapping; the mapping is first copied to avoid changing the order of the original array
|
(function PhraseMappingServiceModule() {
"use strict";
angular.module('translate.app')
.factory('phraseMappingService', PhraseMappingService);
PhraseMappingService.$inject = ['configService'];
function PhraseMappingService(configService) {
return {
mapPhrase: function (phrase) {
return configService.get('profile')
.then(function (profile) {
if (profile && Array.isArray(profile.translations)) {
var copy = _.clone(profile.translations);
copy.sort(function (a, b) { return b.length - a.length; });
return copy.reduce(function (prev, cur) {
var needle = new RegExp(escapeRegExp(cur.key), 'g');
return prev.replace(needle, cur.value);
}, phrase);
}
return phrase;
});
}
};
}
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
})();
|
(function PhraseMappingServiceModule() {
"use strict";
angular.module('translate.app')
.factory('phraseMappingService', PhraseMappingService);
PhraseMappingService.$inject = ['configService'];
function PhraseMappingService(configService) {
return {
mapPhrase: function (phrase) {
return configService.get('profile')
.then(function (profile) {
if (profile && Array.isArray(profile.translations)) {
return profile.translations.reduce(function (prev, cur) {
var needle = new RegExp(escapeRegExp(cur.key), 'g');
return prev.replace(needle, cur.value);
}, phrase);
}
return phrase;
});
}
};
}
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
})();
|
Change user activation complete URL to avoid conflicts
Because a separate django app is overriding 'accounts/activate/w+'
'accounts/activate/complete' was never being hit.
Fixes #1133
|
from django.conf.urls import patterns
from django.conf.urls import include
from django.conf.urls import url
from django.views.generic.base import TemplateView
from views import RegistrationView, ActivationView
urlpatterns = patterns('',
url(r'^activation-complete/$',
TemplateView.as_view(template_name='registration/activation_complete.html'), # NOQA
name='registration_activation_complete'),
# Activation keys get matched by \w+ instead of the more specific
# [a-fA-F0-9]{40} because a bad activation key should still get
# to the view; that way it can return a sensible "invalid key"
# message instead of a confusing 404.
url(r'^activate/(?P<activation_key>\w+)/$',
ActivationView.as_view(),
name='registration_activate'),
url(r'^register/$',
RegistrationView.as_view(),
name='registration_register'),
url(r'^register/complete/$',
TemplateView.as_view(template_name='registration/registration_complete.html'), # NOQA
name='registration_complete'),
url(r'^register/closed/$',
TemplateView.as_view(template_name='registration/registration_closed.html'), # NOQA
name='registration_disallowed'),
(r'', include('registration.auth_urls')),
) # NOQA
|
from django.conf.urls import patterns
from django.conf.urls import include
from django.conf.urls import url
from django.views.generic.base import TemplateView
from views import RegistrationView, ActivationView
urlpatterns = patterns('',
url(r'^activate/complete/$',
TemplateView.as_view(template_name='registration/activation_complete.html'), # NOQA
name='registration_activation_complete'),
# Activation keys get matched by \w+ instead of the more specific
# [a-fA-F0-9]{40} because a bad activation key should still get
# to the view; that way it can return a sensible "invalid key"
# message instead of a confusing 404.
url(r'^activate/(?P<activation_key>\w+)/$',
ActivationView.as_view(),
name='registration_activate'),
url(r'^register/$',
RegistrationView.as_view(),
name='registration_register'),
url(r'^register/complete/$',
TemplateView.as_view(template_name='registration/registration_complete.html'), # NOQA
name='registration_complete'),
url(r'^register/closed/$',
TemplateView.as_view(template_name='registration/registration_closed.html'), # NOQA
name='registration_disallowed'),
(r'', include('registration.auth_urls')),
) # NOQA
|
Emphasize that we support Python 3.4.x
|
"""
CQLSL
-----
CQL for Python without any additional abstraction layers.
Designed to be simple and fast tool for communication with Cassandra.
CQLSL is something between native Cassandra driver (which is really awesome!) and ORM.
[Installation](https://github.com/drudim/cqlsl#installation)
[Documentation](https://github.com/drudim/cqlsl#getting-started)
"""
from setuptools import setup
import cqlsl
setup(
name='cqlsl',
version=cqlsl.__version__,
url='https://github.com/drudim/cqlsl',
license='MIT',
author='Dmytro Popovych',
author_email='drudim.ua@gmail.com',
description='CQL for Python without any additional abstraction layers',
long_description=__doc__,
keywords=['cassandra', 'cql'],
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.4",
"Topic :: Database :: Front-Ends",
"Operating System :: OS Independent",
],
packages=['cqlsl'],
include_package_data=True,
install_requires=['cassandra-driver >= 2.1.1'],
test_suite='tests',
)
|
"""
CQLSL
-----
CQL for Python without any additional abstraction layers.
Designed to be simple and fast tool for communication with Cassandra.
CQLSL is something between native Cassandra driver (which is really awesome!) and ORM.
[Installation](https://github.com/drudim/cqlsl#installation)
[Documentation](https://github.com/drudim/cqlsl#getting-started)
"""
from setuptools import setup
import cqlsl
setup(
name='cqlsl',
version=cqlsl.__version__,
url='https://github.com/drudim/cqlsl',
license='MIT',
author='Dmytro Popovych',
author_email='drudim.ua@gmail.com',
description='CQL for Python without any additional abstraction layers',
long_description=__doc__,
keywords=['cassandra', 'cql'],
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 2.7",
"Topic :: Database :: Front-Ends",
"Operating System :: OS Independent",
],
packages=['cqlsl'],
include_package_data=True,
install_requires=['cassandra-driver >= 2.1.1'],
test_suite='tests',
)
|
Revert "Don't add Change Password item yet"
This reverts commit 7dd474eefb54fb31fa09fe50c4634f7bd5f51d71.
|
@extends('layouts.master')
@section('content')
@section('nav-left')
<li><a href="{{ route('admin.requests') }}"><i class="fa fa-user-plus"></i> Pending Accounts</a></li>
<li><a href="{{ route('admin.users') }}"><i class="fa fa-user"></i> Users</a></li>
@stop
@section('nav-right')
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"
role="button" aria-haspopup="true" aria-expanded="false">
{{ Auth::user()->name }} <i class="fa fa-caret-down"></i></a>
<ul class="dropdown-menu">
<li><a href="#"><i class="fa fa-lock fa-fw"></i> Change Password</a></li>
<li role="separator" class="divider"></li>
<li><a href="{{ route('logout') }}"><i class="fa fa-sign-out fa-fw"></i> Logout</a></li>
</ul>
</li>
@stop
@yield('admin-content')
@stop
|
@extends('layouts.master')
@section('content')
@section('nav-left')
<li><a href="{{ route('admin.requests') }}"><i class="fa fa-user-plus"></i> Pending Accounts</a></li>
<li><a href="{{ route('admin.users') }}"><i class="fa fa-user"></i> Users</a></li>
@stop
@section('nav-right')
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"
role="button" aria-haspopup="true" aria-expanded="false">
{{ Auth::user()->name }} <i class="fa fa-caret-down"></i></a>
<ul class="dropdown-menu">
<li><a href="{{ route('logout') }}"><i class="fa fa-sign-out fa-fw"></i> Logout</a></li>
</ul>
</li>
@stop
@yield('admin-content')
@stop
|
Fix test bootstrap for new skinning approach
|
/*
* skinned-sdk.js
*
* Skins the react-sdk with a few stub components which we expect the
* application to provide
*/
/* this is a convenient place to ensure we load the compatibility libraries we expect our
* app to provide
*/
import * as sdk from "../src/index";
import stubComponent from "./components/stub-component";
const components = {};
components['structures.LeftPanel'] = stubComponent();
components['structures.RightPanel'] = stubComponent();
components['structures.RoomDirectory'] = stubComponent();
components['views.globals.MatrixToolbar'] = stubComponent();
components['views.globals.GuestWarningBar'] = stubComponent();
components['views.globals.NewVersionBar'] = stubComponent();
components['views.elements.Spinner'] = stubComponent({displayName: 'Spinner'});
components['views.messages.DateSeparator'] = stubComponent({displayName: 'DateSeparator'});
components['views.messages.MessageTimestamp'] = stubComponent({displayName: 'MessageTimestamp'});
components['views.messages.SenderProfile'] = stubComponent({displayName: 'SenderProfile'});
components['views.rooms.SearchBar'] = stubComponent();
sdk.loadSkin({components});
export default sdk;
|
/*
* skinned-sdk.js
*
* Skins the react-sdk with a few stub components which we expect the
* application to provide
*/
/* this is a convenient place to ensure we load the compatibility libraries we expect our
* app to provide
*/
// for ES6 stuff like startsWith() and Object.values() that babel doesn't do by
// default
require('babel-polyfill');
const sdk = require("../src/index");
const skin = require('../src/component-index.js');
const stubComponent = require('./components/stub-component.js');
const components = skin.components;
components['structures.LeftPanel'] = stubComponent();
components['structures.RightPanel'] = stubComponent();
components['structures.RoomDirectory'] = stubComponent();
components['views.globals.MatrixToolbar'] = stubComponent();
components['views.globals.GuestWarningBar'] = stubComponent();
components['views.globals.NewVersionBar'] = stubComponent();
components['views.elements.Spinner'] = stubComponent({displayName: 'Spinner'});
components['views.messages.DateSeparator'] = stubComponent({displayName: 'DateSeparator'});
components['views.messages.MessageTimestamp'] = stubComponent({displayName: 'MessageTimestamp'});
components['views.messages.SenderProfile'] = stubComponent({displayName: 'SenderProfile'});
components['views.rooms.SearchBar'] = stubComponent();
sdk.loadSkin(skin);
module.exports = sdk;
|
Change wording on warning for accuracy
|
var pingPongType = function(i) {
if ((i % 5 === 0) || (i % 3 === 0) || (i % 15 === 0)) {
if (i % 15 === 0) {
return "pingpong";
} else if (i % 5 === 0) {
return "pong";
} else {
return "ping";
}
} else {
return i;
}
}
$(function() {
$("#game").submit(function(event) {
$('#outputList').empty();
var number = parseInt($("#userNumber").val());
var warning = "Whoops! Please enter a number (decimals will be rounded)!"
if (Number.isNaN(number) === true) {
alert(warning);
}
for (var i = 1; i <= number; i += 1) {
var output = pingPongType(i)
$('#outputList').append("<li>" + output + "</li>")
}
event.preventDefault();
});
});
|
var pingPongType = function(i) {
if ((i % 5 === 0) || (i % 3 === 0) || (i % 15 === 0)) {
if (i % 15 === 0) {
return "pingpong";
} else if (i % 5 === 0) {
return "pong";
} else {
return "ping";
}
} else {
return i;
}
}
$(function() {
$("#game").submit(function(event) {
$('#outputList').empty();
var number = parseInt($("#userNumber").val());
var warning = "Whoops! Please enter an integer!"
if (Number.isNaN(number) === true) {
alert(warning);
}
for (var i = 1; i <= number; i += 1) {
var output = pingPongType(i)
$('#outputList').append("<li>" + output + "</li>")
}
event.preventDefault();
});
});
|
Store cur_language in alternate before everything
|
from django.conf import settings as django_settings
try:
from django.core.urlresolvers import reverse, resolve
except ImportError:
from django.urls import reverse, resolve
from django.utils.translation import activate, get_language
from urllib.parse import urljoin
from .request_utils import get_host_url
def settings(request):
return {'settings': django_settings}
def alternate_seo_url(request):
alternate_url = dict()
path = request.path
url_parts = resolve(path)
base_url = get_host_url(request)
cur_language = get_language()
if not url_parts.app_names:
for lang_code, lang_name in django_settings.LANGUAGES:
activate(lang_code)
url = reverse(
url_parts.view_name,
kwargs=url_parts.kwargs
)
alternate_url[lang_code] = urljoin(base_url, url)
activate(cur_language)
return {'alternate': alternate_url}
|
from django.conf import settings as django_settings
try:
from django.core.urlresolvers import reverse, resolve
except ImportError:
from django.urls import reverse, resolve
from django.utils.translation import activate, get_language
from urllib.parse import urljoin
from .request_utils import get_host_url
def settings(request):
return {'settings': django_settings}
def alternate_seo_url(request):
alternate_url = dict()
path = request.path
url_parts = resolve(path)
base_url = get_host_url(request)
if not url_parts.app_names:
cur_language = get_language()
for lang_code, lang_name in django_settings.LANGUAGES:
activate(lang_code)
url = reverse(
url_parts.view_name,
kwargs=url_parts.kwargs
)
alternate_url[lang_code] = urljoin(base_url, url)
activate(cur_language)
return {'alternate': alternate_url}
|
Refactor to use method calls rather than direct def calls.
|
module.exports = (function() {
var def = require('./def');
var util = require('./util');
var guard_undef = util.guard_undef;
var Message = def.type(function(raw_msg) {
guard_undef(raw_msg);
this.def_prop('raw', raw_msg);
this.def_prop('channel', slack.getChannelGroupOrDMByID(raw_msg.channel));
this.def_prop('user', slack.getUserByID(raw_msg.user));
this.def_prop('text', raw_msg.text);
});
Message.def_method(function send_to(name, text) {
return this.respond('@' + name + ': ' + text);
});
Message.def_method(function reply(text) {
return this.send_to(this.raw_msg.user.name, text);
});
Message.def_method(function respond(text) {
this.channel.send(text);
});
return Message;
})();
|
module.exports = (function() {
var def = require('./def');
var util = require('./util');
var guard_undef = util.guard_undef;
var Message = def.type(function(raw_msg) {
guard_undef(raw_msg);
var def_prop = def.prop.bind(this);
def_prop('raw', raw_msg);
def_prop('channel', slack.getChannelGroupOrDMByID(raw_msg.channel));
def_prop('user', slack.getUserByID(raw_msg.user));
def_prop('text', raw_msg.text);
});
def.method(Message, function send_to(name, text) {
return this.respond('@' + name + ': ' + text);
});
def.method(Message, function reply(text) {
return this.send_to(this.raw_msg.user.name, text);
});
def.method(type, function respond(text) {
this.channel.send(text);
});
return type;
})();
|
Add fields to save question url and annexure links
Details of each question is in another link and some questions have annexures
(in English/Hindi), add fields to save all these items
Signed-off-by: Arun Siluvery <66692e34e783869a1e5829b4c5eee5e1a471c4f7@gmail.com>
|
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class MemberofParliament(scrapy.Item):
"""
Data structure to define Member of Parliament information
"""
mp_id = scrapy.Field()
mp_name = scrapy.Field()
mp_constituency = scrapy.Field()
mp_party = scrapy.Field()
mp_photo = scrapy.Field()
class RajyaSabhaQuestion(scrapy.Item):
"""
Data structure to define a Rajya Sabha question
"""
q_no = scrapy.Field()
q_type = scrapy.Field()
q_date = scrapy.Field()
q_ministry = scrapy.Field()
q_member = scrapy.Field()
q_subject = scrapy.Field()
class LokSabhaQuestion(scrapy.Item):
"""
Data structure to define a Lok Sabha question
"""
q_no = scrapy.Field()
q_session = scrapy.Field()
q_type = scrapy.Field()
q_date = scrapy.Field()
q_ministry = scrapy.Field()
q_member = scrapy.Field()
q_subject = scrapy.Field()
q_url = scrapy.Field()
q_annex = scrapy.Field()
|
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class MemberofParliament(scrapy.Item):
"""
Data structure to define Member of Parliament information
"""
mp_id = scrapy.Field()
mp_name = scrapy.Field()
mp_constituency = scrapy.Field()
mp_party = scrapy.Field()
mp_photo = scrapy.Field()
class RajyaSabhaQuestion(scrapy.Item):
"""
Data structure to define a Rajya Sabha question
"""
q_no = scrapy.Field()
q_type = scrapy.Field()
q_date = scrapy.Field()
q_ministry = scrapy.Field()
q_member = scrapy.Field()
q_subject = scrapy.Field()
class LokSabhaQuestion(scrapy.Item):
"""
Data structure to define a Lok Sabha question
"""
q_no = scrapy.Field()
q_session = scrapy.Field()
q_type = scrapy.Field()
q_date = scrapy.Field()
q_ministry = scrapy.Field()
q_member = scrapy.Field()
q_subject = scrapy.Field()
|
Use `debug` instead of `console.log`
|
const { it } = require('mocha');
const debug = require('debug')('nails:test');
const initSocket = require('../../src/ws');
const { IO } = require('./util');
module.exports = ({ server }) => {
let connect;
initSocket({
on(connection, f) {
connect = f;
},
}, server.handler);
it('connects', () => {
const io = new IO();
connect(io);
});
it('joins the correct room', done => {
const io = new IO();
io.join = function (room) {
if (room === '/status') {
return done();
}
done(false);
};
connect(io);
process.nextTick(() => {
io.emit('join', '/status');
});
});
it('receives status messages', done => {
const io = new IO();
io.on('message', arg => {
if (['ok', '👍', '⚠', '🚨'].includes(arg)) {
done();
} else {
done(new Error('bad message: ' + require('util').inspect(arg, { depth: null })));
}
});
connect(io);
process.nextTick(() => {
io.emit('join', '/status');
});
io.on('error', err => {
debug('err!', err);
done(err);
io.close();
});
});
};
|
const { it } = require('mocha');
const initSocket = require('../../src/ws');
const { IO } = require('./util');
module.exports = ({ server }) => {
let connect;
initSocket({
on(connection, f) {
connect = f;
},
}, server.handler);
it('connects', () => {
const io = new IO();
connect(io);
});
it('joins the correct room', done => {
const io = new IO();
io.join = function (room) {
if (room === '/status') {
return done();
}
done(false);
};
connect(io);
process.nextTick(() => {
io.emit('join', '/status');
});
});
it('receives status messages', done => {
const io = new IO();
io.on('message', arg => {
if (['ok', '👍', '⚠', '🚨'].includes(arg)) {
done();
} else {
done(new Error('bad message: ' + require('util').inspect(arg, { depth: null })));
}
});
connect(io);
process.nextTick(() => {
io.emit('join', '/status');
});
io.on('error', err => {
console.log('err!', err);
done(err);
io.close();
});
});
};
|
Check in fix for py3k and urlparse.
|
import sys
import itertools
PY3 = sys.version_info[:2] >= (3,0)
if PY3:
def dict_iteritems(d):
return d.items().__iter__()
xrange = range
_inttypes = (int,)
_strtypes = (str,)
unicode = str
imap = map
basestring = str
import urllib.parse as urlparse
else:
import __builtin__
def dict_iteritems(d):
return d.iteritems()
xrange = __builtin__.xrange
unicode = __builtin__.unicode
basestring = __builtin__.basestring
_strtypes = (str, unicode)
_inttypes = (int, long)
imap = itertools.imap
import urlparse
|
import sys
import itertools
PY3 = sys.version_info[:2] >= (3,0)
if PY3:
def dict_iteritems(d):
return d.items().__iter__()
xrange = range
_inttypes = (int,)
_strtypes = (str,)
unicode = str
imap = map
basestring = str
import urllib
urlparse = urllib.parse
else:
import __builtin__
def dict_iteritems(d):
return d.iteritems()
xrange = __builtin__.xrange
unicode = __builtin__.unicode
basestring = __builtin__.basestring
_strtypes = (str, unicode)
_inttypes = (int, long)
imap = itertools.imap
import urlparse
|
Use version 0.9 of pyimagediet
|
from setuptools import setup
long_description = '''\
image-diet2 is a Django application for removing unnecessary bytes from image
files. It optimizes images without changing their look or visual quality
("losslessly").
It works on images in JPEG, GIF and PNG formats and will leave others
unchanged. Provides a seemless integration with easy_thumbnails app, but can
work with others too.'''
setup(
author="Marko Samastur",
author_email="markos@gaivo.net",
name='image-diet2',
version='0.7.1',
description='Remove unnecessary bytes from images',
long_description=long_description,
url='https://github.com/samastur/image-diet2/',
platforms=['OS Independent'],
license='MIT License',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
'Topic :: Utilities',
],
install_requires=[
'pyimagediet>=0.9',
],
include_package_data=True,
packages=['image_diet'],
zip_safe=False
)
|
from setuptools import setup
long_description = '''\
image-diet2 is a Django application for removing unnecessary bytes from image
files. It optimizes images without changing their look or visual quality
("losslessly").
It works on images in JPEG, GIF and PNG formats and will leave others
unchanged. Provides a seemless integration with easy_thumbnails app, but can
work with others too.'''
setup(
author="Marko Samastur",
author_email="markos@gaivo.net",
name='image-diet2',
version='0.7.1',
description='Remove unnecessary bytes from images',
long_description=long_description,
url='https://github.com/samastur/image-diet2/',
platforms=['OS Independent'],
license='MIT License',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
'Topic :: Utilities',
],
install_requires=[
'pyimagediet>=0.5',
],
include_package_data=True,
packages=['image_diet'],
zip_safe=False
)
|
Add date and social media fields to proposal
|
from django.db import models
from django.utils.timezone import now
from pyconcz_2016.conferences.models import Conference
class Cfp(models.Model):
conference = models.ForeignKey(Conference, related_name="cfps")
title = models.CharField(max_length=200)
date_start = models.DateTimeField()
date_end = models.DateTimeField()
class Meta:
ordering = ['date_start']
def __str__(self):
return self.title
class Proposal(models.Model):
DIFFICULTY = (
('all', 'All'),
('beginner', 'Beginner'),
('advanced', 'Advanced'),
)
cfp = models.ForeignKey(Cfp, related_name='proposals')
# Public speaker info
full_name = models.CharField(max_length=200)
bio = models.TextField()
twitter = models.CharField(max_length=20, blank=True)
github = models.CharField(max_length=20, blank=True)
# Public talk info
title = models.CharField(max_length=200)
abstract = models.TextField()
difficulty = models.CharField(
max_length=10, choices=DIFFICULTY, default='all')
# Private notes (for reviewers only)
note = models.TextField()
date = models.DateTimeField(default=now)
|
from django.db import models
from pyconcz_2016.conferences.models import Conference
class Cfp(models.Model):
conference = models.ForeignKey(Conference, related_name="cfps")
title = models.CharField(max_length=200)
date_start = models.DateTimeField()
date_end = models.DateTimeField()
class Meta:
ordering = ['date_start']
def __str__(self):
return self.title
class Proposal(models.Model):
DIFFICULTY = (
('all', 'All'),
('beginner', 'Beginner'),
('advanced', 'Advanced'),
)
cfp = models.ForeignKey(Cfp, related_name='proposals')
# Public speaker info
full_name = models.CharField(max_length=200)
bio = models.TextField()
twitter = models.CharField(max_length=20, blank=True)
github = models.CharField(max_length=20, blank=True)
# Public talk info
title = models.CharField(max_length=200)
abstract = models.TextField()
difficulty = models.CharField(
max_length=10, choices=DIFFICULTY, default='all')
# Private notes (for reviewers only)
note = models.TextField()
|
Add better label function for bullet
|
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
class Bullet extends Model
{
/**
* Each bullet belongs to a Cartridge type
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function cartridge() {
return $this->belongsTo('App\Cartridge');
}
public function purpose() {
return $this->belongsTo('App\Purpose');
}
public function updateInventory() {
$rounds_purchased = DB::table('orders')
->where('bullet_id', $this->id)
->sum('rounds');
$rounds_fired = DB::table('shoots')
->where('bullet_id', $this->id)
->sum('rounds');
$this->inventory = $rounds_purchased - $rounds_fired;
$this->save();
}
public function getLabel() {
return $this->cartridge->label . " " . $this->manufacturer . " " . $this->model . ", " . $this->weight . "gr";
}
}
|
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
class Bullet extends Model
{
/**
* Each bullet belongs to a Cartridge type
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function cartridge() {
return $this->belongsTo('App\Cartridge');
}
public function purpose() {
return $this->belongsTo('App\Purpose');
}
public function updateInventory() {
$rounds_purchased = DB::table('orders')
->where('bullet_id', $this->id)
->sum('rounds');
$rounds_fired = DB::table('shoots')
->where('bullet_id', $this->id)
->sum('rounds');
$this->inventory = $rounds_purchased - $rounds_fired;
$this->save();
}
}
|
refactor: Change iteration over a collection based on ags suggestion
|
def bot_says(channel, text, slack_client):
return slack_client.api_call("chat.postMessage",
channel=channel,
text=text,
as_user=True)
def compose_explanation(url):
return "If you would like {} to be stored please react to it with a :+1:, \
if you would like it to be ignored use :-1:".format(url)
def ask_confirmation(message, slack_client):
bot_says(message['channel'],
compose_explanation(message['url']),
slack_client)
def compose_url_list(url_cache_list):
if len(url_cache_list) == 0:
return "The list is empty"
intro = "The list of urls to be confirmed is: \n"
options = ["{} - {}".format(i, v['url']) for i, v in enumerate(url_cache_list)]
return intro + "\n".join(options)
def list_cached_urls(url_cache_list, channel, slack_client):
bot_says(channel,
compose_url_list(url_cache_list),
slack_client)
|
def bot_says(channel, text, slack_client):
return slack_client.api_call("chat.postMessage",
channel=channel,
text=text,
as_user=True)
def compose_explanation(url):
return "If you would like {} to be stored please react to it with a :+1:, \
if you would like it to be ignored use :-1:".format(url)
def ask_confirmation(message, slack_client):
bot_says(message['channel'],
compose_explanation(message['url']),
slack_client)
def compose_url_list(url_cache_list):
if len(url_cache_list) == 0:
return "The list is empty"
list_message = "The list of urls to be confirmed is: \n"
for index in range(0, len(url_cache_list)):
extra = "{} - {} \n".format(index, url_cache_list[index]['url'])
list_message = list_message + extra
return list_message
def list_cached_urls(url_cache_list, channel, slack_client):
bot_says(channel,
compose_url_list(url_cache_list),
slack_client)
|
Use absolute path for scikits.image.data_dir.
|
"""Image Processing SciKit (Toolbox for SciPy)"""
import os.path as _osp
data_dir = _osp.abspath(_osp.join(_osp.dirname(__file__), 'data'))
from version import version as __version__
def _setup_test():
import functools
basedir = _osp.dirname(_osp.join(__file__, '../'))
args = ['', '--exe', '-w', '%s' % basedir]
try:
import nose as _nose
except ImportError:
print("Could not load nose. Unit tests not available.")
return None
else:
return functools.partial(_nose.run, 'scikits.image', argv=args)
test = _setup_test()
if test is None:
del test
def get_log(name):
"""Return a console logger.
Output may be sent to the logger using the `debug`, `info`, `warning`,
`error` and `critical` methods.
Parameters
----------
name : str
Name of the log.
References
----------
.. [1] Logging facility for Python,
http://docs.python.org/library/logging.html
"""
import logging, sys
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
return logging.getLogger(name)
|
"""Image Processing SciKit (Toolbox for SciPy)"""
import os.path as _osp
data_dir = _osp.join(_osp.dirname(__file__), 'data')
from version import version as __version__
def _setup_test():
import functools
basedir = _osp.dirname(_osp.join(__file__, '../'))
args = ['', '--exe', '-w', '%s' % basedir]
try:
import nose as _nose
except ImportError:
print("Could not load nose. Unit tests not available.")
return None
else:
return functools.partial(_nose.run, 'scikits.image', argv=args)
test = _setup_test()
if test is None:
del test
def get_log(name):
"""Return a console logger.
Output may be sent to the logger using the `debug`, `info`, `warning`,
`error` and `critical` methods.
Parameters
----------
name : str
Name of the log.
References
----------
.. [1] Logging facility for Python,
http://docs.python.org/library/logging.html
"""
import logging, sys
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
return logging.getLogger(name)
|
Update the PyPI version to 7.0.14.
|
# -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='7.0.14',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
|
# -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='7.0.13',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
|
Prepare 0.15.0rc8 to release it as 0.15.0
|
# -*- coding: cp1252 -*-
#
##################################################################################
#
# Copyright 2014-2017 Félix Brezo and Yaiza Rubio (i3visio, contacto@i3visio.com)
#
# OSRFramework is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##################################################################################
import osrframework.utils.logger
# Calling the logger when being imported
osrframework.utils.logger.setupLogger(loggerName="osrframework")
__version__="0.15.0rc8"
|
# -*- coding: cp1252 -*-
#
##################################################################################
#
# Copyright 2014-2017 Félix Brezo and Yaiza Rubio (i3visio, contacto@i3visio.com)
#
# OSRFramework is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##################################################################################
import osrframework.utils.logger
# Calling the logger when being imported
osrframework.utils.logger.setupLogger(loggerName="osrframework")
__version__="0.15.0rc7"
|
Synchronize access to ServiceLoaders to prevent race conditions
|
package org.opencds.cqf.cql.engine.serializing;
import java.util.Iterator;
import java.util.ServiceLoader;
public class CqlLibraryReaderFactory {
static ServiceLoader<CqlLibraryReaderProvider> loader = ServiceLoader
.load(CqlLibraryReaderProvider.class);
public static synchronized Iterator<CqlLibraryReaderProvider> providers(boolean refresh) {
if (refresh) {
loader.reload();
}
return loader.iterator();
}
public static CqlLibraryReader getReader(String contentType) {
var providers = providers(false);
if (providers.hasNext()) {
return providers.next().create(contentType);
}
throw new RuntimeException("No ElmLibraryReaderProviders found for " + contentType);
}
}
|
package org.opencds.cqf.cql.engine.serializing;
import java.util.Iterator;
import java.util.ServiceLoader;
public class CqlLibraryReaderFactory {
static ServiceLoader<CqlLibraryReaderProvider> loader = ServiceLoader
.load(CqlLibraryReaderProvider.class);
public static Iterator<CqlLibraryReaderProvider> providers(boolean refresh) {
if (refresh) {
loader.reload();
}
return loader.iterator();
}
public static CqlLibraryReader getReader(String contentType) {
if (providers(false).hasNext()) {
return providers(false).next().create(contentType);
}
throw new RuntimeException("No ElmLibraryReaderProviders found for " + contentType);
}
}
|
Make the system paths more configurable
configs/test/SysPaths.py:
Make the paths more configurable
|
import os, sys
from os.path import isdir, join as joinpath
from os import environ as env
systemdir = None
bindir = None
diskdir = None
scriptdir = None
def load_defaults():
global systemdir, bindir, diskdir, scriptdir
if not systemdir:
try:
path = env['M5_PATH'].split(':')
except KeyError:
path = [ '/dist/m5/system' ]
for systemdir in path:
if os.path.isdir(systemdir):
break
else:
raise ImportError, "Can't find a path to system files."
if not bindir:
bindir = joinpath(systemdir, 'binaries')
if not diskdir:
diskdir = joinpath(systemdir, 'disks')
if not scriptdir:
scriptdir = joinpath(systemdir, 'boot')
def disk(file):
load_defaults()
return joinpath(diskdir, file)
def binary(file):
load_defaults()
return joinpath(bindir, file)
def script(file):
load_defaults()
return joinpath(scriptdir, file)
|
from m5 import *
import os.path
import sys
# Edit the following list to include the possible paths to the binary
# and disk image directories. The first directory on the list that
# exists will be selected.
SYSTEMDIR_PATH = ['/n/poolfs/z/dist/m5/system']
SYSTEMDIR = None
for d in SYSTEMDIR_PATH:
if os.path.exists(d):
SYSTEMDIR = d
break
if not SYSTEMDIR:
print >>sys.stderr, "Can't find a path to system files."
sys.exit(1)
BINDIR = SYSTEMDIR + '/binaries'
DISKDIR = SYSTEMDIR + '/disks'
def disk(file):
return os.path.join(DISKDIR, file)
def binary(file):
return os.path.join(BINDIR, file)
def script(file):
return os.path.join(SYSTEMDIR, 'boot', file)
|
Bring back PetitionResponse to petition detail page
|
import React from 'react';
import LayoutWrap from 'components/LayoutWrap';
import LayoutContent from 'components/LayoutContent';
import LayoutSidebar from 'components/LayoutSidebar';
import Container from 'components/Container';
import Section from 'components/Section';
import PetitionHeader from 'containers/PetitionHeader';
import PetitionBody from 'containers/PetitionBody';
import PetitionResponse from 'containers/PetitionResponse';
import PetitionSidebar from 'containers/PetitionSidebar';
const Petition = ({ preview }) => (
<article>
<Section theme={'grey'}>
<Container>
<PetitionHeader />
</Container>
</Section>
<Container>
<LayoutWrap>
<LayoutContent>
<PetitionBody />
<PetitionResponse />
</LayoutContent>
<LayoutSidebar>
<PetitionSidebar />
</LayoutSidebar>
</LayoutWrap>
</Container>
</article>
);
export default Petition;
|
import React from 'react';
import LayoutWrap from 'components/LayoutWrap';
import LayoutContent from 'components/LayoutContent';
import LayoutSidebar from 'components/LayoutSidebar';
import Container from 'components/Container';
import Section from 'components/Section';
import PetitionHeader from 'containers/PetitionHeader';
import PetitionBody from 'containers/PetitionBody';
import PetitionSidebar from 'containers/PetitionSidebar';
const Petition = ({ preview }) => (
<article>
<Section theme={'grey'}>
<Container>
<PetitionHeader />
</Container>
</Section>
<Container>
<LayoutWrap>
<LayoutContent>
<PetitionBody />
</LayoutContent>
<LayoutSidebar>
<PetitionSidebar />
</LayoutSidebar>
</LayoutWrap>
</Container>
</article>
);
export default Petition;
|
Work around gulp error during i18n asset rebuilding
The test file requires built assets, so linting fails with an unresolved require while the i18n assets are being built.
|
const jsdom = require('jsdom');
global.document = jsdom.jsdom("<!doctype html><html><body><div data-current_user='{ \"admin\": false, \"id\": null }' id='react_root'></div></body></html>", {
url: 'http://localhost',
skipWindowCheck: true
});
global.window = document.defaultView;
global.navigator = global.window.navigator;
const sinon = require('sinon');
const React = require('react');
const ReactDOM = require('react-dom');
const ReactTestUtils = require('react-addons-test-utils');
const $ = require('jquery');
const _ = require('lodash');
const moment = require('moment');
const momentRecur = require('moment-recur');
const I18n = require('../public/assets/javascripts/i18n.js'); // eslint-disable-line import/no-unresolved
const chai = require('chai');
const sinonChai = require('sinon-chai');
global.$ = $;
global._ = _;
global.sinon = sinon;
global.React = React;
global.ReactDOM = ReactDOM;
global.ReactTestUtils = ReactTestUtils;
global.Simulate = ReactTestUtils.Simulate;
global.moment = moment;
global['moment-recur'] = momentRecur;
global.I18n = I18n;
global.chai = chai;
global.expect = chai.expect;
global.assert = chai.assert;
global.Features = {};
require('../public/assets/javascripts/i18n/en'); // eslint-disable-line import/no-unresolved
chai.use(sinonChai);
|
const jsdom = require('jsdom');
global.document = jsdom.jsdom("<!doctype html><html><body><div data-current_user='{ \"admin\": false, \"id\": null }' id='react_root'></div></body></html>", {
url: 'http://localhost',
skipWindowCheck: true
});
global.window = document.defaultView;
global.navigator = global.window.navigator;
const sinon = require('sinon');
const React = require('react');
const ReactDOM = require('react-dom');
const ReactTestUtils = require('react-addons-test-utils');
const $ = require('jquery');
const _ = require('lodash');
const moment = require('moment');
const momentRecur = require('moment-recur');
const I18n = require('../public/assets/javascripts/i18n.js');
const chai = require('chai');
const sinonChai = require('sinon-chai');
global.$ = $;
global._ = _;
global.sinon = sinon;
global.React = React;
global.ReactDOM = ReactDOM;
global.ReactTestUtils = ReactTestUtils;
global.Simulate = ReactTestUtils.Simulate;
global.moment = moment;
global['moment-recur'] = momentRecur;
global.I18n = I18n;
global.chai = chai;
global.expect = chai.expect;
global.assert = chai.assert;
global.Features = {};
require('../public/assets/javascripts/i18n/en');
chai.use(sinonChai);
|
Remove selectorFound event listener
Rename templateLayout() to init()
|
/*!
* TemplateLayout Wef plugin
* Copyright (c) 2011 Pablo Escalada
* MIT Licensed
*/
//requires: cssParser
//exports: templateLayout
(function () {
var templateLayout = {
name:"templateLayout",
version:"0.0.1",
description:"W3C CSS Template Layout Module",
authors:["Pablo Escalada <uo1398@uniovi.es>"],
licenses:["MIT"], //TODO: Licenses
init:function () {
document.addEventListener('propertyFound', function (e) {
// e.target matches the elem from above
lastEvent = e;
//console.log(lastEvent.property);
}, false);
return templateLayout;
},
getLastEvent:function () {
return lastEvent;
}
};
var lastEvent = 0;
wef.plugins.register("templateLayout", templateLayout);
})();
|
/*!
* TemplateLayout Wef plugin
* Copyright (c) 2011 Pablo Escalada
* MIT Licensed
*/
//requires: cssParser
//exports: templateLayout
(function () {
var templateLayout = {
name:"templateLayout",
version:"0.0.1",
description:"W3C CSS Template Layout Module",
authors:["Pablo Escalada <uo1398@uniovi.es>"],
licenses:["MIT"], //TODO: Licenses
templateLayout:function () {
document.addEventListener('selectorFound', function (e) {
// e.target matches the elem from above
lastEvent = e;
//console.log(lastEvent.selectorText | lastEvent.property);
}, false);
document.addEventListener('propertyFound', function (e) {
// e.target matches the elem from above
lastEvent = e;
//console.log(lastEvent.selectorText | lastEvent.property);
}, false);
return templateLayout;
},
getLastEvent:function () {
return lastEvent;
}
};
var lastEvent = 0;
wef.plugins.register("templateLayout", templateLayout);
})();
|
Add search text to if not found message
|
<?php
# Grab the Slack post variables
$token = ($_POST['token'] === 'CxPDeOTKKscdX6nkTi3lOn1d' ? $_POST['token'] : false); # Replace with the token from your slash command config
$channel = $_POST['channel_name'];
$text = $_POST['text'];
# Check pre-requisites for the script to run
if(!$token){
$msg = "This token doesn't match the slack command set up.";
die($msg);
}
# Set up Frequently Asked Question (FAQ) array
$faq = [
"company information" => "Here is some information about our company...",
"contact" => "Here are the contact details for our company...",
];
# Check if the user's text has partially matched any of the FAQ keys
foreach ($faq as $key => $value) {
if (strpos(strtolower($key), strtolower($text)) !== false) {
$results[] = "*" . $key . "*\n\n" . $value . "\n\n";
}
}
# Output each of the matched key values
if (sizeof($results) > 0) {
foreach ($results as $key => $value) {
echo $value;
}
# or inform the user nothing was matched
} else if ((sizeof($results) === 0)) {
echo "We couldn't find a part of the guide related to the search *" . $text . "* :disappointed:";
}
|
<?php
# Grab the Slack post variables
$token = ($_POST['token'] === 'CxPDeOTKKscdX6nkTi3lOn1d' ? $_POST['token'] : false); # Replace with the token from your slash command config
$channel = $_POST['channel_name'];
$text = $_POST['text'];
# Check pre-requisites for the script to run
if(!$token){
$msg = "This token doesn't match the slack command set up.";
die($msg);
}
# Set up Frequently Asked Question (FAQ) array
$faq = [
"company information" => "Here is some information about our company...",
"contact" => "Here are the contact details for our company...",
];
# Check if the user's text has partially matched any of the FAQ keys
foreach ($faq as $key => $value) {
if (strpos(strtolower($key), strtolower($text)) !== false) {
$results[] = "*" . $key . "*\n\n" . $value . "\n\n";
}
}
# Output each of the matched key values
if (sizeof($results) > 0) {
foreach ($results as $key => $value) {
echo $value;
}
# or inform the user nothing was matched
} else if ((sizeof($results) === 0)) {
echo "We couldn't find a part of the guide related to this search :disappointed:";
}
|
Use the draw function in the test
|
/* eslint-env mocha */
let expect = require('chai').expect
let CardGame = require('./index')
let Deck = CardGame.Deck
describe('Deck', function () {
specify('An empty deck with no cards', function () {
let deckData = { cards: [ ] }
let deck = new Deck(deckData)
expect(deck.cards.length).to.eq(0)
})
specify('drawing from A Deck with an Ace of Spades and nothing else yields the ace of spades', function () {
let deckData = {
cards: [{
value: 'A',
suit: 'Spades'
}]
}
let deck = new Deck(deckData)
expect(deck.cards.length).to.eq(1)
let theAce = deck.draw()
expect(theAce.value).to.eq('A')
expect(theAce.suit).to.eq('Spades')
})
})
|
/* eslint-env mocha */
let expect = require('chai').expect
let CardGame = require('./index')
let Deck = CardGame.Deck
describe('Deck', function () {
specify('An empty deck with no cards', function () {
let deckData = { cards: [ ] }
let deck = new Deck(deckData)
expect(deck.cards.length).to.eq(0)
})
specify('A Deck with an Ace of Spades and nothing else', function () {
let deckData = {
cards: [{
value: 'A',
suit: 'Spades'
}]
}
let deck = new Deck(deckData)
expect(deck.cards.length).to.eq(1)
let theAce = deck.cards[0]
expect(theAce.value).to.eq('A')
expect(theAce.suit).to.eq('Spades')
})
specify('drawing from a deck with the jack of clubs in it yields the jack of clubs', function() {
let deckData = {
cards: [{
value: 'J',
suit: 'Clubs'
}]
}
let deck = new Deck(deckData)
let theJack = deck.draw()
expect(theJack.value).to.eq('J')
})
})
|
Add support for python 3.7 and 3.8 in package classifiers
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from setuptools import setup
from github_backup import __version__
def open_file(fname):
return open(os.path.join(os.path.dirname(__file__), fname))
setup(
name='github-backup',
version=__version__,
author='Jose Diaz-Gonzalez',
author_email='github-backup@josediazgonzalez.com',
packages=['github_backup'],
scripts=['bin/github-backup'],
url='http://github.com/josegonzalez/python-github-backup',
license=open('LICENSE.txt').read(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Topic :: System :: Archiving :: Backup',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
],
description='backup a github user or organization',
long_description=open_file('README.rst').read(),
install_requires=open_file('requirements.txt').readlines(),
zip_safe=True,
)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from setuptools import setup
from github_backup import __version__
def open_file(fname):
return open(os.path.join(os.path.dirname(__file__), fname))
setup(
name='github-backup',
version=__version__,
author='Jose Diaz-Gonzalez',
author_email='github-backup@josediazgonzalez.com',
packages=['github_backup'],
scripts=['bin/github-backup'],
url='http://github.com/josegonzalez/python-github-backup',
license=open('LICENSE.txt').read(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Topic :: System :: Archiving :: Backup',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
],
description='backup a github user or organization',
long_description=open_file('README.rst').read(),
install_requires=open_file('requirements.txt').readlines(),
zip_safe=True,
)
|
Remove reporter from gulp mocha options
|
const gulp = require('gulp');
const util = require('gulp-util');
const babel = require('gulp-babel');
const mocha = require('gulp-mocha');
const eslint = require('gulp-eslint');
const compiler = require('babel-core/register');
const src = 'src/*.js';
gulp.task('lint', () => (
gulp.src(src)
.pipe(eslint())
.pipe(eslint.format())
));
gulp.task('test', ['lint'], () => (
gulp.src('test')
.pipe(mocha({
compilers: {
js: compiler,
},
}))
.on('error', util.log)
));
gulp.task('build', ['test'], () => (
gulp.src(src)
.pipe(babel())
.pipe(gulp.dest('lib'))
));
gulp.task('default', ['build']);
|
const gulp = require('gulp');
const util = require('gulp-util');
const babel = require('gulp-babel');
const mocha = require('gulp-mocha');
const eslint = require('gulp-eslint');
const compiler = require('babel-core/register');
const src = 'src/*.js';
gulp.task('lint', () => (
gulp.src(src)
.pipe(eslint())
.pipe(eslint.format())
));
gulp.task('test', ['lint'], () => (
gulp.src('test')
.pipe(mocha({
reporter: 'spec',
compilers: {
js: compiler,
},
}))
.on('error', util.log)
));
gulp.task('build', ['test'], () => (
gulp.src(src)
.pipe(babel())
.pipe(gulp.dest('lib'))
));
gulp.task('default', ['build']);
|
Fix Ratio Imageslider (wordpresss starter)
|
<?php
/**
* Image Slider
* ============
* Build a Image Slider with Swipper.js
*/
// Default Vars
$classname = 'o-imageslider';
$ratio = get_sub_field('ratio');
?>
<? // Build Element Block ?>
<figure class="<?= $classname; ?>" itemscope itemtype="http://schema.org/ImageGallery" role="presentation">
<div class="<?= $classname; ?>__wrapper">
<?php while( have_rows('photos') ) : the_row(); ?>
<div class="<?= $classname; ?>__slide" itemscope itemtype="http://schema.org/ImageObject">
<?php macro_mediaImageSet(get_sub_field('photo'), $classname.'__image', $ratio); ?>
</div>
<?php endwhile; ?>
</div>
<div class="<?= $classname; ?>__pagination"></div>
<div class="<?= $classname; ?>__button-next"></div>
<div class="<?= $classname; ?>__button-prev"></div>
</figure>
|
<?php
/**
* Image Slider
* ============
* Build a Image Slider with Swipper.js
*/
// Default Vars
$classname = 'o-imageslider';
?>
<? // Build Element Block ?>
<figure class="<?= $classname; ?>" itemscope itemtype="http://schema.org/ImageGallery" role="presentation">
<div class="<?= $classname; ?>__wrapper">
<?php while( have_rows('photos') ) : the_row(); ?>
<div class="<?= $classname; ?>__slide" itemscope itemtype="http://schema.org/ImageObject">
<?php macro_mediaImageSet(get_sub_field('photo'), $classname.'__image', get_sub_field('ratio')); ?>
</div>
<?php endwhile; ?>
</div>
<div class="<?= $classname; ?>__pagination"></div>
<div class="<?= $classname; ?>__button-next"></div>
<div class="<?= $classname; ?>__button-prev"></div>
</figure>
|
Tweak and simplify FormRequest validations
|
<?php
declare(strict_types=1);
namespace Rinvex\Support\Traits;
trait Escaper
{
/**
* Escape all values.
*
* @param array $data
*
* @return array
*/
protected function escape(array $data): array
{
$arrayDot = array_filter(array_dot($data));
foreach ($arrayDot as $key => $value) {
if (is_string($value)) {
$arrayDot[$key] = e($value);
}
}
foreach ($arrayDot as $key => $value) {
array_set($data, $key, $value);
}
return $data;
}
/**
* Configure the validator instance.
*
* @param \Illuminate\Validation\Validator $validator
*
* @return void
*/
public function withValidator($validator): void
{
// Sanitize input data before submission
$this->replace($this->escape($this->all()));
}
}
|
<?php
declare(strict_types=1);
namespace Rinvex\Support\Traits;
trait Escaper
{
/**
* Escape all values.
*
* @param array $data
*
* @return array
*/
protected function escape(array $data): array
{
$arrayDot = array_filter(array_dot($data));
foreach ($arrayDot as $key => $value) {
if (is_string($value)) {
$arrayDot[$key] = e($value);
}
}
foreach ($arrayDot as $key => $value) {
array_set($data, $key, $value);
}
return $data;
}
}
|
Print the Nagare version number
--HG--
extra : convert_revision : svn%3Afc25bd86-f976-46a1-be41-59ef0291ea8c/trunk%4076
|
#--
# Copyright (c) 2008, 2009 Net-ng.
# All rights reserved.
#
# This software is licensed under the BSD License, as described in
# the file LICENSE.txt, which you should have received as part of
# this distribution.
#--
"""The ``info`` administrative command
Display informations about the framework environment
"""
import sys, pkg_resources
from nagare.admin import util
class Info(util.Command):
"""Display informations about the framework environment"""
desc = 'Display various informations'
@staticmethod
def run(parser, options, args):
"""Display the informations
In:
- ``parser`` -- the optparse.OptParser object used to parse the configuration file
- ``options`` -- options in the command lines
- ``args`` -- arguments in the command lines
"""
# For the moment, just diplay the Python version
print sys.version
print
print 'Nagare version', pkg_resources.get_distribution('nagare').version
|
#--
# Copyright (c) 2008, 2009 Net-ng.
# All rights reserved.
#
# This software is licensed under the BSD License, as described in
# the file LICENSE.txt, which you should have received as part of
# this distribution.
#--
"""The ``info`` administrative command
Display informations about the framework environment
"""
import sys
from nagare.admin import util
class Info(util.Command):
"""Display informations about the framework environment"""
desc = 'Display various informations'
@staticmethod
def run(parser, options, args):
"""Display the informations
In:
- ``parser`` -- the optparse.OptParser object used to parse the configuration file
- ``options`` -- options in the command lines
- ``args`` -- arguments in the command lines
"""
# For the moment, just diplay the Python version
print sys.version
|
Fix directories for watch files
|
module.exports = function(grunt) {
// Add the grunt-mocha-test tasks.
grunt.loadNpmTasks('grunt-contrib-jasmine');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.initConfig({
jasmine : {
src : 'src/**/*.js',
options : {
specs : 'spec/**/*.js'
}
},
watch: {
scripts: {
files: ['src/**/*.js', 'spec/**/*.js'],
tasks: ['jshint'],
options: {
spawn: false,
}
}
},
jshint: {
all: [
'Gruntfile.js',
'src/**/*.js',
'test/**/*.js'
]
}
});
grunt.registerTask('default', ['jshint', 'jasmine']);
};
|
module.exports = function(grunt) {
// Add the grunt-mocha-test tasks.
grunt.loadNpmTasks('grunt-contrib-jasmine');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.initConfig({
jasmine : {
src : 'src/**/*.js',
options : {
specs : 'spec/**/*.js'
}
},
watch: {
scripts: {
files: ['static/js/**/*.js', 'test/**/*.js'],
tasks: ['jshint'],
options: {
spawn: false,
}
}
},
jshint: {
all: [
'Gruntfile.js',
'src/**/*.js',
'test/**/*.js'
]
}
});
grunt.registerTask('default', ['jshint', 'jasmine']);
};
|
Change the key to be string
|
import os
from flask import Flask, request
import psycopg2
import json
app = Flask(__name__)
DATABASE_URL = os.environ['DATABASE_URL']
conn = psycopg2.connect(DATABASE_URL)
@app.route('/find')
def find():
lat = request.args.get('lat')
lng = request.args.get('lng')
radius = request.args.get('radius')
cursor = conn.cursor()
query = 'SELECT * from signs WHERE earth_box(ll_to_earth(%s, %s), %s) @> ll_to_earth(latitude, longtitude);'
cursor.execute(query, (lat, lng, radius))
columns = ['longtitude', 'latitude', 'object_id', 'sg_key_bor', 'sg_order_n', 'sg_seqno_n', 'sg_mutcd_c', 'sr_dist', 'sg_sign_fc', 'sg_arrow_d', 'x', 'y', 'signdesc']
results = []
for row in cursor.fetchall():
results.append(dict(zip(columns, row)))
return json.dumps({'results':results})
if __name__ == '__main__':
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port, debug=True)
|
import os
from flask import Flask, request
import psycopg2
import json
app = Flask(__name__)
DATABASE_URL = os.environ['DATABASE_URL']
conn = psycopg2.connect(DATABASE_URL)
@app.route('/find')
def find():
lat = request.args.get('lat')
lng = request.args.get('lng')
radius = request.args.get('radius')
cursor = conn.cursor()
query = 'SELECT * from signs WHERE earth_box(ll_to_earth(%s, %s), %s) @> ll_to_earth(latitude, longtitude);'
cursor.execute(query, (lat, lng, radius))
columns = ['longtitude', 'latitude', 'object_id', 'sg_key_bor', 'sg_order_n', 'sg_seqno_n', 'sg_mutcd_c', 'sr_dist', 'sg_sign_fc', 'sg_arrow_d', 'x', 'y', 'signdesc']
results = []
for row in cursor.fetchall():
results.append(dict(zip(columns, row)))
return json.dumps({results:results})
if __name__ == '__main__':
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port, debug=True)
|
Update formatting on track labels
|
__author__ = 'dcl9'
from render import render_template
import argparse
import yaml
def generate_track_dict(metadata):
d = dict()
d['track_name'] = '{}_{}({})'.format(metadata['protein'], metadata['serial_number'], metadata['author_identifier'])
d['bigbed_url'] = metadata['track_filename']
d['short_label'] = '{}_{} binding'.format(metadata['protein'], metadata['serial_number'])
d['long_label'] = 'Predicted {} binding sites (site width = {})'.format(metadata['protein'], metadata['width'])
return d
def render_tracks(assembly, metadata_file):
obj = yaml.load(metadata_file)
# Just pull out the assembly ones
tracks = [generate_track_dict(x) for x in obj if x['assembly'] == assembly]
trackdb = {'tracks': tracks}
render_template(trackdb, 'trackDb')
def main():
parser = argparse.ArgumentParser(description='Render trackDb.txt')
parser.add_argument('--assembly')
parser.add_argument('metadata_file', type=argparse.FileType('r'))
args = parser.parse_args()
render_tracks(args.assembly, args.metadata_file)
if __name__ == '__main__':
main()
|
__author__ = 'dcl9'
from render import render_template
import argparse
import yaml
def generate_track_dict(metadata):
d = dict()
d['track_name'] = '{}_{}({})'.format(metadata['protein'], metadata['serial_number'], metadata['author_identifier'])
d['bigbed_url'] = metadata['track_filename']
d['short_label'] = '{}_{} binding sites'.format(metadata['protein'], metadata['serial_number'])
d['long_label'] = 'Predicted {} binding sites (site width = {}, model identifier {}({}))'.format(metadata['protein'], metadata['width'], metadata['serial_number'], metadata['author_identifier'])
return d
def render_tracks(assembly, metadata_file):
obj = yaml.load(metadata_file)
# Just pull out the assembly ones
tracks = [generate_track_dict(x) for x in obj if x['assembly'] == assembly]
trackdb = {'tracks': tracks}
render_template(trackdb, 'trackDb')
def main():
parser = argparse.ArgumentParser(description='Render trackDb.txt')
parser.add_argument('--assembly')
parser.add_argument('metadata_file', type=argparse.FileType('r'))
args = parser.parse_args()
render_tracks(args.assembly, args.metadata_file)
if __name__ == '__main__':
main()
|
Make the one-step backend a little more robust with custom users.
|
"""
A one-step (user signs up and is immediately active and logged in)
workflow.
"""
from django.contrib.auth import authenticate, get_user_model, login
from django.urls import reverse_lazy
from django_registration import signals
from django_registration.views import RegistrationView as BaseRegistrationView
User = get_user_model()
class RegistrationView(BaseRegistrationView):
"""
Registration via the simplest possible process: a user supplies a
username, email address and password (the bare minimum for a
useful account), and is immediately signed up and logged in.
"""
success_url = reverse_lazy('registration_complete')
def register(self, form):
new_user = form.save()
new_user = authenticate(**{
User.USERNAME_FIELD: getattr(new_user, User.USERNAME_FIELD),
'password': form.cleaned_data['password1']
})
login(self.request, new_user)
signals.user_registered.send(
sender=self.__class__,
user=new_user,
request=self.request
)
return new_user
|
"""
A one-step (user signs up and is immediately active and logged in)
workflow.
"""
from django.contrib.auth import authenticate, get_user_model, login
from django.urls import reverse_lazy
from django_registration import signals
from django_registration.views import RegistrationView as BaseRegistrationView
User = get_user_model()
class RegistrationView(BaseRegistrationView):
"""
Registration via the simplest possible process: a user supplies a
username, email address and password (the bare minimum for a
useful account), and is immediately signed up and logged in.
"""
success_url = reverse_lazy('registration_complete')
def register(self, form):
new_user = form.save()
new_user = authenticate(
username=getattr(new_user, User.USERNAME_FIELD),
password=form.cleaned_data['password1']
)
login(self.request, new_user)
signals.user_registered.send(
sender=self.__class__,
user=new_user,
request=self.request
)
return new_user
|
Use blocking call to queue and null safe it.
|
package com.github.ingarabr.mi;
import org.elasticsearch.client.Client;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class EsWriter implements Runnable {
private final Client esClient;
private final BlockingQueue<String> writeQueue = new LinkedBlockingQueue<String>();
private boolean run = true;
public EsWriter(Client esClient) {
this.esClient = esClient;
}
public void run() {
try {
while (run) {
String metric = writeQueue.take();
log();
if (metric != null) {
esClient.prepareIndex("metrics", "metric").setSource(metric).get();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void log() {
if (writeQueue.size() > 10) {
System.out.println("ElasticSearch WriteQueue size: " + writeQueue.size());
}
}
public void addMetric(String metric) {
writeQueue.add(metric);
}
public void stop() {
run = false;
}
}
|
package com.github.ingarabr.mi;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
import org.elasticsearch.client.Client;
public class EsWriter implements Runnable {
private final Client esClient;
private final Queue<String> writeQueue = new LinkedBlockingQueue<String>();
private boolean run = true;
public EsWriter(Client esClient) {
this.esClient = esClient;
}
public void run() {
while (run) {
String metric = writeQueue.poll();
log();
esClient.prepareIndex("metrics", "metric").setSource(metric).get();
}
}
private void log() {
if (writeQueue.size() > 10) {
System.out.println("ElasticSearch WriteQueue size: " + writeQueue.size());
}
}
public void addMetric(String metric) {
writeQueue.add(metric);
}
public void stop() {
run = false;
}
}
|
Set ISO date as the Sentry release tag
|
// @flow
import Raven from 'raven-js';
function addUserData(data) {
if (!window.champaign) return;
if (!window.champaign.personalization) return;
const { location, member } = window.champaign.personalization;
data.user = {
id: member ? member.id : undefined,
username: member ? member.name : undefined,
ip: location ? location.ip : undefined,
};
}
function addReduxState(data) {
if (window.champaign && window.champaign.store) {
data.extra = {
...data.extra,
reduxState: window.champaign.store.getState(),
};
}
}
Raven.config(process.env.SENTRY_DSN, {
release: new Date().toISOString(),
environment: process.env.SENTRY_ENVIRONMENT || 'development',
dataCallback: data => {
addUserData(data);
addReduxState(data);
return data;
},
}).install();
window.Raven = Raven;
|
// @flow
import Raven from 'raven-js';
function addUserData(data) {
if (!window.champaign) return;
if (!window.champaign.personalization) return;
const { location, member } = window.champaign.personalization;
data.user = {
id: member ? member.id : undefined,
username: member ? member.name : undefined,
ip: location ? location.ip : undefined,
};
}
function addReduxState(data) {
if (window.champaign && window.champaign.store) {
data.extra = {
...data.extra,
reduxState: window.champaign.store.getState(),
};
}
}
Raven.config(process.env.SENTRY_DSN, {
release: process.env.CIRCLE_SHA1,
environment: process.env.SENTRY_ENVIRONMENT || 'development',
dataCallback: data => {
addUserData(data);
addReduxState(data);
return data;
},
}).install();
window.Raven = Raven;
|
Add support for manual journals
|
from .manager import Manager
class Xero(object):
"""An ORM-like interface to the Xero API"""
OBJECT_LIST = (u'Contacts', u'Accounts', u'CreditNotes',
u'Currencies', u'Invoices', u'Items', u'Organisation',
u'Payments', u'TaxRates', u'TrackingCategories', u'ManualJournals')
def __init__(self, credentials):
# Iterate through the list of objects we support, for
# each of them create an attribute on our self that is
# the lowercase name of the object and attach it to an
# instance of a Manager object to operate on it
for name in self.OBJECT_LIST:
setattr(self, name.lower(), Manager(name, credentials.oauth))
|
from .manager import Manager
class Xero(object):
"""An ORM-like interface to the Xero API"""
OBJECT_LIST = (u'Contacts', u'Accounts', u'CreditNotes',
u'Currencies', u'Invoices', u'Items', u'Organisation',
u'Payments', u'TaxRates', u'TrackingCategories')
def __init__(self, credentials):
# Iterate through the list of objects we support, for
# each of them create an attribute on our self that is
# the lowercase name of the object and attach it to an
# instance of a Manager object to operate on it
for name in self.OBJECT_LIST:
setattr(self, name.lower(), Manager(name, credentials.oauth))
|
Revert "Not fail the build if file-leak-detector server down"
This reverts commit f4003e6e794f75517f160c46e19bed52fc5a0165.
|
import java.time.format.*;
import java.time.*;
import java.io.*;
import java.nio.file.*;
import java.net.*;
import java.util.*;
public class DumpOpenFiles {
public static void main(String[] args) throws Exception {
String url = "http://localhost:" + parsePort() + "/dump";
System.out.println("Sending request to " + url);
try (BufferedReader response = new BufferedReader(new InputStreamReader(new URL(url).openStream()))) {
String line = null;
while ((line = response.readLine()) != null) {
System.out.println(line);
}
}
}
private static String parsePort() throws Exception {
if (new File("port.txt").isFile()) {
return Files.readAllLines(new File("port.txt").toPath()).get(0).trim();
} else {
System.err.println("Port not found, skip");
System.exit(0);
return "";
}
}
}
|
import java.time.format.*;
import java.time.*;
import java.io.*;
import java.nio.file.*;
import java.net.*;
import java.util.*;
public class DumpOpenFiles {
public static void main(String[] args) throws Exception {
String url = "http://localhost:" + parsePort() + "/dump";
System.out.println("Sending request to " + url);
try (BufferedReader response = new BufferedReader(new InputStreamReader(new URL(url).openStream()))) {
String line = null;
while ((line = response.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static String parsePort() throws Exception {
if (new File("port.txt").isFile()) {
return Files.readAllLines(new File("port.txt").toPath()).get(0).trim();
} else {
System.err.println("Port not found, skip");
System.exit(0);
return "";
}
}
}
|
Migrate from Folly Format to fmt
Summary: Migrate from Folly Format to fmt which provides smaller compile times and per-call binary code size.
Reviewed By: alandau
Differential Revision: D14954926
fbshipit-source-id: 9d2c39e74a5d11e0f90c8ad0d71b79424c56747f
|
#!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import specs.folly as folly
import specs.fizz as fizz
import specs.fmt as fmt
import specs.rsocket as rsocket
import specs.sodium as sodium
import specs.wangle as wangle
import specs.zstd as zstd
from shell_quoting import ShellQuoted
def fbcode_builder_spec(builder):
# This API should change rarely, so build the latest tag instead of master.
builder.add_option(
'no1msd/mstch:git_hash',
ShellQuoted('$(git describe --abbrev=0 --tags)')
)
return {
'depends_on': [folly, fizz, fmt, sodium, rsocket, wangle, zstd],
'steps': [
# This isn't a separete spec, since only fbthrift uses mstch.
builder.github_project_workdir('no1msd/mstch', 'build'),
builder.cmake_install('no1msd/mstch'),
builder.fb_github_cmake_install('fbthrift/thrift'),
],
}
|
#!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import specs.folly as folly
import specs.fizz as fizz
import specs.rsocket as rsocket
import specs.sodium as sodium
import specs.wangle as wangle
import specs.zstd as zstd
from shell_quoting import ShellQuoted
def fbcode_builder_spec(builder):
# This API should change rarely, so build the latest tag instead of master.
builder.add_option(
'no1msd/mstch:git_hash',
ShellQuoted('$(git describe --abbrev=0 --tags)')
)
return {
'depends_on': [folly, fizz, sodium, rsocket, wangle, zstd],
'steps': [
# This isn't a separete spec, since only fbthrift uses mstch.
builder.github_project_workdir('no1msd/mstch', 'build'),
builder.cmake_install('no1msd/mstch'),
builder.fb_github_cmake_install('fbthrift/thrift'),
],
}
|
service: Send tags out in array
|
<?php
/* Notice: Copyright 2016, The Care Connections Initiative c.i.c.
* Author: Charlie Fyvie-Gauld <cfg@zunautica.org>
* License: Apache License, Version 2 (http://www.apache.org/licenses/LICENSE-2.0)
*/
use Flintstone\Flintstone;
if(!defined('SPRING_IF')) return [];
$options['dir'] = SpringDvs\Config::$sys['store_live'];
$db = new Flintstone('netservice_bulletin', $options);
$bulletins = $db->getAll();
$final = [];
$queries = [];
parse_str($url->query(), $queries);
if(isset($queries['tags'])) {
$qtags = explode(',', $queries['tags']);
foreach($bulletins as $key => &$value) {
$tags = explode(',', $value['tags']);
foreach($tags as $tag) {
if(in_array(trim($tag), $qtags)){
$value['tags'] = $tags;
$final[$key] = $value;
}
}
}
} else {
foreach($bulletins as $key => &$value) {
$tags = explode(',', $value['tags']);
$value['tags'] = $tags;
}
$final = $bulletins;
}
return array_values($final);
|
<?php
/* Notice: Copyright 2016, The Care Connections Initiative c.i.c.
* Author: Charlie Fyvie-Gauld <cfg@zunautica.org>
* License: Apache License, Version 2 (http://www.apache.org/licenses/LICENSE-2.0)
*/
use Flintstone\Flintstone;
if(!defined('SPRING_IF')) return [];
$options['dir'] = SpringDvs\Config::$sys['store_live'];
$db = new Flintstone('netservice_bulletin', $options);
$bulletins = $db->getAll();
$final = [];
$queries = [];
parse_str($url->query(), $queries);
if(isset($queries['tags'])) {
$qtags = explode(',', $queries['tags']);
foreach($bulletins as $key => $value) {
$tags = explode(',', $value['tags']);
foreach($tags as $tag) {
if(in_array(trim($tag), $qtags)){
$final[$key] = $value;
}
}
}
} else {
$final = $bulletins;
}
return array_values($final);
|
Change /data servlet to show Hello Laura!
|
// Copyright 2019 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.
package com.google.sps.servlets;
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/** Servlet that returns some example content. TODO: modify this file to handle comments data */
@WebServlet("/data")
public class DataServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html;");
response.getWriter().println("<h1>Hello Laura!</h1>");
}
}
|
// Copyright 2019 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.
package com.google.sps.servlets;
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/** Servlet that returns some example content. TODO: modify this file to handle comments data */
@WebServlet("/data")
public class DataServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html;");
response.getWriter().println("<h1>Hello world!</h1>");
}
}
|
Remove unnecessary variable from route
Jinja will set any variable it can't find to None, so the title variable
is unnecessary.
|
from flask import render_template, request, flash
from flask_login import login_required
from .. import main
from ... import data_api_client
from ..auth import role_required
@main.route('/buyers', methods=['GET'])
@login_required
@role_required('admin')
def find_buyer_by_brief_id():
brief_id = request.args.get('brief_id')
try:
brief = data_api_client.get_brief(brief_id).get('briefs')
except:
flash('no_brief', 'error')
return render_template(
"view_buyers.html",
users=list(),
brief_id=brief_id
), 404
users = brief.get('users')
title = brief.get('title')
return render_template(
"view_buyers.html",
users=users,
title=title,
brief_id=brief_id
)
|
from flask import render_template, request, flash
from flask_login import login_required
from .. import main
from ... import data_api_client
from ..auth import role_required
@main.route('/buyers', methods=['GET'])
@login_required
@role_required('admin')
def find_buyer_by_brief_id():
brief_id = request.args.get('brief_id')
try:
brief = data_api_client.get_brief(brief_id).get('briefs')
except:
flash('no_brief', 'error')
return render_template(
"view_buyers.html",
users=list(),
title=None,
brief_id=brief_id
), 404
users = brief.get('users')
title = brief.get('title')
return render_template(
"view_buyers.html",
users=users,
title=title,
brief_id=brief_id
)
|
Add catchall fields property to KeyValueSerializer
With the latest django-restframework, not explicitly setting the
fields for a serializer causes errors. This explicitly sets the
fields to those of the model.
|
from django.core.exceptions import PermissionDenied
from rest_framework import serializers
from wafer.kv.models import KeyValue
class KeyValueSerializer(serializers.ModelSerializer):
class Meta:
model = KeyValue
fields = ('group', 'key', 'value')
# There doesn't seem to be a better way of handling the problem
# of filtering the groups.
# See the DRF meta-issue https://github.com/tomchristie/django-rest-framework/issues/1985
# and various related subdisscussions, such as https://github.com/tomchristie/django-rest-framework/issues/2292
def __init__(self, *args, **kwargs):
# Explicitly fail with a hopefully informative error message
# if there is no request. This is for introspection tools which
# call serializers without a request
if 'request' not in kwargs['context']:
raise PermissionDenied("No request information provided."
"The KeyValue API isn't available without "
"an authorized user")
user = kwargs['context']['request'].user
# Limit to groups shown to those we're a member of
groups = self.fields['group']
groups.queryset = user.groups
super(KeyValueSerializer, self).__init__(*args, **kwargs)
|
from django.core.exceptions import PermissionDenied
from rest_framework import serializers
from wafer.kv.models import KeyValue
class KeyValueSerializer(serializers.ModelSerializer):
class Meta:
model = KeyValue
# There doesn't seem to be a better way of handling the problem
# of filtering the groups.
# See the DRF meta-issue https://github.com/tomchristie/django-rest-framework/issues/1985
# and various related subdisscussions, such as https://github.com/tomchristie/django-rest-framework/issues/2292
def __init__(self, *args, **kwargs):
# Explicitly fail with a hopefully informative error message
# if there is no request. This is for introspection tools which
# call serializers without a request
if 'request' not in kwargs['context']:
raise PermissionDenied("No request information provided."
"The KeyValue API isn't available without "
"an authorized user")
user = kwargs['context']['request'].user
# Limit to groups shown to those we're a member of
groups = self.fields['group']
groups.queryset = user.groups
super(KeyValueSerializer, self).__init__(*args, **kwargs)
|
Add default value for config
|
import configJson from '../../../../config.json'; // root path json config
const config = 'production' === process.env.NODE_ENV ? configJson.production : configJson.development;
export const GOOGLE_API_KEY = (config.google && config.google.apiKey) || '';
export const GOOGLE_CLIENT_ID = (config.google && config.google.clientID) || '';
export const DROPBOX_APP_KEY = (config.dropbox && config.dropbox.appKey) || '';
export const domain = config.domain || ''; // domain name
export const urlpath = config.urlpath || ''; // sub url path, like: www.example.com/<urlpath>
export const debug = config.debug || false;
export const port = window.location.port;
export const serverurl = `${window.location.protocol}//${domain ? domain : window.location.hostname}${port ? ':' + port : ''}${urlpath ? '/' + urlpath : ''}`;
window.serverurl = serverurl;
export const noteid = urlpath ? window.location.pathname.slice(urlpath.length + 1, window.location.pathname.length).split('/')[1] : window.location.pathname.split('/')[1];
export const noteurl = `${serverurl}/${noteid}`;
export const version = '0.5.0';
|
import configJson from '../../../../config.json'; // root path json config
const config = 'production' === process.env.NODE_ENV ? configJson.production : configJson.development;
export const GOOGLE_API_KEY = config.google && config.google.apiKey;
export const GOOGLE_CLIENT_ID = config.google && config.google.clientID
export const DROPBOX_APP_KEY = config.dropbox && config.dropbox.appKey
export const domain = config.domain;
export const urlpath = config.urlpath;
export const debug = config.debug;
export const port = window.location.port;
export const serverurl = `${window.location.protocol}//${domain ? domain : window.location.hostname}${port ? ':' + port : ''}${urlpath ? '/' + urlpath : ''}`;
window.serverurl = serverurl;
export const noteid = urlpath ? window.location.pathname.slice(urlpath.length + 1, window.location.pathname.length).split('/')[1] : window.location.pathname.split('/')[1];
export const noteurl = `${serverurl}/${noteid}`;
export const version = '0.5.0';
|
Remove duplicate slashes from category name.
|
<?php
namespace FluxBB\Actions;
use FluxBB\Core\Action;
use FluxBB\Models\CategoryRepository;
class ViewCategory extends Action
{
protected $categories;
public function __construct(CategoryRepository $repository)
{
$this->categories = $repository;
}
protected function run()
{
$slug = $this->request->get('slug');
$slug = preg_replace('/\/+/', '/', '/'.$slug.'/');
$category = $this->categories->findBySlug($slug);
$this->data['category'] = $category;
$this->data['categories'] = $this->categories->getByParent($slug);
$this->data['conversations'] = $this->categories->getConversationsIn($category);
}
}
|
<?php
namespace FluxBB\Actions;
use FluxBB\Core\Action;
use FluxBB\Models\CategoryRepository;
use Illuminate\Support\Str;
class ViewCategory extends Action
{
protected $categories;
public function __construct(CategoryRepository $repository)
{
$this->categories = $repository;
}
protected function run()
{
$slug = $this->request->get('slug');
$slug = '/'.Str::finish(trim($slug, '/'), '/');
$category = $this->categories->findBySlug($slug);
$this->data['category'] = $category;
$this->data['categories'] = $this->categories->getByParent($slug);
$this->data['conversations'] = $this->categories->getConversationsIn($category);
}
}
|
Add Aria checked attribute binding
|
import Component from '@ember/component';
import { computed } from '@ember/object';
import { isEqual } from '@ember/utils';
import { run } from '@ember/runloop';
export default Component.extend({
tagName: 'input',
type: 'radio',
// value - required
// groupValue - required
// autofocus - boolean
// disabled - optional
// name - optional
// required - optional
// radioClass - string
// radioId - string
// tabindex - number
// ariaLabelledby - string
// ariaDescribedby - string
defaultLayout: null, // ie8 support
attributeBindings: [
'autofocus',
'checked',
'disabled',
'name',
'required',
'tabindex',
'type',
'value',
'ariaLabelledby:aria-labelledby',
'ariaDescribedby:aria-describedby',
'checked:aria-checked'
],
checked: computed('groupValue', 'value', function() {
return isEqual(this.get('groupValue'), this.get('value'));
}).readOnly(),
sendChangedAction() {
this.sendAction('changed', this.get('value'));
},
change() {
let value = this.get('value');
let groupValue = this.get('groupValue');
if (groupValue !== value) {
this.set('groupValue', value); // violates DDAU
run.once(this, 'sendChangedAction');
}
}
});
|
import Component from '@ember/component';
import { computed } from '@ember/object';
import { isEqual } from '@ember/utils';
import { run } from '@ember/runloop';
export default Component.extend({
tagName: 'input',
type: 'radio',
// value - required
// groupValue - required
// autofocus - boolean
// disabled - optional
// name - optional
// required - optional
// radioClass - string
// radioId - string
// tabindex - number
// ariaLabelledby - string
// ariaDescribedby - string
defaultLayout: null, // ie8 support
attributeBindings: [
'autofocus',
'checked',
'disabled',
'name',
'required',
'tabindex',
'type',
'value',
'ariaLabelledby:aria-labelledby',
'ariaDescribedby:aria-describedby'
],
checked: computed('groupValue', 'value', function() {
return isEqual(this.get('groupValue'), this.get('value'));
}).readOnly(),
sendChangedAction() {
this.sendAction('changed', this.get('value'));
},
change() {
let value = this.get('value');
let groupValue = this.get('groupValue');
if (groupValue !== value) {
this.set('groupValue', value); // violates DDAU
run.once(this, 'sendChangedAction');
}
}
});
|
Use Pattern::template() instead of string concatenation
|
<?php
namespace Coyote\Services\Parser\Parsers;
use Coyote\Repositories\Contracts\WordRepositoryInterface as WordRepository;
use TRegx\CleanRegex\Pattern;
use TRegx\SafeRegex\Exception\PregException;
use TRegx\SafeRegex\preg;
class Censore extends Parser implements ParserInterface
{
public function __construct(private WordRepository $word)
{
}
public function parse(string $text): string
{
static $result;
$text = $this->hashBlock($text, ['code', 'a']);
$text = $this->hashInline($text, 'img');
if ($result === null) {
$template = Pattern::template('(?<![\p{L}\p{N}_])@(?![\p{L}\p{N}_])', 'iu');
foreach ($this->word->allWords() as $word) {
$pattern = $template->mask($word->word, ['*' => '(\p{L}*?)']);
$result["$pattern"] = $word->replacement;
}
}
try {
$text = preg::replace(array_keys($result), array_values($result), $text);
} catch (PregException $ignored) {
}
$text = $this->unhash($text);
return $text;
}
}
|
<?php
namespace Coyote\Services\Parser\Parsers;
use Coyote\Repositories\Contracts\WordRepositoryInterface as WordRepository;
use TRegx\SafeRegex\Exception\PregException;
use TRegx\SafeRegex\preg;
class Censore extends Parser implements ParserInterface
{
public function __construct(private WordRepository $word)
{
}
public function parse(string $text): string
{
static $result;
$text = $this->hashBlock($text, ['code', 'a']);
$text = $this->hashInline($text, 'img');
if ($result === null) {
$result = $this->word->allWords();
}
$words = [];
foreach ($result as $row) {
$word = '#(?<![\p{L}\p{N}_])' . str_replace('\*', '(\p{L}*?)', preg_quote($row->word)) . '(?![\p{L}\p{N}_])#iu';
$words[$word] = $row->replacement;
}
try {
$text = preg::replace(array_keys($words), array_values($words), $text);
} catch (PregException $ignored) {
}
$text = $this->unhash($text);
return $text;
}
}
|
Use equals instead of equalsIgnoreCase
Co-authored-by: Jesse Glick <f03f7b035106bba3da9b565be6f0115dc0d88f87@cloudbees.com>
|
package org.jenkins.tools.test.hook;
import hudson.model.UpdateSite;
import hudson.util.VersionNumber;
import java.util.Map;
public class WorkflowCpsHook extends AbstractMultiParentHook {
@Override
protected String getParentFolder() {
return "workflow-cps-plugin";
}
@Override
protected String getParentProjectName() {
return "workflow-cps-parent";
}
@Override
protected String getPluginFolderName(UpdateSite.Plugin currentPlugin){
return "plugin";
}
@Override
public boolean check(Map<String, Object> info) {
return isMultiModuleVersionOfWorkflowCps(info);
}
public static boolean isMultiModuleVersionOfWorkflowCps(Map<String, Object> info) {
UpdateSite.Plugin plugin = info.get("plugin") != null ? (UpdateSite.Plugin) info.get("plugin") : null;
if (plugin != null && plugin.name.equals("workflow-cps") && plugin.version != null) {
VersionNumber pluginVersion = new VersionNumber(plugin.version);
// 2803 was the final release before it became a multi-module project.
// The history of groovy-cps history was merged into the repo, so the first multi-module release will be a little over 3500.
VersionNumber multiModuleSince = new VersionNumber("3500");
return pluginVersion.isNewerThan(multiModuleSince);
}
return false;
}
}
|
package org.jenkins.tools.test.hook;
import hudson.model.UpdateSite;
import hudson.util.VersionNumber;
import java.util.Map;
public class WorkflowCpsHook extends AbstractMultiParentHook {
@Override
protected String getParentFolder() {
return "workflow-cps-plugin";
}
@Override
protected String getParentProjectName() {
return "workflow-cps-parent";
}
@Override
protected String getPluginFolderName(UpdateSite.Plugin currentPlugin){
return "plugin";
}
@Override
public boolean check(Map<String, Object> info) {
return isMultiModuleVersionOfWorkflowCps(info);
}
public static boolean isMultiModuleVersionOfWorkflowCps(Map<String, Object> info) {
UpdateSite.Plugin plugin = info.get("plugin") != null ? (UpdateSite.Plugin) info.get("plugin") : null;
if (plugin != null && plugin.name.equalsIgnoreCase("workflow-cps") && plugin.version != null) {
VersionNumber pluginVersion = new VersionNumber(plugin.version);
// 2803 was the final release before it became a multi-module project.
// The history of groovy-cps history was merged into the repo, so the first multi-module release will be a little over 3500.
VersionNumber multiModuleSince = new VersionNumber("3500");
return pluginVersion.isNewerThan(multiModuleSince);
}
return false;
}
}
|
Change check for honey pot
|
<?php
require 'vendor/autoload.php';
require 'lib/readConfig.php';
// Read config file
$config = readConfig('config');
if ($config === FALSE) {
die('Config file not found');
}
// Start Slim
$app = new \Slim\Slim();
$app->post('/comments', function () use ($app) {
$data = $app->request()->post();
// Checking for the honey pot
if ((isset($data['company'])) && (!empty($data['company']))) {
return;
}
// Checking for mandatory fields
if ((!isset($data['name'])) ||
(!isset($data['email'])) ||
(!isset($data['message'])) ||
(!isset($data['post'])))
{
echo('Mandatory fields are missing.');
return;
}
$emailHash = md5(trim(strtolower($data['email'])));
$shellCommand = './new-comment.sh';
$shellCommand .= ' --name ' . escapeshellarg($data['name']);
$shellCommand .= ' --hash \'' . $emailHash . '\'';
$shellCommand .= ' --post ' . escapeshellarg($data['post']);
$shellCommand .= ' --message ' . escapeshellarg($data['message']);
if (isset($data['url'])) {
$shellCommand .= ' --url ' . escapeshellarg($data['url']);
}
exec($shellCommand, $output);
});
$app->run();
?>
|
<?php
require 'vendor/autoload.php';
require 'lib/readConfig.php';
// Read config file
$config = readConfig('config');
if ($config === FALSE) {
die('Config file not found');
}
// Start Slim
$app = new \Slim\Slim();
$app->post('/comments', function () use ($app) {
$data = $app->request()->post();
// We're looking for the honey pot field and testing mandatory fields
if ((isset($data['company'])) ||
(!isset($data['name'])) ||
(!isset($data['email'])) ||
(!isset($data['message'])) ||
(!isset($data['post'])))
{
echo('Aborting...');
return;
}
$emailHash = md5(trim(strtolower($data['email'])));
$shellCommand = './new-comment.sh';
$shellCommand .= ' --name ' . escapeshellarg($data['name']);
$shellCommand .= ' --hash \'' . $emailHash . '\'';
$shellCommand .= ' --post ' . escapeshellarg($data['post']);
$shellCommand .= ' --message ' . escapeshellarg($data['message']);
if (isset($data['url'])) {
$shellCommand .= ' --url ' . escapeshellarg($data['url']);
}
exec($shellCommand, $output);
});
$app->run();
?>
|
Fix permissions for dev env.
|
<?php
use Symfony\Component\HttpFoundation\Request;
// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);
// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
|| isset($_SERVER['HTTP_X_FORWARDED_FOR'])
|| !in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', 'fe80::1', '::1'))
) {
header('HTTP/1.0 403 Forbidden');
exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}
$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
require_once __DIR__.'/../app/AppKernel.php';
$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
Request::enableHttpMethodParameterOverride();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
|
<?php
use Symfony\Component\HttpFoundation\Request;
// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
umask(0000);
// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
|| isset($_SERVER['HTTP_X_FORWARDED_FOR'])
|| !in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', 'fe80::1', '::1'))
) {
header('HTTP/1.0 403 Forbidden');
exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}
$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
require_once __DIR__.'/../app/AppKernel.php';
$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
Request::enableHttpMethodParameterOverride();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
|
Resolve bug with twitter authorization.
|
package org.kefirsf.tk;
import twitter4j.Twitter;
/**
* Utilities for twitter.
* @author Vitalii Samolovskikh aka Kefir
*/
public final class TwitterUtils {
public static boolean validate(Twitter twitter){
boolean flag = false;
if(twitter!=null){
try {
twitter.verifyCredentials();
flag = true;
} catch (Throwable e) {
// Nothing!
}
}
return flag;
}
/**
* Prevent class initialization.
*/
private TwitterUtils() {
}
}
|
package org.kefirsf.tk;
import twitter4j.Twitter;
import twitter4j.TwitterException;
/**
* Utilities for twitter.
* @author Vitalii Samolovskikh aka Kefir
*/
public final class TwitterUtils {
public static boolean validate(Twitter twitter){
boolean flag = false;
if(twitter!=null){
try {
twitter.verifyCredentials();
flag = true;
} catch (TwitterException e) {
// Nothing!
}
}
return flag;
}
/**
* Prevent class initialization.
*/
private TwitterUtils() {
}
}
|
Change to make metaclass clearer
|
from fields import FieldBase
class Model(object):
class __metaclass__(type):
def __init__(cls, name, bases, attrs):
cls._fields = {}
for name, value in attrs.items():
if isinstance(value, FieldBase):
cls._fields[name] = value
def __init__(self, data):
"""Create an instance of the model subclass. The constructor should
be passed a dictionary of data to provide values for its fields.
For each field defined on the class (and stored in the _fields
property by the metaclass), a property is created on the instance
which contains the converted value from the source data.
"""
for name, field in self._fields.items():
key = field.source or name
field.populate(data.get(key))
value = field.to_python()
setattr(self, name, value)
self._data = data
|
from fields import FieldBase
class Model(object):
class __metaclass__(type):
def __init__(cls, name, bases, attrs):
fields = {}
for name, value in attrs.items():
if isinstance(value, FieldBase):
fields[name] = value
setattr(cls, '_fields', fields)
def __init__(self, data):
"""Create an instance of the model subclass. The constructor should
be passed a dictionary of data to provide values for its fields.
For each field defined on the class (and stored in the _fields
property by the metaclass), a property is created on the instance
which contains the converted value from the source data.
"""
for name, field in self._fields.items():
key = field.source or name
field.populate(data.get(key))
value = field.to_python()
setattr(self, name, value)
self._data = data
|
Rename cmd flag root to root-url for integrated tests
|
# coding: utf-8
"""Pytest config."""
import os
import sys
import pytest
from kiteconnect import KiteConnect
sys.path.append(os.path.join(os.path.dirname(__file__), '../helpers'))
def pytest_addoption(parser):
"""Add available args."""
parser.addoption("--api-key", action="store", default="Api key")
parser.addoption("--access-token", action="store", default="Access token")
parser.addoption("--root-url", action="store", default="")
def pytest_generate_tests(metafunc):
"""This is called for every test. Only get/set command line arguments. If the argument is specified in the list of test "fixturenames"."""
access_token = metafunc.config.option.access_token
api_key = metafunc.config.option.api_key
root_url = metafunc.config.option.root_url
if "access_token" in metafunc.fixturenames and access_token is not None:
metafunc.parametrize("access_token", [access_token])
if "api_key" in metafunc.fixturenames and api_key is not None:
metafunc.parametrize("api_key", [api_key])
if "root_url" in metafunc.fixturenames and root_url is not None:
metafunc.parametrize("root_url", [root_url])
@pytest.fixture()
def kiteconnect(api_key, access_token, root_url):
"""Init Kite connect object."""
return KiteConnect(api_key=api_key, access_token=access_token, root=root_url or None)
|
# coding: utf-8
"""Pytest config."""
import os
import sys
import pytest
from kiteconnect import KiteConnect
sys.path.append(os.path.join(os.path.dirname(__file__), '../helpers'))
def pytest_addoption(parser):
"""Add available args."""
parser.addoption("--api-key", action="store", default="Api key")
parser.addoption("--access-token", action="store", default="Access token")
parser.addoption("--root", action="store", default="")
def pytest_generate_tests(metafunc):
"""This is called for every test. Only get/set command line arguments. If the argument is specified in the list of test "fixturenames"."""
access_token = metafunc.config.option.access_token
api_key = metafunc.config.option.api_key
root = metafunc.config.option.root
if "access_token" in metafunc.fixturenames and access_token is not None:
metafunc.parametrize("access_token", [access_token])
if "api_key" in metafunc.fixturenames and api_key is not None:
metafunc.parametrize("api_key", [api_key])
if "root" in metafunc.fixturenames and root is not None:
metafunc.parametrize("root", [root])
@pytest.fixture()
def kiteconnect(api_key, access_token, root):
"""Init Kite connect object."""
return KiteConnect(api_key=api_key, access_token=access_token, root=root or None)
|
Remove app.debug as we do not use it any more.
Change-Id: I61497ae95dd304e60240f8ac731e63950351782f
Closes-Bug: #1583663
|
# 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
from oslo_log import log
from kuryr import app
from kuryr.common import config
from kuryr import controllers
config.init(sys.argv[1:])
controllers.neutron_client()
controllers.check_for_neutron_ext_support()
controllers.check_for_neutron_ext_tag()
log.setup(config.CONF, 'Kuryr')
def start():
port = int(config.CONF.kuryr_uri.split(':')[-1])
app.run("0.0.0.0", port)
if __name__ == '__main__':
start()
|
# 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
from oslo_log import log
from kuryr import app
from kuryr.common import config
from kuryr import controllers
config.init(sys.argv[1:])
controllers.neutron_client()
controllers.check_for_neutron_ext_support()
controllers.check_for_neutron_ext_tag()
app.debug = config.CONF.debug
log.setup(config.CONF, 'Kuryr')
def start():
port = int(config.CONF.kuryr_uri.split(':')[-1])
app.run("0.0.0.0", port)
if __name__ == '__main__':
start()
|
Fix: Use the raw GitHub URL for old blacklist
|
'use strict';
var https = require('https');
var concat = require('concat-stream');
var url = 'https://raw.githubusercontent.com/gulpjs/plugins/master/src/blackList.json';
function collect(stream, cb) {
stream.on('error', cb);
stream.pipe(concat(onSuccess));
function onSuccess(result) {
cb(null, result);
}
}
function parse(str, cb) {
try {
cb(null, JSON.parse(str));
} catch (err) {
/* istanbul ignore next */
cb(new Error('Invalid Blacklist JSON.'));
}
}
// TODO: Test this impl
function getBlacklist(cb) {
https.get(url, onRequest);
function onRequest(res) {
/* istanbul ignore if */
if (res.statusCode !== 200) {
// TODO: Test different status codes
return cb(new Error('Request failed. Status Code: ' + res.statusCode));
}
res.setEncoding('utf8');
collect(res, onCollect);
}
function onCollect(err, result) {
/* istanbul ignore if */
if (err) {
return cb(err);
}
parse(result, onParse);
}
function onParse(err, blacklist) {
/* istanbul ignore if */
if (err) {
return cb(err);
}
cb(null, blacklist);
}
}
module.exports = getBlacklist;
|
'use strict';
var https = require('https');
var concat = require('concat-stream');
var url = 'https://gulpjs.com/plugins/blackList.json';
function collect(stream, cb) {
stream.on('error', cb);
stream.pipe(concat(onSuccess));
function onSuccess(result) {
cb(null, result);
}
}
function parse(str, cb) {
try {
cb(null, JSON.parse(str));
} catch (err) {
/* istanbul ignore next */
cb(new Error('Invalid Blacklist JSON.'));
}
}
// TODO: Test this impl
function getBlacklist(cb) {
https.get(url, onRequest);
function onRequest(res) {
/* istanbul ignore if */
if (res.statusCode !== 200) {
// TODO: Test different status codes
return cb(new Error('Request failed. Status Code: ' + res.statusCode));
}
res.setEncoding('utf8');
collect(res, onCollect);
}
function onCollect(err, result) {
/* istanbul ignore if */
if (err) {
return cb(err);
}
parse(result, onParse);
}
function onParse(err, blacklist) {
/* istanbul ignore if */
if (err) {
return cb(err);
}
cb(null, blacklist);
}
}
module.exports = getBlacklist;
|
Fix to the pressure sensor
|
# -*- coding: utf-8 -*-
import sys
from sense_hat import SenseHat
#add the project folder to pythpath
sys.path.append('../../')
from library.components.SensorModule import SensorModule as Sensor
from library.components.MetaData import MetaData as MetaData
class SensePressure(Sensor):
def __init__(self):
super(SensePressure, self).__init__()
tempMetaData = MetaData('Millibars')
tempMetaData.setValueCallback(self.getPressureValue)
tempMetaData.setUnitCallback(self.getPressureUnit)
self.addMetaData(tempMetaData)
def getPressureValue(self):
sense = SenseHat()
return str(sense.pressure)
def getPressureUnit(self):
return " Millibars"
def getMetaData(self):
return super(SensePressure, self).getMetaData()
|
# -*- coding: utf-8 -*-
import sys
from sense_hat import SenseHat
#add the project folder to pythpath
sys.path.append('../../')
from library.components.SensorModule import SensorModule as Sensor
from library.components.MetaData import MetaData as MetaData
class SensePressure(Sensor):
def __init__(self):
super(SensePressure, self).__init__()
tempMetaData = MetaData('millibars')
tempMetaData.setValueCallback(self.getPressureValue)
tempMetaData.setUnitCallback(self.getPressureUnit)
self.addMetaData(tempMetaData)
def getPressureValue(self):
sense = SenseHat()
return str(sense.pressure)
def getPressureUnit(self):
return " Millibars"
def getMetaData(self):
return super(SensePressure, self).getMetaData()
|
Use `version` not `platformVersion` for iOS appium config
|
// Test runner
var runTests = require('./affixing-header-specs'),
browsers = [
{browserName: 'chrome'},
{browserName: 'firefox'}
];
// var browserConfig = require('./helpers/browser-config');
if (process.env.TRAVIS_JOB_NUMBER) {
browsers.push(
{browserName: 'safari', version: 7},
{browserName: 'ipad', version: '8.2', appiumVersion: '1.3.7'},
{browserName: 'iphone', version: '8.2', appiumVersion: '1.3.7'},
{browserName: 'chrome', platformVersion: '4.0', platformName: 'Android', appiumVersion: '1.3.7', deviceName: 'Android Emulator'},
{browserName: 'internet explorer'}
);
}
browsers.forEach(function(browser) {
runTests(browser);
});
|
// Test runner
var runTests = require('./affixing-header-specs'),
browsers = [
{browserName: 'chrome'},
{browserName: 'firefox'}
];
// var browserConfig = require('./helpers/browser-config');
if (process.env.TRAVIS_JOB_NUMBER) {
browsers.push(
{browserName: 'safari', version: 7},
{browserName: 'ipad', platformVersion: '8.2', appiumVersion: '1.3.7'},
{browserName: 'iphone', platformVersion: '8.2', appiumVersion: '1.3.7'},
{browserName: 'chrome', platformVersion: '4.0', platformName: 'Android', appiumVersion: '1.3.7', deviceName: 'Android Emulator'},
{browserName: 'internet explorer'}
);
}
browsers.forEach(function(browser) {
runTests(browser);
});
|
Make internal property not writable
|
'use strict';
var aFrom = require('es5-ext/array/from')
, remove = require('es5-ext/array/#/remove')
, value = require('es5-ext/object/valid-object')
, d = require('d')
, emit = require('./').methods.emit
, defineProperty = Object.defineProperty
, hasOwnProperty = Object.prototype.hasOwnProperty
, getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
module.exports = function (e1, e2) {
var pipes, pipe, desc;
(value(e1) && value(e2));
if (typeof e1.emit !== 'function') {
throw new TypeError(e1 + ' is not emitter');
}
pipe = {
close: function () { remove.call(pipes, e2); }
};
if (hasOwnProperty.call(e1, '__eePipes__')) {
(pipes = e1.__eePipes__).push(e2);
return pipe;
}
defineProperty(e1, '__eePipes__', d('c', pipes = [e2]));
desc = getOwnPropertyDescriptor(e1, 'emit');
delete desc.get;
delete desc.set;
desc.value = function () {
var i, emitter, data = aFrom(pipes);
emit.apply(this, arguments);
for (i = 0; (emitter = data[i]); ++i) emit.apply(emitter, arguments);
};
defineProperty(e1, 'emit', desc);
return pipe;
};
|
'use strict';
var aFrom = require('es5-ext/array/from')
, remove = require('es5-ext/array/#/remove')
, value = require('es5-ext/object/valid-object')
, d = require('d')
, emit = require('./').methods.emit
, defineProperty = Object.defineProperty
, hasOwnProperty = Object.prototype.hasOwnProperty
, getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
module.exports = function (e1, e2) {
var pipes, pipe, desc;
(value(e1) && value(e2));
if (typeof e1.emit !== 'function') {
throw new TypeError(e1 + ' is not emitter');
}
pipe = {
close: function () { remove.call(pipes, e2); }
};
if (hasOwnProperty.call(e1, '__eePipes__')) {
(pipes = e1.__eePipes__).push(e2);
return pipe;
}
defineProperty(e1, '__eePipes__', d(pipes = [e2]));
desc = getOwnPropertyDescriptor(e1, 'emit');
delete desc.get;
delete desc.set;
desc.value = function () {
var i, emitter, data = aFrom(pipes);
emit.apply(this, arguments);
for (i = 0; (emitter = data[i]); ++i) emit.apply(emitter, arguments);
};
defineProperty(e1, 'emit', desc);
return pipe;
};
|
Increase form length limits for news item's slug, title, and image URL path
|
"""
byceps.blueprints.news_admin.forms
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import re
from wtforms import StringField, TextAreaField
from wtforms.validators import InputRequired, Length, Optional, Regexp
from ...util.l10n import LocalizedForm
SLUG_REGEX = re.compile('^[a-z0-9-]+$')
class ChannelCreateForm(LocalizedForm):
channel_id = StringField('ID', validators=[Length(min=1, max=40)])
url_prefix = StringField('URL-Präfix', [InputRequired(), Length(max=80)])
class ItemCreateForm(LocalizedForm):
slug = StringField('Slug', [InputRequired(), Length(max=100), Regexp(SLUG_REGEX, message='Nur Kleinbuchstaben, Ziffern und Bindestrich sind erlaubt.')])
title = StringField('Titel', [InputRequired(), Length(max=100)])
body = TextAreaField('Text', [InputRequired()])
image_url_path = StringField('Bild-URL-Pfad', [Optional(), Length(max=100)])
class ItemUpdateForm(ItemCreateForm):
pass
|
"""
byceps.blueprints.news_admin.forms
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import re
from wtforms import StringField, TextAreaField
from wtforms.validators import InputRequired, Length, Optional, Regexp
from ...util.l10n import LocalizedForm
SLUG_REGEX = re.compile('^[a-z0-9-]+$')
class ChannelCreateForm(LocalizedForm):
channel_id = StringField('ID', validators=[Length(min=1, max=40)])
url_prefix = StringField('URL-Präfix', [InputRequired(), Length(max=80)])
class ItemCreateForm(LocalizedForm):
slug = StringField('Slug', [InputRequired(), Length(max=80), Regexp(SLUG_REGEX, message='Nur Kleinbuchstaben, Ziffern und Bindestrich sind erlaubt.')])
title = StringField('Titel', [InputRequired(), Length(max=80)])
body = TextAreaField('Text', [InputRequired()])
image_url_path = StringField('Bild-URL-Pfad', [Optional(), Length(max=80)])
class ItemUpdateForm(ItemCreateForm):
pass
|
Reduce function, to stop nested lists
|
if 'logger' not in globals():
import logging
logger = logging.getLogger('Main')
logger.setLevel(logging.DEBUG)
logger.propagate = False
if not logger.handlers:
hdlr = logging.StreamHandler()
hdlr.setLevel(logging.DEBUG)
formatter = logging.Formatter(
# '%(asctime)s - '
'%(name)s - '
'%(levelname)s '
'%(filename)s:%(lineno)d: '
'%(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
def reduce(obj, can_return_single=False):
"""
Flattens nested lists, like so;
>>> reduce([[[[[[[None]]]]]]])
None
"""
if type(obj) == list and len(obj) == 1 and type(obj[0]) == list:
return reduce(obj[0])
elif type(obj) == list and len(obj) == 1 and can_return_single:
return obj[0]
else:
return obj
|
if 'logger' not in globals():
import logging
logger = logging.getLogger('Main')
logger.setLevel(logging.DEBUG)
logger.propagate = False
if not logger.handlers:
hdlr = logging.StreamHandler()
hdlr.setLevel(logging.DEBUG)
formatter = logging.Formatter(
# '%(asctime)s - '
'%(name)s - '
'%(levelname)s '
'%(filename)s:%(lineno)d: '
'%(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
|
Update
- cannot open 2 session
|
const assert = require('assert');
const { crypto, config } = require('./config');
describe("WebCrypto", () => {
it("get random values", () => {
var buf = new Uint8Array(16);
var check = new Buffer(buf).toString("base64");
assert.notEqual(new Buffer(crypto.getRandomValues(buf)).toString("base64"), check, "Has no random values");
})
it("get random values with large buffer", () => {
var buf = new Uint8Array(65600);
assert.throws(() => {
crypto.getRandomValues(buf);
}, Error);
})
it("reset", (done) => {
const currentHandle = crypto.session.handle.toString("hex");
crypto.reset()
.then(() => {
crypto.login(config.pin);
const newHandle = crypto.session.handle.toString("hex");
assert(currentHandle !== newHandle, true, "handle of session wasn't changed");
})
.then(done, done);
})
})
|
const assert = require('assert');
const { crypto, config } = require('./config');
describe("WebCrypto", () => {
it("get random values", () => {
var buf = new Uint8Array(16);
var check = new Buffer(buf).toString("base64");
assert.notEqual(new Buffer(crypto.getRandomValues(buf)).toString("base64"), check, "Has no random values");
})
it("get random values with large buffer", () => {
var buf = new Uint8Array(65600);
assert.throws(() => {
crypto.getRandomValues(buf);
}, Error);
})
it("reset", (done) => {
var WebCrypto = require("../").WebCrypto;
const crypto = new WebCrypto(config);
const currentHandle = crypto.session.handle.toString("hex");
crypto.reset()
.then(() => {
const newHandle = crypto.session.handle.toString("hex");
assert(currentHandle !== newHandle, true, "handle of session wasn't changed");
})
.then(done, done);
})
})
|
Fix bad property name in Form_Filter.
|
<?php
/**
* Abstract class to define form element filters
* @author Jon Johnson <jon.johnson@ucsf.edu>
* @license http://jazzee.org/license.txt
* @package foundation
* @subpackage forms
*/
abstract class Form_Filter{
/**
* Holds the element we are filtering
* @var Form_Element
*/
protected $e;
/**
* Holds the rule set for processing
* @var mixed
*/
protected $ruleSet;
/**
* Constructor
* @param Form_Element $e the element we are validating
*/
public function __construct(Form_Element $e, $ruleSet = null){
$this->e = $e;
$this->ruleSet = $ruleSet;
}
/**
* Filter the input
* @param mixed $value
* @return mixed @value
*/
abstract public function filter($value);
}
?>
|
<?php
/**
* Abstract class to define form element filters
* @author Jon Johnson <jon.johnson@ucsf.edu>
* @license http://jazzee.org/license.txt
* @package foundation
* @subpackage forms
*/
abstract class Form_Filter{
/**
* Holds the element we are filtering
* @var Form_Element
*/
protected $e;
/**
* Holds the rule set for processing
* @var mixed
*/
protected $rulesSet;
/**
* Constructor
* @param Form_Element $e the element we are validating
*/
public function __construct(Form_Element $e, $ruleSet = null){
$this->e = $e;
$this->ruleSet = $ruleSet;
}
/**
* Filter the input
* @param mixed $value
* @return mixed @value
*/
abstract public function filter($value);
}
?>
|
Change Elron max time to 10min
|
const got = require('got');
const cache = require('../utils/cache.js');
const time = require('../utils/time.js');
// Get trips for stop.
async function getTrips(id) {
const now = time.getSeconds();
const trips = JSON.parse((await got(`http://elron.ee/api/v1/stop?stop=${encodeURIComponent(id)}`)).body).data;
if (!trips) throw new Error("Provider 'Elron' is not returning data");
if (trips.text) throw new Error(trips.text);
// Show not arrived trips until 10 minutes of being late.
return trips.filter((trip) => !trip.tegelik_aeg).map((trip) => ({
time: time.toSeconds(trip.plaaniline_aeg),
countdown: time.toSeconds(trip.plaaniline_aeg) - now,
name: trip.reis,
destination: trip.liin,
type: 'train',
live: false,
provider: 'elron'
})).filter((trip) => now - trip.time < 600).slice(0, 15);
}
module.exports = {
getTrips
};
|
const got = require('got');
const cache = require('../utils/cache.js');
const time = require('../utils/time.js');
// Get trips for stop.
async function getTrips(id) {
const now = time.getSeconds();
const trips = JSON.parse((await got(`http://elron.ee/api/v1/stop?stop=${encodeURIComponent(id)}`)).body).data;
if (!trips) throw new Error("Provider 'Elron' is not returning data");
if (trips.text) throw new Error(trips.text);
// Show not arrived trips until 30 minutes of being late.
return trips.filter((trip) => !trip.tegelik_aeg).map((trip) => ({
time: time.toSeconds(trip.plaaniline_aeg),
countdown: time.toSeconds(trip.plaaniline_aeg) - now,
name: trip.reis,
destination: trip.liin,
type: 'train',
live: false,
provider: 'elron'
})).filter((trip) => now - trip.time < 1800).slice(0, 15);
}
module.exports = {
getTrips
};
|
Make methods abstract to force the dev to implement these correctly (it won't work otherwise anyways).
|
/*
* Android SDK for Piwik
*
* @link https://github.com/piwik/piwik-android-sdk
* @license https://github.com/piwik/piwik-sdk-android/blob/master/LICENSE BSD-3 Clause
*/
package org.piwik.sdk;
import android.app.Application;
import android.util.Log;
import java.net.MalformedURLException;
public abstract class PiwikApplication extends Application {
Tracker piwikTracker;
public Piwik getPiwik(){
return Piwik.getInstance(this);
}
public Tracker getTracker() {
if (piwikTracker != null) {
return piwikTracker;
}
try {
piwikTracker = getPiwik().newTracker(getTrackerUrl(), getSiteId(), getAuthToken());
} catch (MalformedURLException e) {
Log.i(Tracker.LOGGER_TAG, getTrackerUrl());
Log.w(Tracker.LOGGER_TAG, "url is malformed", e);
return null;
}
return piwikTracker;
}
public abstract String getTrackerUrl();
public abstract Integer getSiteId();
@Deprecated
public String getAuthToken() {
return null;
}
}
|
/*
* Android SDK for Piwik
*
* @link https://github.com/piwik/piwik-android-sdk
* @license https://github.com/piwik/piwik-sdk-android/blob/master/LICENSE BSD-3 Clause
*/
package org.piwik.sdk;
import android.app.Application;
import android.util.Log;
import java.net.MalformedURLException;
public abstract class PiwikApplication extends Application {
Tracker piwikTracker;
public Piwik getPiwik(){
return Piwik.getInstance(this);
}
public Tracker getTracker() {
if (piwikTracker != null) {
return piwikTracker;
}
try {
piwikTracker = getPiwik().newTracker(getTrackerUrl(), getSiteId(), getAuthToken());
} catch (MalformedURLException e) {
Log.i(Tracker.LOGGER_TAG, getTrackerUrl());
Log.w(Tracker.LOGGER_TAG, "url is malformed", e);
return null;
}
return piwikTracker;
}
public String getTrackerUrl() {
return "";
}
public Integer getSiteId() {
return 1;
}
@Deprecated
public String getAuthToken() {
return null;
}
}
|
Rename headers and add doc comment
|
// Copyright 2017 Mathew Robinson <mrobinson@praelatus.io>. All rights reserved.
// Use of this source code is governed by the AGPLv3 license that can be found in
// the LICENSE file.
// Package middleware contains the HTTP middleware used in the api as
// well as utility functions for interacting with them
package middleware
import (
"net/http"
"github.com/praelatus/praelatus/repo"
)
// Cache is the global SessionCache
var Cache repo.Cache
// ContentHeaders will set the content-type header for the API to application/json
func ContentHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path[len("/api"):] == "/api" {
w.Header().Set("Content-Type", "application/json")
}
next.ServeHTTP(w, r)
})
}
// LoadMw will wrap the given http.Handler in the DefaultMiddleware
func LoadMw(handler http.Handler) http.Handler {
h := handler
for _, m := range DefaultMiddleware {
h = m(h)
}
return h
}
// DefaultMiddleware is the default middleware stack for Praelatus
var DefaultMiddleware = []func(http.Handler) http.Handler{
ContentHeaders,
Logger,
}
|
// Copyright 2017 Mathew Robinson <mrobinson@praelatus.io>. All rights reserved.
// Use of this source code is governed by the AGPLv3 license that can be found in
// the LICENSE file.
// Package middleware contains the HTTP middleware used in the api as
// well as utility functions for interacting with them
package middleware
import (
"net/http"
"github.com/praelatus/praelatus/repo"
)
// Cache is the global SessionCache
var Cache repo.Cache
func headers(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
h.ServeHTTP(w, r)
})
}
// LoadMw will wrap the given http.Handler in the DefaultMiddleware
func LoadMw(handler http.Handler) http.Handler {
h := handler
for _, m := range DefaultMiddleware {
h = m(h)
}
return h
}
// DefaultMiddleware is the default middleware stack for Praelatus
var DefaultMiddleware = []func(http.Handler) http.Handler{
headers,
Logger,
}
|
Use json by default for js library
|
// general action
// f_ok(data, textStatus, XMLHttpRequest)
// f_err(XMLHttpRequest,textStatus, errorThrown)
function general_action( type, url, params, f_ok, f_err ) {
$.ajax({
type: type,
url: url+'.json',
data: params,
success: f_ok,
error: f_err
});
}
function create(url, params, f_ok, f_err) {
return general_action( "POST", url, params, f_ok, f_err);
}
function list(url, params, f_ok, f_err) {
return general_action( "GET", url, params, f_ok, f_err);
}
function show(url, params, f_ok, f_err) {
return general_action( "GET", url, params, f_ok, f_err);
}
function update(url, params, f_ok, f_err) {
return general_action( "PUT", url, params, f_ok, f_err);
}
function rest_delete(url, params, f_ok, f_err) {
return general_action( "DELETE", url, params, f_ok, f_err);
}
|
// general action
// f_ok(data, textStatus, XMLHttpRequest)
// f_err(XMLHttpRequest,textStatus, errorThrown)
function general_action( type, url, params, f_ok, f_err ) {
$.ajax({
type: type,
url: url,
data: params,
success: f_ok,
error: f_err
});
}
function create(url, params, f_ok, f_err) {
return general_action( "POST", url, params, f_ok, f_err);
}
function list(url, params, f_ok, f_err) {
return general_action( "GET", url, params, f_ok, f_err);
}
function show(url, params, f_ok, f_err) {
return general_action( "GET", url, params, f_ok, f_err);
}
function update(url, params, f_ok, f_err) {
return general_action( "PUT", url, params, f_ok, f_err);
}
function rest_delete(url, params, f_ok, f_err) {
return general_action( "DELETE", url, params, f_ok, f_err);
}
|
Remove invalid proxy config from search facade
Change-Id: I0cc7b4bab426a354524fb49f3670370142e8e9be
|
package com.cgi.eoss.ftep.search;
import com.cgi.eoss.ftep.catalogue.CatalogueConfig;
import com.cgi.eoss.ftep.persistence.PersistenceConfig;
import com.cgi.eoss.ftep.search.api.SearchFacade;
import com.cgi.eoss.ftep.search.api.SearchProvider;
import okhttp3.OkHttpClient;
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import java.util.Collection;
@Configuration
@Import({
PropertyPlaceholderAutoConfiguration.class,
CatalogueConfig.class,
PersistenceConfig.class
})
@ComponentScan(basePackageClasses = SearchConfig.class)
public class SearchConfig {
@Bean
public SearchFacade searchFacade(Collection<SearchProvider> searchProviders) {
return new SearchFacade(searchProviders);
}
@Bean
public OkHttpClient httpClient() {
return new OkHttpClient.Builder().build();
}
}
|
package com.cgi.eoss.ftep.search;
import com.cgi.eoss.ftep.catalogue.CatalogueConfig;
import com.cgi.eoss.ftep.persistence.PersistenceConfig;
import com.cgi.eoss.ftep.search.api.SearchFacade;
import com.cgi.eoss.ftep.search.api.SearchProvider;
import okhttp3.OkHttpClient;
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.Collection;
@Configuration
@Import({
PropertyPlaceholderAutoConfiguration.class,
CatalogueConfig.class,
PersistenceConfig.class
})
@ComponentScan(basePackageClasses = SearchConfig.class)
public class SearchConfig {
@Bean
public SearchFacade searchFacade(Collection<SearchProvider> searchProviders) {
return new SearchFacade(searchProviders);
}
@Bean
public OkHttpClient httpClient() {
return new OkHttpClient.Builder()
.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.logica.com", 80)))
.build();
}
}
|
Make TriggerEventWidgetComponent compatible with Ember 3.8
|
import Component from '@glimmer/component';
import { set } from '@ember/object';
import { keyResponder, onKey } from 'ember-keyboard';
// Use set(this) instead of tracked properties for Ember 3.8 compatibility.
@keyResponder({ activated: true })
export default class extends Component {
keyboardActivated = true;
keyDown = false;
keyDownWithMods = false;
keyPress = false;
keyUp = false;
@onKey('KeyA', { event: 'keydown' })
toggleKeyDown = () => set(this, 'keyDown', !this.keyDown);
@onKey('KeyA+cmd+shift', { event: 'keydown' })
toggleKeyDownWithMods = () =>
set(this, 'keyDownWithMods', !this.keyDownWithMods);
@onKey('KeyA', { event: 'keypress' })
toggleKeyPress = () => set(this, 'keyPress', !this.keyPress);
@onKey('KeyA', { event: 'keyup' })
toggleKeyUp = () => set(this, 'keyUp', !this.keyUp);
}
|
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { keyResponder, onKey } from 'ember-keyboard';
@keyResponder({ activated: true })
export default class extends Component {
@tracked keyboardActivated = true;
@tracked keyDown = false;
@tracked keyDownWithMods = false;
@tracked keyPress = false;
@tracked keyUp = false;
@onKey('KeyA', { event: 'keydown' })
toggleKeyDown = () => (this.keyDown = !this.keyDown);
@onKey('KeyA+cmd+shift', { event: 'keydown' })
toggleKeyDownWithMods = () => (this.keyDownWithMods = !this.keyDownWithMods);
@onKey('KeyA', { event: 'keypress' })
toggleKeyPress = () => (this.keyPress = !this.keyPress);
@onKey('KeyA', { event: 'keyup' })
toggleKeyUp = () => (this.keyUp = !this.keyUp);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.