text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Remove reference to log, as it's not set up correctly yet. | import os
import sys
from aqt import mw, QAction, QFileDialog
sys.path.append(os.path.join(os.path.dirname(__file__), "dist"))
from .anki.hook_vendor import HookVendor
from .anki.ui.action_vendor import ActionVendor
def anki_actions_init(window):
action_vendor = ActionVendor(window, QAction, lambda caption: QFileDialog.getExistingDirectory(caption=caption))
after_export_action_position = -2
window.form.menuCol.insertActions(window.form.menuCol.actions()[after_export_action_position],
action_vendor.actions())
def anki_init(window):
if not window:
return
HookVendor(window).setup_hooks()
anki_actions_init(window)
anki_init(mw)
"""
Warning:
Creation of collection has a side effect of changing current directory to ${collection_path}/collection.media
"""
| import os
import sys
from aqt import mw, QAction, QFileDialog
sys.path.append(os.path.join(os.path.dirname(__file__), "dist"))
from .anki.hook_vendor import HookVendor
from .anki.ui.action_vendor import ActionVendor
from .utils.log import setup_log
def anki_actions_init(window):
action_vendor = ActionVendor(window, QAction, lambda caption: QFileDialog.getExistingDirectory(caption=caption))
after_export_action_position = -2
window.form.menuCol.insertActions(window.form.menuCol.actions()[after_export_action_position],
action_vendor.actions())
def anki_init(window):
if not window:
return
HookVendor(window).setup_hooks()
anki_actions_init(window)
setup_log()
anki_init(mw)
"""
Warning:
Creation of collection has a side effect of changing current directory to ${collection_path}/collection.media
"""
|
Use builder to construct the source | package org.apidesign.demo.rubyjs.fromjava;
import com.oracle.truffle.api.source.Source;
import com.oracle.truffle.api.vm.PolyglotEngine;
import java.io.File;
import java.net.URL;
public final class Main {
private Main() {
}
public static void main(String[] args) throws Exception {
System.err.println("Setting up PolyglotEngine");
PolyglotEngine vm = PolyglotEngine.newBuilder().
build();
URL url = Main.class.getProtectionDomain().getCodeSource().getLocation();
File local = new File(url.toURI());
for (;;) {
File sieveInRuby = new File(local, "sieve.rb");
if (sieveInRuby.exists()) {
break;
}
local = local.getParentFile();
}
Source ruby = Source.newBuilder(new File(local, "sieve.rb")).build();
Source js = Source.newBuilder(new File(local, "sieve.js")).build();
vm.eval(ruby);
vm.eval(js);
}
}
| package org.apidesign.demo.rubyjs.fromjava;
import com.oracle.truffle.api.source.Source;
import com.oracle.truffle.api.vm.PolyglotEngine;
import java.io.File;
import java.net.URL;
public final class Main {
private Main() {
}
public static void main(String[] args) throws Exception {
System.err.println("Setting up PolyglotEngine");
PolyglotEngine vm = PolyglotEngine.newBuilder().
build();
URL url = Main.class.getProtectionDomain().getCodeSource().getLocation();
File local = new File(url.toURI());
for (;;) {
File sieveInRuby = new File(local, "sieve.rb");
if (sieveInRuby.exists()) {
break;
}
local = local.getParentFile();
}
Source ruby = Source.fromFileName(new File(local, "sieve.rb").getPath());
Source js = Source.fromFileName(new File(local, "sieve.js").getPath());
vm.eval(ruby);
vm.eval(js);
}
}
|
Set Sentry `site_id` tag only in site app mode | """
byceps.util.sentry
~~~~~~~~~~~~~~~~~~
Sentry_ integration
.. _Sentry: https://sentry.io/
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from flask import Flask
def configure_sentry_for_webapp(dsn: str, environment: str, app: Flask) -> None:
"""Initialize and configure the Sentry SDK for the Flask-based web
application (both in 'admin' and 'site' modes).
"""
import sentry_sdk
from sentry_sdk.integrations.flask import FlaskIntegration
sentry_sdk.init(
dsn=dsn, environment=environment, integrations=[FlaskIntegration()],
)
app_mode = app.config.get('APP_MODE')
sentry_sdk.set_tag('app_mode', app_mode)
if app_mode == 'site':
sentry_sdk.set_tag('site_id', app.config.get('SITE_ID'))
def configure_sentry_for_worker(dsn: str, environment: str) -> None:
"""Initialize and configure the Sentry SDK for the RQ worker."""
import sentry_sdk
from sentry_sdk.integrations.rq import RqIntegration
sentry_sdk.init(
dsn=dsn, environment=environment, integrations=[RqIntegration()],
)
sentry_sdk.set_tag('app_mode', 'worker')
| """
byceps.util.sentry
~~~~~~~~~~~~~~~~~~
Sentry_ integration
.. _Sentry: https://sentry.io/
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from flask import Flask
def configure_sentry_for_webapp(dsn: str, environment: str, app: Flask) -> None:
"""Initialize and configure the Sentry SDK for the Flask-based web
application (both in 'admin' and 'site' modes).
"""
import sentry_sdk
from sentry_sdk.integrations.flask import FlaskIntegration
sentry_sdk.init(
dsn=dsn, environment=environment, integrations=[FlaskIntegration()],
)
sentry_sdk.set_tag('app_mode', app.config.get('APP_MODE'))
sentry_sdk.set_tag('site_id', app.config.get('SITE_ID'))
def configure_sentry_for_worker(dsn: str, environment: str) -> None:
"""Initialize and configure the Sentry SDK for the RQ worker."""
import sentry_sdk
from sentry_sdk.integrations.rq import RqIntegration
sentry_sdk.init(
dsn=dsn, environment=environment, integrations=[RqIntegration()],
)
sentry_sdk.set_tag('app_mode', 'worker')
|
i18n: Add comment explaining why our use of legacy-context works. | /* @flow strict-local */
import { connect } from 'react-redux';
import React, { PureComponent } from 'react';
import { Text } from 'react-native';
import { IntlProvider } from 'react-intl';
import type { ChildrenArray, GlobalState } from '../types';
import { getSettings } from '../selectors';
import '../../vendor/intl/intl';
import messages from '../i18n/messages';
import '../i18n/locale';
type Props = {
locale: string,
children: ChildrenArray<*>,
};
class TranslationProvider extends PureComponent<Props> {
props: Props;
render() {
const { locale, children } = this.props;
return (
/* `IntlProvider` uses React's "legacy context API", deprecated since
* React 16.3, of which the docs say:
*
* ## Updating Context
*
* Don't do it.
*
* React has an API to update context, but it is fundamentally
* broken and you should not use it.
*
* To work around that, we set `key={locale}` to force the whole tree
* to rerender if the locale changes. Not cheap, but the locale
* changing is rare.
*/
<IntlProvider key={locale} locale={locale} textComponent={Text} messages={messages[locale]}>
{children}
</IntlProvider>
);
}
}
export default connect((state: GlobalState) => ({
locale: getSettings(state).locale,
}))(TranslationProvider);
| /* @flow strict-local */
import { connect } from 'react-redux';
import React, { PureComponent } from 'react';
import { Text } from 'react-native';
import { IntlProvider } from 'react-intl';
import type { ChildrenArray, GlobalState } from '../types';
import { getSettings } from '../selectors';
import '../../vendor/intl/intl';
import messages from '../i18n/messages';
import '../i18n/locale';
type Props = {
locale: string,
children: ChildrenArray<*>,
};
class TranslationProvider extends PureComponent<Props> {
props: Props;
render() {
const { locale, children } = this.props;
return (
<IntlProvider key={locale} locale={locale} textComponent={Text} messages={messages[locale]}>
{children}
</IntlProvider>
);
}
}
export default connect((state: GlobalState) => ({
locale: getSettings(state).locale,
}))(TranslationProvider);
|
Fix for display messages from User class. | <?php
/**
* Landing CMS
*
* A simple CMS for Landing Pages.
*
* @package Landing CMS
* @author Ilia Chernykh <landingcms@yahoo.com>
* @copyright 2017, Landing CMS (https://github.com/Elias-Black/Landing-CMS)
* @license https://opensource.org/licenses/LGPL-2.1 LGPL-2.1
* @version Release: 0.0.5
* @link https://github.com/Elias-Black/Landing-CMS
*/
// Connecting main classes
require_once('../_classes/index.php');
defined('CORE') OR die('403');
$data = isset($message) ? $message : array();
// Catching form submit
if( !empty($_POST) )
{
$data = User::updatePassword();
}
// Render form of changing password
$content = Utils::render(
'forms/password.php',
$data
);
// Printing page
echo Utils::renderIndex($content, $data);
| <?php
/**
* Landing CMS
*
* A simple CMS for Landing Pages.
*
* @package Landing CMS
* @author Ilia Chernykh <landingcms@yahoo.com>
* @copyright 2017, Landing CMS (https://github.com/Elias-Black/Landing-CMS)
* @license https://opensource.org/licenses/LGPL-2.1 LGPL-2.1
* @version Release: 0.0.5
* @link https://github.com/Elias-Black/Landing-CMS
*/
// Connecting main classes
require_once('../_classes/index.php');
defined('CORE') OR die('403');
$data = array();
// Catching form submit
if( !empty($_POST) )
{
$data = User::updatePassword();
}
// Render form of changing password
$content = Utils::render(
'forms/password.php',
$data
);
// Printing page
echo Utils::renderIndex($content, $data);
|
Use 'babel' Prettier parser instead of deprecated 'bablyon'.
As per warning when using jest-react-fela.
console.warn node_modules/prettier/index.js:7939
{ parser: "babylon" } is deprecated; we now treat it as { parser:
"babel" }. | import { format } from 'prettier'
import HTMLtoJSX from 'htmltojsx'
import { renderToString } from 'fela-tools'
import type { DOMRenderer } from '../../../flowtypes/DOMRenderer'
function formatCSS(css) {
return format(css, { parser: 'css', useTabs: false, tabWidth: 2 })
}
function formatHTML(html) {
const converter = new HTMLtoJSX({
createClass: false,
})
const jsx = converter.convert(html)
return format(jsx, { parser: 'babel' }).replace(/[\\"]/g, '')
}
export default function createSnapshotFactory(
createElement: Function,
render: Function,
defaultRenderer: Function,
defaultRendererProvider: Function,
defaultThemeProvider: Function
): Function {
return function createSnapshot(
component: any,
theme: Object = {},
renderer: DOMRenderer = defaultRenderer,
RendererProvider: Function = defaultRendererProvider,
ThemeProvider: Function = defaultThemeProvider
) {
const div = document.createElement('div')
// reset renderer to have a clean setup
renderer.clear()
render(
createElement(
RendererProvider,
{ renderer },
createElement(ThemeProvider, { theme }, component)
),
div
)
return `${formatCSS(renderToString(renderer))}\n\n${formatHTML(
div.innerHTML
)}`
}
}
| import { format } from 'prettier'
import HTMLtoJSX from 'htmltojsx'
import { renderToString } from 'fela-tools'
import type { DOMRenderer } from '../../../flowtypes/DOMRenderer'
function formatCSS(css) {
return format(css, { parser: 'css', useTabs: false, tabWidth: 2 })
}
function formatHTML(html) {
const converter = new HTMLtoJSX({
createClass: false,
})
const jsx = converter.convert(html)
return format(jsx, { parser: 'babylon' }).replace(/[\\"]/g, '')
}
export default function createSnapshotFactory(
createElement: Function,
render: Function,
defaultRenderer: Function,
defaultRendererProvider: Function,
defaultThemeProvider: Function
): Function {
return function createSnapshot(
component: any,
theme: Object = {},
renderer: DOMRenderer = defaultRenderer,
RendererProvider: Function = defaultRendererProvider,
ThemeProvider: Function = defaultThemeProvider
) {
const div = document.createElement('div')
// reset renderer to have a clean setup
renderer.clear()
render(
createElement(
RendererProvider,
{ renderer },
createElement(ThemeProvider, { theme }, component)
),
div
)
return `${formatCSS(renderToString(renderer))}\n\n${formatHTML(
div.innerHTML
)}`
}
}
|
Fix broken iteration of items in Opentype.js slyphs object | #!/usr/bin/env node
/**
* index.js
*
* for `character-map` command
*/
var opts = require('minimist')(process.argv.slice(2));
var opentype = require('opentype.js');
if (!opts.f || typeof opts.f !== 'string') {
console.log('use -f to specify your font path, TrueType and OpenType supported');
return;
}
opentype.load(opts.f, function(err, font) {
if (err) {
console.log(err);
return;
}
var glyphs = font.glyphs.glyphs;
if (!glyphs || glyphs.length === 0) {
console.log('no glyphs found in this font');
return;
}
var table = '';
Object.keys(glyphs).forEach(function(key) {
var glyph = glyphs[key];
if (!glyph.unicode) {
return;
}
table += String.fromCharCode(glyph.unicode);
});
console.log(table);
});
| #!/usr/bin/env node
/**
* index.js
*
* for `character-map` command
*/
var opts = require('minimist')(process.argv.slice(2));
var opentype = require('opentype.js');
if (!opts.f || typeof opts.f !== 'string') {
console.log('use -f to specify your font path, TrueType and OpenType supported');
return;
}
opentype.load(opts.f, function(err, font) {
if (err) {
console.log(err);
return;
}
if (!font.glyphs || font.glyphs.length === 0) {
console.log('no glyphs found in this font');
return;
}
var table = '';
font.glyphs.forEach(function(glyph) {
if (!glyph.unicode) {
return;
}
table += String.fromCharCode(glyph.unicode);
});
console.log(table);
});
|
Fix error in test-cross handling of drake submitted event | import actionTypes from '../action-types';
import { GUIDE_CONNECTED, GUIDE_ERRORED,
GUIDE_MESSAGE_RECEIVED, GUIDE_ALERT_RECEIVED, ADVANCE_NOTIFICATIONS } from '../modules/notifications';
const initialState = true;
export default function parentDrakeHidden(state = initialState, action) {
switch (action.type) {
case actionTypes.ALLELE_SELECTED:
state = state.setIn(["selectedAlleles", action.chromosome, action.side, action.gene], action.newAllele);
return state;
case actionTypes.NAVIGATED:
return state;
case actionTypes.READY_TO_ANSWER:
state = state.setIn(["hiddenGenotype"], !action.ready);
return state;
case actionTypes.DRAKE_SUBMITTED:
if (state && state.hiddenImage) state = state.setIn(["hiddenImage"], !action.correct);
return state;
default:
return state;
}
}
| import actionTypes from '../action-types';
import { GUIDE_CONNECTED, GUIDE_ERRORED,
GUIDE_MESSAGE_RECEIVED, GUIDE_ALERT_RECEIVED, ADVANCE_NOTIFICATIONS } from '../modules/notifications';
const initialState = true;
export default function parentDrakeHidden(state = initialState, action) {
switch (action.type) {
case actionTypes.ALLELE_SELECTED:
state = state.setIn(["selectedAlleles", action.chromosome, action.side, action.gene], action.newAllele);
return state;
case actionTypes.NAVIGATED:
return state;
case actionTypes.READY_TO_ANSWER:
state = state.setIn(["hiddenGenotype"], !action.ready);
return state;
case actionTypes.DRAKE_SUBMITTED:
state = state.setIn(["hiddenImage"], !action.correct);
return state;
default:
return state;
}
}
|
Add Netty default sizing to test | package org.jctools.queues;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Queue;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.jctools.queues.spec.ConcurrentQueueSpec;
import org.jctools.queues.spec.Ordering;
@RunWith(Parameterized.class)
public class QueueSanityTestMpscChunked extends QueueSanityTestMpscArray
{
public QueueSanityTestMpscChunked(ConcurrentQueueSpec spec, Queue<Integer> queue)
{
super(spec, queue);
}
@Parameterized.Parameters
public static Collection<Object[]> parameters()
{
ArrayList<Object[]> list = new ArrayList<Object[]>();
list.add(makeQueue(0, 1, 4, Ordering.FIFO, new MpscChunkedArrayQueue<>(2, 4)));// MPSC size 1
list.add(makeQueue(0, 1, SIZE, Ordering.FIFO, new MpscChunkedArrayQueue<>(8, SIZE)));// MPSC size SIZE
list.add(makeQueue(0, 1, 4096, Ordering.FIFO, new MpscChunkedArrayQueue<>(32, 4096)));// Netty recycler defaults
return list;
}
}
| package org.jctools.queues;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Queue;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.jctools.queues.spec.ConcurrentQueueSpec;
import org.jctools.queues.spec.Ordering;
@RunWith(Parameterized.class)
public class QueueSanityTestMpscChunked extends QueueSanityTestMpscArray
{
public QueueSanityTestMpscChunked(ConcurrentQueueSpec spec, Queue<Integer> queue)
{
super(spec, queue);
}
@Parameterized.Parameters
public static Collection<Object[]> parameters()
{
ArrayList<Object[]> list = new ArrayList<Object[]>();
list.add(makeQueue(0, 1, 4, Ordering.FIFO, new MpscChunkedArrayQueue<>(2, 4)));// MPSC size 1
list.add(makeQueue(0, 1, SIZE, Ordering.FIFO, new MpscChunkedArrayQueue<>(8, SIZE)));// MPSC size SIZE
return list;
}
}
|
Fix docstring of error functions | import cupy.core.fusion
from cupy.math import ufunc
_erf = ufunc.create_math_ufunc(
'erf', 1, 'cupyx_scipy_erf',
'''Error function.
.. seealso:: :meth:`scipy.special.erf`
''',
support_complex=False)
_erfc = ufunc.create_math_ufunc(
'erfc', 1, 'cupyx_scipy_erfc',
'''Complementary error function.
.. seealso:: :meth:`scipy.special.erfc`
''',
support_complex=False)
_erfcx = ufunc.create_math_ufunc(
'erfcx', 1, 'cupyx_scipy_erfcx',
'''Scaled complementary error function.
.. seealso:: :meth:`scipy.special.erfcx`
''',
support_complex=False)
erf = cupy.core.fusion.ufunc(_erf)
erfc = cupy.core.fusion.ufunc(_erfc)
erfcx = cupy.core.fusion.ufunc(_erfcx)
| import cupy.core.fusion
from cupy.math import ufunc
_erf = ufunc.create_math_ufunc(
'erf', 1, 'cupyx_scipy_erf',
'''Error function.
.. seealso:: :meth: scipy.special.erf
''',
support_complex=False)
_erfc = ufunc.create_math_ufunc(
'erfc', 1, 'cupyx_scipy_erfc',
'''Complementary error function.
.. seealso:: :meth: scipy.special.erfc
''',
support_complex=False)
_erfcx = ufunc.create_math_ufunc(
'erfcx', 1, 'cupyx_scipy_erfcx',
'''Scaled complementary error function.
.. seealso:: :meth: scipy.special.erfcx
''',
support_complex=False)
erf = cupy.core.fusion.ufunc(_erf)
erfc = cupy.core.fusion.ufunc(_erfc)
erfcx = cupy.core.fusion.ufunc(_erfcx)
|
Add detailed error message to jsonl parsing | import json
def read(fn):
if fn.endswith(".jsonl"):
raise TypeError("JSON Newline format can only be read by iread")
with open(fn) as f:
return json.load(f)
def append(obj, fn):
with open(fn, "a+") as f:
f.write(json.dumps(obj) + "\n")
def write(obj, fn):
with open(fn, "w") as f:
json.dump(obj, f, indent=4)
def iread(fn):
with open(fn) as f:
for i, line in enumerate(f):
try:
yield json.loads(line)
except json.decoder.JSONDecodeError as e:
raise json.decoder.JSONDecodeError(
"JSON-L parsing error in line number {} in the jsonl file".format(i),
line, e.pos)
def iwrite(obj, fn):
with open(fn, "w") as f:
for chunk in obj:
f.write(json.dumps(chunk) + "\n")
| import json
def read(fn):
if fn.endswith(".jsonl"):
raise TypeError("JSON Newline format can only be read by iread")
with open(fn) as f:
return json.load(f)
def append(obj, fn):
with open(fn, "a+") as f:
f.write(json.dumps(obj) + "\n")
def write(obj, fn):
with open(fn, "w") as f:
json.dump(obj, f, indent=4)
def iread(fn):
with open(fn) as f:
for line in f:
yield json.loads(line)
def iwrite(obj, fn):
with open(fn, "w") as f:
for chunk in obj:
f.write(json.dumps(chunk) + "\n")
|
Include multiple milestones and open issues in contributor list [ci skip] | #!/usr/bin/env python
"""Print a list of contributors for a particular milestone.
Usage:
python tools/contributor_list.py [MILESTONE] [MILESTONE] ...
"""
import sys
from gh_api import (
get_milestones,
get_milestone_id,
get_issues_list,
)
if __name__ == "__main__":
if len(sys.argv) < 2:
milestones = get_milestones("jupyter/nbgrader", auth=True)
else:
milestones = sys.argv[1:]
users = set()
for milestone in milestones:
if milestone['title'] == "No action":
continue
print("Getting users for {}...".format(milestone['title']))
# this returns both issues and PRs
issues = get_issues_list(
"jupyter/nbgrader",
state='all',
milestone=milestone['number'],
auth=True)
for issue in issues:
users.add(issue['user']['login'])
users = {user.lower(): user for user in users}
print()
print("The following users have submitted issues and/or PRs:")
print("-----------------------------------------------------")
for user in sorted(users.keys()):
print("{}".format(users[user]))
print("-----------------------------------------------------")
| #!/usr/bin/env python
"""Print a list of contributors for a particular milestone.
Usage:
python tools/contributor_list.py MILESTONE
"""
import sys
from gh_api import (
get_milestone_id,
get_issues_list,
)
if __name__ == "__main__":
if len(sys.argv) != 2:
print(__doc__)
sys.exit(1)
milestone = sys.argv[1]
milestone_id = get_milestone_id(
"jupyter/nbgrader",
milestone,
auth=True)
# this returns both issues and PRs
issues = get_issues_list(
"jupyter/nbgrader",
state='closed',
milestone=milestone_id,
auth=True)
users = set()
for issue in issues:
users.add(issue['user']['login'])
users = {user.lower(): user for user in users}
print()
print("The following users have submitted issues and/or PRs:")
print("-----------------------------------------------------")
for user in sorted(users.keys()):
print("- {}".format(users[user]))
print("-----------------------------------------------------")
|
Upgrade tangled 0.1a5 => 0.1a9 | from setuptools import setup
setup(
name='tangled.session',
version='0.1a3.dev0',
description='Tangled session integration',
long_description=open('README.rst').read(),
url='http://tangledframework.org/',
download_url='https://github.com/TangledWeb/tangled.session/tags',
author='Wyatt Baldwin',
author_email='self@wyattbaldwin.com',
packages=[
'tangled',
'tangled.session',
'tangled.session.tests',
],
install_requires=[
'Beaker>=1.6.4',
'tangled>=0.1a9',
],
extras_require={
'dev': [
'tangled[dev]>=0.1a9',
],
},
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
| from setuptools import setup
setup(
name='tangled.session',
version='0.1a3.dev0',
description='Tangled session integration',
long_description=open('README.rst').read(),
url='http://tangledframework.org/',
download_url='https://github.com/TangledWeb/tangled.session/tags',
author='Wyatt Baldwin',
author_email='self@wyattbaldwin.com',
packages=[
'tangled',
'tangled.session',
'tangled.session.tests',
],
install_requires=[
'tangled>=0.1a5',
'Beaker>=1.6.4',
],
extras_require={
'dev': [
'tangled[dev]>=0.1a5',
],
},
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
|
Allow specifying channels to connect to | #!/usr/bin/env node
var IRCb = require('ircb')
var args = require('yargs')
.alias('host', 'h')
.demand('host')
.describe('host', 'IRC server (e.g. chat.freenode.net)')
.alias('port', 'p')
.demand('port')
.describe('port', 'IRC server port')
.default('secure', true)
.describe('secure', 'Whether to use TLS')
.alias('nick', 'n')
.demand('nick')
.describe('nick', 'Bot\'s nick')
.alias('real-name', 'r')
.demand('real-name')
.describe('real-name', 'Bot\'s real name')
.alias('username', 'u')
.demand('username')
.describe('username', 'Bot\' username')
.alias('channel', 'c')
.describe('channel', 'Channel(s) to connect to')
.argv
var tzbot = require('./tzbot.js')
var reconnect = require('reconnect' + (args.secure ? '/tls' : ''))
reconnect(function (stream) {
var irc = IRCb({
nick: args.nick,
realName: args['real-name'],
username: args.username,
channels: Array.isArray(args.channel) ? args.channel : [args.channel]
})
stream.pipe(irc).pipe(stream)
tzbot(irc)
}).connect({
host: args.host,
port: args.port
})
| #!/usr/bin/env node
var IRCb = require('ircb')
var args = require('yargs')
.alias('host', 'h')
.demand('host')
.describe('host', 'IRC server (e.g. chat.freenode.net)')
.alias('port', 'p')
.demand('port')
.describe('port', 'IRC server port')
.default('secure', true)
.describe('secure', 'Whether to use TLS')
.alias('nick', 'n')
.demand('nick')
.describe('nick', 'Bot\'s nick')
.alias('real-name', 'r')
.demand('real-name')
.describe('real-name', 'Bot\'s real name')
.alias('username', 'u')
.demand('username')
.describe('username', 'Bot\' username')
.argv
var tzbot = require('./tzbot.js')
var reconnect = require('reconnect' + (args.secure ? '/tls' : ''))
reconnect(function (stream) {
var irc = IRCb({
nick: args.nick,
realName: args['real-name'],
username: args.username
})
stream.pipe(irc).pipe(stream)
tzbot(irc)
}).connect({
host: args.host,
port: args.port
})
|
Use attributesToArray instead of getAttributes | <?php
namespace Chromabits\Illuminated\Database\Articulate;
use Chromabits\Nucleus\Foundation\BaseObject;
use Chromabits\Nucleus\Meditation\Exceptions\FailedCheckException;
/**
* Class ValidatingObserver
*
* Originally from: https://github.com/AltThree/Validator/
*
* @author Eduardo Trujillo <ed@chromabits.com>
* @package Chromabits\Illuminated\Database\Articulate
*/
class ValidatingObserver extends BaseObject
{
/**
* Validate the model on saving.
*
* @param Model $model
*/
public function saving(Model $model)
{
$this->validate($model);
}
/**
* Validate the model on saving.
*
* @param Model $model
*/
public function restoring(Model $model)
{
$this->validate($model);
}
protected function validate(Model $model)
{
$attributes = $model->attributesToArray();
$checkable = $model->getCheckable();
if ($checkable === null) {
return;
}
$result = $checkable->check($attributes);
if ($result->failed()) {
throw new FailedCheckException($checkable, $result);
}
}
} | <?php
namespace Chromabits\Illuminated\Database\Articulate;
use Chromabits\Nucleus\Foundation\BaseObject;
use Chromabits\Nucleus\Meditation\Exceptions\FailedCheckException;
/**
* Class ValidatingObserver
*
* Originally from: https://github.com/AltThree/Validator/
*
* @author Eduardo Trujillo <ed@chromabits.com>
* @package Chromabits\Illuminated\Database\Articulate
*/
class ValidatingObserver extends BaseObject
{
/**
* Validate the model on saving.
*
* @param Model $model
*/
public function saving(Model $model)
{
$this->validate($model);
}
/**
* Validate the model on saving.
*
* @param Model $model
*/
public function restoring(Model $model)
{
$this->validate($model);
}
protected function validate(Model $model)
{
$attributes = $model->getAttributes();
$checkable = $model->getCheckable();
if ($checkable === null) {
return;
}
$result = $checkable->check($attributes);
if ($result->failed()) {
throw new FailedCheckException($checkable, $result);
}
}
} |
Validate only last line for leader command test
This is to deflake leader command integration test.
The reason for failure is that error output contains some netty error
trace that we can't control. When netty receives a command for a stream
that is closed or being closed, such traces are written to sys::err. In
this case, it's the latter, that some stream is about to be closed when
leader command hits the server. This flake is introduced by gRPC long
polling. Reason for that is now that servers keep an open stream,
closing a server attempts to close those as well. However that takes
some time after actual complete call is called on the stream. Hence it
increased exposure to receive cancelled/closed stream errors from netty.
pr-link: Alluxio/alluxio#9582
change-id: cid-c455b0b6604c60a490beed43b3a6f2e98424adf3 | /*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.client.cli.fs.command;
import alluxio.client.cli.fs.AbstractFileSystemShellTest;
import org.junit.Assert;
import org.junit.Test;
/**
* Tests for leader command.
*/
public final class LeaderCommandIntegrationTest extends AbstractFileSystemShellTest {
@Test
public void leader() {
mFsShell.run("leader");
String expected =
mLocalAlluxioCluster.getLocalAlluxioMaster().getAddress().getHostName() + "\n";
Assert.assertEquals(expected, mOutput.toString());
}
@Test
public void leaderAddressNotAvailable() throws Exception {
mLocalAlluxioCluster.stopMasters();
mFsShell.run("leader");
String expected = "The leader is not currently serving requests.";
Assert.assertTrue(mErrOutput.toString().contains(expected));
}
}
| /*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.client.cli.fs.command;
import alluxio.client.cli.fs.AbstractFileSystemShellTest;
import org.junit.Assert;
import org.junit.Test;
/**
* Tests for leader command.
*/
public final class LeaderCommandIntegrationTest extends AbstractFileSystemShellTest {
@Test
public void leader() {
mFsShell.run("leader");
String expected =
mLocalAlluxioCluster.getLocalAlluxioMaster().getAddress().getHostName() + "\n";
Assert.assertEquals(expected, mOutput.toString());
}
@Test
public void leaderAddressNotAvailable() throws Exception {
mLocalAlluxioCluster.stopMasters();
mFsShell.run("leader");
String expected = "The leader is not currently serving requests.\n";
Assert.assertEquals(expected, mErrOutput.toString());
}
}
|
Add properties to Error from execFileOut
These are the same properties added to errors by execFile and
getExecFile. Add them for consistency and because callers may need
them.
Signed-off-by: Kevin Locke <ffb4761cba839470133bee36aeb139f58d7dbaa9@kevinlocke.name> | /**
* @copyright Copyright 2017 Kevin Locke <kevin@kevinlocke.name>
* @license MIT
*/
'use strict';
var getExecFile = require('get-exec-file');
/** Promisified <code>execFile</code> wrapper which only provides access to
* <code>stdout</code> and fails if <code>stderr</code> is non-empty.
* @param {string} file The name or path of the executable file to run
* @param {Array<string>=} args List of string arguments
* @param {Object=} options Options.
* @return {Promise<string>} Promise of <code>stdout</code> or Error if
* <code>execFile</code> fails or <code>stderr</code> contains non-whitespace
* characters.
* @private
*/
function execFileOut(file, args, options) {
var child = getExecFile(file, args, options);
child.stdin.end();
return child.then(function(result) {
// Note: stderr can be Buffer if options.encoding === 'buffer'
var stderr = result.stderr.toString();
if (stderr.trim()) {
// Same Error as execFile for code !== 0
var cmd = file;
if (args) {
cmd += ' ' + args.join(' ');
}
var err = new Error('Command failed: ' + cmd + '\n' + stderr);
err.cmd = cmd;
err.code = 0;
err.stderr = result.stderr;
err.stdout = result.stdout;
return Promise.reject(err);
}
return result.stdout;
});
}
module.exports = execFileOut;
| /**
* @copyright Copyright 2017 Kevin Locke <kevin@kevinlocke.name>
* @license MIT
*/
'use strict';
var getExecFile = require('get-exec-file');
/** Promisified <code>execFile</code> wrapper which only provides access to
* <code>stdout</code> and fails if <code>stderr</code> is non-empty.
* @param {string} file The name or path of the executable file to run
* @param {Array<string>=} args List of string arguments
* @param {Object=} options Options.
* @return {Promise<string>} Promise of <code>stdout</code> or Error if
* <code>execFile</code> fails or <code>stderr</code> contains non-whitespace
* characters.
* @private
*/
function execFileOut(file, args, options) {
var child = getExecFile(file, args, options);
child.stdin.end();
return child.then(function(result) {
// Note: stderr can be Buffer if options.encoding === 'buffer'
var stderr = result.stderr.toString();
if (stderr.trim()) {
// Same Error as execFile for code !== 0
var cmd = file;
if (args) {
cmd += ' ' + args.join(' ');
}
return Promise.reject(
new Error('Command failed: ' + cmd + '\n' + stderr)
);
}
return result.stdout;
});
}
module.exports = execFileOut;
|
Change the Sifter issue number matching
Now it's only 3-5 digits, optionally with the hash,
and only as a standalone word. | import os
import requests
import re
import json
NUM_REGEX = r'\b\#?(\d\d\d\d?\d?)\b'
API_KEY = os.environ['SIFTER']
def find_ticket(number):
headers = {
'X-Sifter-Token': API_KEY
}
url = 'https://unisubs.sifterapp.com/api/projects/12298/issues?q=%s'
api = url % number
r = requests.get(api, headers=headers)
data = json.loads(r.content)
for issue in data['issues']:
if str(issue['number']) == number:
return format_ticket(issue)
def format_ticket(issue):
url = "https://unisubs.sifterapp.com/issue/%s" % issue['number']
return "%s - %s - %s" % (issue['number'], issue['subject'], url)
def parse(text):
issues = re.findall(NUM_REGEX, text)
return map(find_ticket, issues)
| import os
import requests
import re
import json
NUM_REGEX = r'\#([0-9]+)'
API_KEY = os.environ['SIFTER']
def find_ticket(number):
headers = {
'X-Sifter-Token': API_KEY
}
url = 'https://unisubs.sifterapp.com/api/projects/12298/issues?q=%s'
api = url % number
r = requests.get(api, headers=headers)
data = json.loads(r.content)
for issue in data['issues']:
if str(issue['number']) == number:
return format_ticket(issue)
def format_ticket(issue):
url = "https://unisubs.sifterapp.com/issue/%s" % issue['number']
return "%s - %s - %s" % (issue['number'], issue['subject'], url)
def parse(text):
issues = re.findall(NUM_REGEX, text)
return map(find_ticket, issues)
|
Update service worker to update cached files, get effect reset fix. | // Version 7
self.addEventListener('install', function(e) {
e.waitUntil(
caches.open('playbulb-candle').then(function(cache) {
return cache.addAll([
'/demos/playbulb-candle/',
'/demos/playbulb-candle/index.html',
'/demos/playbulb-candle/styles.css',
'/demos/playbulb-candle/playbulbCandle.js',
'/demos/playbulb-candle/app.js',
'/demos/playbulb-candle/color-wheel.png',
'/demos/playbulb-candle/code.getmdl.io/1.0.4/material.green-light_green.min.css',
'/demos/playbulb-candle/code.getmdl.io/1.0.4/material.min.js',
'https://fonts.googleapis.com/icon?family=Material+Icons',
]).then(function() {
return self.skipWaiting();
});
})
);
});
self.addEventListener('activate', function(event) {
event.waitUntil(self.clients.claim());
});
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request).then(function(response) {
return response || fetch(event.request);
})
);
});
| // Version 6
self.addEventListener('install', function(e) {
e.waitUntil(
caches.open('playbulb-candle').then(function(cache) {
return cache.addAll([
'/demos/playbulb-candle/',
'/demos/playbulb-candle/index.html',
'/demos/playbulb-candle/styles.css',
'/demos/playbulb-candle/playbulbCandle.js',
'/demos/playbulb-candle/app.js',
'/demos/playbulb-candle/color-wheel.png',
'/demos/playbulb-candle/code.getmdl.io/1.0.4/material.green-light_green.min.css',
'/demos/playbulb-candle/code.getmdl.io/1.0.4/material.min.js',
'https://fonts.googleapis.com/icon?family=Material+Icons',
]).then(function() {
return self.skipWaiting();
});
})
);
});
self.addEventListener('activate', function(event) {
event.waitUntil(self.clients.claim());
});
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request).then(function(response) {
return response || fetch(event.request);
})
);
});
|
code: Replace deprecated Buffer() with Buffer.from(). | require('es6-promise').polyfill();
const helper = require('./helper');
function api(baseUrl, config, method, params) {
let url = baseUrl;
const auth = Buffer.from(`${config.username}:${config.apiKey}`).toString('base64');
const authHeader = `Basic ${auth}`;
const options = { method, headers: { Authorization: authHeader } };
if (method === 'POST') {
options.body = new helper.FormData();
Object.keys(params).forEach((key) => {
options.body.append(key, params[key]);
});
} else if (params) {
const generateQueryParam = key => `${key}=${params[key]}`;
const queryParams = Object.keys(params).map(generateQueryParam);
url = `${url}?${queryParams.join('&')}`;
}
return helper.fetch(url, options).then(res => res.json());
}
module.exports = api;
| require('es6-promise').polyfill();
const helper = require('./helper');
function api(baseUrl, config, method, params) {
let url = baseUrl;
const auth = new Buffer(`${config.username}:${config.apiKey}`).toString('base64');
const authHeader = `Basic ${auth}`;
const options = { method, headers: { Authorization: authHeader } };
if (method === 'POST') {
options.body = new helper.FormData();
Object.keys(params).forEach((key) => {
options.body.append(key, params[key]);
});
} else if (params) {
const generateQueryParam = key => `${key}=${params[key]}`;
const queryParams = Object.keys(params).map(generateQueryParam);
url = `${url}?${queryParams.join('&')}`;
}
return helper.fetch(url, options).then(res => res.json());
}
module.exports = api;
|
[docs] Use id for TodoApp example | var TODO_COMPONENT = `
var TodoList = React.createClass({
render: function() {
var createItem = function(item) {
return <li key={item.id}>{item.text}</li>;
};
return <ul>{this.props.items.map(createItem)}</ul>;
}
});
var TodoApp = React.createClass({
getInitialState: function() {
return {items: [], text: ''};
},
onChange: function(e) {
this.setState({text: e.target.value});
},
handleSubmit: function(e) {
e.preventDefault();
var nextItems = this.state.items.concat([{text: this.state.text, id: Date.now()}]);
var nextText = '';
this.setState({items: nextItems, text: nextText});
},
render: function() {
return (
<div>
<h3>TODO</h3>
<TodoList items={this.state.items} />
<form onSubmit={this.handleSubmit}>
<input onChange={this.onChange} value={this.state.text} />
<button>{'Add #' + (this.state.items.length + 1)}</button>
</form>
</div>
);
}
});
ReactDOM.render(<TodoApp />, mountNode);
`;
ReactDOM.render(
<ReactPlayground codeText={TODO_COMPONENT} />,
document.getElementById('todoExample')
);
| var TODO_COMPONENT = `
var TodoList = React.createClass({
render: function() {
var createItem = function(itemText, index) {
return <li key={index + itemText}>{itemText}</li>;
};
return <ul>{this.props.items.map(createItem)}</ul>;
}
});
var TodoApp = React.createClass({
getInitialState: function() {
return {items: [], text: ''};
},
onChange: function(e) {
this.setState({text: e.target.value});
},
handleSubmit: function(e) {
e.preventDefault();
var nextItems = this.state.items.concat([this.state.text]);
var nextText = '';
this.setState({items: nextItems, text: nextText});
},
render: function() {
return (
<div>
<h3>TODO</h3>
<TodoList items={this.state.items} />
<form onSubmit={this.handleSubmit}>
<input onChange={this.onChange} value={this.state.text} />
<button>{'Add #' + (this.state.items.length + 1)}</button>
</form>
</div>
);
}
});
ReactDOM.render(<TodoApp />, mountNode);
`;
ReactDOM.render(
<ReactPlayground codeText={TODO_COMPONENT} />,
document.getElementById('todoExample')
);
|
Fix indefinite hangs when closing streaming results.
* See https://github.com/KeepSafe/aiohttp/issues/739 | import asyncio
import json
import logging
import aiohttp.errors
log = logging.getLogger(__name__)
class JsonStreamResult:
def __init__(self, response, transform=None):
self.response = response
self.transform = transform or (lambda x: x)
async def fetch(self):
while True:
try:
data = await self.response.content.readline()
if not data:
break
except (aiohttp.errors.ClientDisconnectedError,
aiohttp.errors.ServerDisconnectedError):
break
yield self.transform(json.loads(data.decode('utf8')))
async def close(self):
# response.release() indefinitely hangs because the server is sending
# an infinite stream of messages.
# (see https://github.com/KeepSafe/aiohttp/issues/739)
await self.response.close()
async def json_stream_result(response, transform=None, stream=True):
json_stream = JsonStreamResult(response, transform)
if stream:
return json_stream
data = []
async for obj in json_stream.fetch():
data.append(obj)
return data
| import asyncio
import json
import logging
import aiohttp.errors
log = logging.getLogger(__name__)
class JsonStreamResult:
def __init__(self, response, transform=None):
self.response = response
self.transform = transform or (lambda x: x)
async def fetch(self):
while True:
try:
data = await self.response.content.readline()
if not data:
break
except (aiohttp.errors.ClientDisconnectedError,
aiohttp.errors.ServerDisconnectedError):
break
yield self.transform(json.loads(data.decode('utf8')))
async def close(self):
await self.response.release()
async def json_stream_result(response, transform=None, stream=True):
json_stream = JsonStreamResult(response, transform)
if stream:
return json_stream
data = []
async for obj in json_stream.fetch():
data.append(obj)
return data
|
Fix anonymous access for sentence writing | 'use strict';
module.exports =
/*@ngInject*/
function configure ($stateProvider) {
$stateProvider
.state('play-sw', {
parent: 'app',
templateUrl: 'sentences.play.html',
controller: 'SentencePlayCtrl',
url: '/play/sw?uid&student&anonymous',
data: {
authenticateUser: true
}
})
.state('play-sw.results', {
parent: 'app',
templateUrl: 'sentences.results.html',
controller: 'ResultsController',
url: '/play/sw/results?uid&student'
})
.state('play-sw-gen.results', {
parent: 'app',
templateUrl: 'sentences.results.html',
controller: 'ResultsController',
url: '/play/sw/gen-results?passageId'
})
.state('play-sw-gen', {
parent: 'app',
templateUrl: 'sentences.play.html',
controller: 'SentencePlayCtrl',
url: '/play/sw/g/:ids?student&passageId&pfAllCorrect'
});
};
| 'use strict';
module.exports =
/*@ngInject*/
function configure ($stateProvider) {
$stateProvider
.state('play-sw', {
parent: 'app',
templateUrl: 'sentences.play.html',
controller: 'SentencePlayCtrl',
url: '/play/sw?uid&student',
data: {
authenticateUser: true
}
})
.state('play-sw.results', {
parent: 'app',
templateUrl: 'sentences.results.html',
controller: 'ResultsController',
url: '/play/sw/results?uid&student'
})
.state('play-sw-gen.results', {
parent: 'app',
templateUrl: 'sentences.results.html',
controller: 'ResultsController',
url: '/play/sw/gen-results?passageId'
})
.state('play-sw-gen', {
parent: 'app',
templateUrl: 'sentences.play.html',
controller: 'SentencePlayCtrl',
url: '/play/sw/g/:ids?student&passageId&pfAllCorrect'
});
};
|
Make default window size smaller | 'use strict'
const electron = require('electron')
const app = electron.app // Module to control application life.
const BrowserWindow = electron.BrowserWindow // Module to create native browser window.
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow
// Quit when all windows are closed.
app.on('window-all-closed', () => {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform != 'darwin') {
app.quit()
}
})
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', () => {
// Create the browser window.
mainWindow = new BrowserWindow({width: 800, height: 600})
// and load the index.html of the app.
mainWindow.loadURL(`file://${__dirname}/index.html`)
// Open the DevTools.
// mainWindow.webContents.openDevTools()
// Emitted when the window is closed.
mainWindow.on('closed', function() {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null
})
}) | 'use strict'
const electron = require('electron')
const app = electron.app // Module to control application life.
const BrowserWindow = electron.BrowserWindow // Module to create native browser window.
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow
// Quit when all windows are closed.
app.on('window-all-closed', () => {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform != 'darwin') {
app.quit()
}
})
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', () => {
// Create the browser window.
mainWindow = new BrowserWindow({width: 1200, height: 900})
// and load the index.html of the app.
mainWindow.loadURL(`file://${__dirname}/index.html`)
// Open the DevTools.
// mainWindow.webContents.openDevTools()
// Emitted when the window is closed.
mainWindow.on('closed', function() {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null
})
}) |
Use new API. Reorder & simplify. | package main
import (
"fmt"
"github.com/urfave/cli"
"log"
"os"
"strconv"
)
// init injects our "ip" related commands/options.
func init() {
// Fill-in the various commands
cliCommands = append(cliCommands, cli.Command{
Name: "ip",
Usage: "returns current ip",
Description: "shorthand for getting current ip",
Action: cmdIP,
})
}
// shortcuts
// cmdIP is a short for displaying the IPs for one probe
func cmdIP(c *cli.Context) error {
var (
probeID int
)
args := c.Args()
if len(args) == 1 {
probeID, _ = strconv.Atoi(args[0])
}
if probeID == 0 {
if mycnf.DefaultProbe == 0 {
log.Fatal("Error: you must specify a probe ID!")
} else {
probeID = mycnf.DefaultProbe
}
}
p, err := client.GetProbe(probeID)
if err != nil {
fmt.Printf("err: %v", err)
os.Exit(1)
}
fmt.Printf("IPv4: %s IPv6: %s\n", p.AddressV4, p.AddressV6)
return nil
}
| package main
import (
"fmt"
"github.com/keltia/ripe-atlas"
"github.com/urfave/cli"
"log"
"os"
"strconv"
)
// init injects our "ip" related commands/options.
func init() {
// Fill-in the various commands
cliCommands = append(cliCommands, cli.Command{
Name: "ip",
Usage: "returns current ip",
Description: "shorthand for getting current ip",
Action: cmdIP,
})
}
// shortcuts
// cmdIP is a short for displaying the IPs for one probe
func cmdIP(c *cli.Context) error {
var probeID string
args := c.Args()
if len(args) == 0 {
if mycnf.DefaultProbe == 0 {
log.Fatal("Error: you must specify a probe ID!")
} else {
probeID = fmt.Sprintf("%d", mycnf.DefaultProbe)
}
} else {
probeID = args[0]
}
id, _ := strconv.Atoi(probeID)
p, err := atlas.GetProbe(id)
if err != nil {
fmt.Printf("err: %v", err)
os.Exit(1)
}
fmt.Printf("IPv4: %s IPv6: %s\n", p.AddressV4, p.AddressV6)
return nil
}
|
Remove obsolute async util import | import { transformFile } from 'babel-core'
import { debug } from '../util/stdio'
import { default as es2015 } from 'babel-preset-es2015'
import { default as amd } from 'babel-plugin-transform-es2015-modules-amd'
export default function configure(pkg, opts) {
return (name, file, done) => {
transformFile(file
, { moduleIds: true
, moduleRoot: `${pkg.name}/${opts.lib}`
, sourceRoot: opts.src
, presets: [es2015]
, plugins: [amd]
, babelrc: true
, sourceMaps: !!opts.debug
, sourceFileName: file
, sourceMapTarget: file
}
, (error, result) => {
if (error) {
done(error)
} else {
let output = { files: { [`${name}.js`]: result.code } }
if (opts.debug) {
output.files[`${name}.js.map`] = JSON.stringify(result.map)
}
done(null, output)
}
}
)
}
} | import { transformFile } from 'babel-core'
import { then } from '../util/async'
import { debug } from '../util/stdio'
import { default as es2015 } from 'babel-preset-es2015'
import { default as amd } from 'babel-plugin-transform-es2015-modules-amd'
export default function configure(pkg, opts) {
return (name, file, done) => {
transformFile(file
, { moduleIds: true
, moduleRoot: `${pkg.name}/${opts.lib}`
, sourceRoot: opts.src
, presets: [es2015]
, plugins: [amd]
, babelrc: true
, sourceMaps: !!opts.debug
, sourceFileName: file
, sourceMapTarget: file
}
, (error, result) => {
if (error) {
done(error)
} else {
let output = { files: { [`${name}.js`]: result.code } }
if (opts.debug) {
output.files[`${name}.js.map`] = JSON.stringify(result.map)
}
done(null, output)
}
}
)
}
} |
Make sure that unhandled rejections are thrown so that eg. mocha will pick them up and consider the test suite to have failed. | /*global Promise:true*/
var Promise = require('bluebird');
var workQueue = {
queue: [],
drain: function () {
this.queue.forEach(function (fn) {
fn();
});
this.queue = [];
}
};
var scheduler = Promise.setScheduler(function (fn) {
workQueue.queue.push(fn);
scheduler(function () {
workQueue.drain();
});
});
var _notifyUnhandledRejection = Promise.prototype._notifyUnhandledRejection;
Promise.prototype._notifyUnhandledRejection = function () {
var that = this;
var args = arguments;
scheduler(function () {
if (that._isRejectionUnhandled()) {
throw that.reason();
}
});
};
module.exports = workQueue;
| /*global Promise:true*/
var Promise = require('bluebird');
var workQueue = {
queue: [],
drain: function () {
this.queue.forEach(function (fn) {
fn();
});
this.queue = [];
}
};
var scheduler = Promise.setScheduler(function (fn) {
workQueue.queue.push(fn);
scheduler(function () {
workQueue.drain();
});
});
var _notifyUnhandledRejection = Promise.prototype._notifyUnhandledRejection;
Promise.prototype._notifyUnhandledRejection = function () {
var that = this;
var args = arguments;
scheduler(function () {
_notifyUnhandledRejection.apply(that, args);
});
};
module.exports = workQueue;
|
Revert "fix: allow backtick in HTML templates as well"
This reverts commit 2f96458bcb6dfe8b8db4ef0101036b09bfa7c5f5. | module.exports = {
name: "frappe-html",
setup(build) {
let path = require("path");
let fs = require("fs/promises");
build.onResolve({ filter: /\.html$/ }, (args) => {
return {
path: path.join(args.resolveDir, args.path),
namespace: "frappe-html",
};
});
build.onLoad({ filter: /.*/, namespace: "frappe-html" }, (args) => {
let filepath = args.path;
let filename = path.basename(filepath).split(".")[0];
return fs
.readFile(filepath, "utf-8")
.then((content) => {
content = scrub_html_template(content);
return {
contents: `\n\tfrappe.templates['${filename}'] = \`${content}\`;\n`,
watchFiles: [filepath],
};
})
.catch(() => {
return {
contents: "",
warnings: [
{
text: `There was an error importing ${filepath}`,
},
],
};
});
});
},
};
function scrub_html_template(content) {
content = content.replace(/`/g, "\\`");
return content;
}
| module.exports = {
name: "frappe-html",
setup(build) {
let path = require("path");
let fs = require("fs/promises");
build.onResolve({ filter: /\.html$/ }, (args) => {
return {
path: path.join(args.resolveDir, args.path),
namespace: "frappe-html",
};
});
build.onLoad({ filter: /.*/, namespace: "frappe-html" }, (args) => {
let filepath = args.path;
let filename = path.basename(filepath).split(".")[0];
return fs
.readFile(filepath, "utf-8")
.then((content) => {
content = JSON.stringify(scrub_html_template(content));
return {
contents: `\n\tfrappe.templates['${filename}'] = ${content};\n`,
watchFiles: [filepath],
};
})
.catch(() => {
return {
contents: "",
warnings: [
{
text: `There was an error importing ${filepath}`,
},
],
};
});
});
},
};
function scrub_html_template(content) {
content = content.replace(/`/g, "\\`");
return content;
}
|
Use send instead of sendAction | import EmberObject from '@ember/object';
import Evented from '@ember/object/evented';
import { computed } from '@ember/object';
import ObjHash from './obj-hash';
import { unwrapper } from 'ember-drag-drop/utils/proxy-unproxy-objects';
export default EmberObject.extend(Evented, {
objectMap: computed(function() {
return ObjHash.create();
}),
getObject: function(id,ops) {
ops = ops || {};
var payload = this.get('objectMap').getObj(id);
if (payload.ops.source && !payload.ops.source.isDestroying && !payload.ops.source.isDestroyed) {
payload.ops.source.send('action', payload.obj);
}
if (payload.ops.target && !payload.ops.target.isDestroying && !payload.ops.target.isDestroyed) {
payload.ops.target.send('action', payload.obj);
}
this.trigger("objectMoved", {obj: unwrapper(payload.obj), source: payload.ops.source, target: ops.target});
return unwrapper(payload.obj);
},
setObject: function(obj,ops) {
ops = ops || {};
return this.get('objectMap').add({obj: obj, ops: ops});
}
});
| import EmberObject from '@ember/object';
import Evented from '@ember/object/evented';
import { computed } from '@ember/object';
import ObjHash from './obj-hash';
import { unwrapper } from 'ember-drag-drop/utils/proxy-unproxy-objects';
export default EmberObject.extend(Evented, {
objectMap: computed(function() {
return ObjHash.create();
}),
getObject: function(id,ops) {
ops = ops || {};
var payload = this.get('objectMap').getObj(id);
if (payload.ops.source && !payload.ops.source.isDestroying && !payload.ops.source.isDestroyed) {
payload.ops.source.sendAction('action',payload.obj);
}
if (payload.ops.target && !payload.ops.target.isDestroying && !payload.ops.target.isDestroyed) {
payload.ops.target.sendAction('action',payload.obj);
}
this.trigger("objectMoved", {obj: unwrapper(payload.obj), source: payload.ops.source, target: ops.target});
return unwrapper(payload.obj);
},
setObject: function(obj,ops) {
ops = ops || {};
return this.get('objectMap').add({obj: obj, ops: ops});
}
});
|
Improve hover text for milestone status display | <?php if ($milestone instanceof TBGMilestone): ?>
<span class="milestonename"><?php echo $milestone->getName(); ?></span>
<div class="statusblocks">
<?php foreach ($status_details['details'] as $status): ?>
<div class="statusblock" style="background-color: <?php echo (isset($statuses[$status['id']])) ? $statuses[$status['id']]->getColor() : '#FFF'; ?>; width: <?php echo $status['percent']; ?>%;" title="<?php echo __('%status_name - %percentage (%count of %total)', array('%status_name' => (isset($statuses[$status['id']])) ? $statuses[$status['id']]->getName() : __('Unknown status'), '%percentage' => $status['percent'].'%', '%count' => $status['count'], '%total' => $status_details['total'])); ?>"></div>
<?php endforeach; ?>
</div>
<div class="milestone_percentage">
<div class="filler" id="milestone_<?php echo $milestone->getID(); ?>_percentage_filler" style="width: <?php echo $milestone->getPercentComplete(); ?>%;" title="<?php echo __('%percentage completed', array('%percentage' => $milestone->getPercentComplete().'%')); ?>"></div>
</div>
<?php else: ?>
<span class="milestonename faded_out"><?php echo __('No milestones exists'); ?></span>
<?php endif; ?>
| <?php if ($milestone instanceof TBGMilestone): ?>
<span class="milestonename"><?php echo $milestone->getName(); ?></span>
<div class="statusblocks">
<?php foreach ($status_details['details'] as $status): ?>
<div class="statusblock" style="background-color: <?php echo (isset($statuses[$status['id']])) ? $statuses[$status['id']]->getColor() : '#FFF'; ?>; width: <?php echo $status['percent']; ?>%;" title="<?php echo (isset($statuses[$status['id']])) ? $statuses[$status['id']]->getName() : __('Unknown status'); ?> - <?php echo $status['percent']; ?>%"></div>
<?php endforeach; ?>
</div>
<div class="milestone_percentage">
<div class="filler" id="milestone_<?php echo $milestone->getID(); ?>_percentage_filler" style="width: <?php echo $milestone->getPercentComplete(); ?>%;"></div>
</div>
<?php else: ?>
<span class="milestonename faded_out"><?php echo __('No milestones exists'); ?></span>
<?php endif; ?>
|
Update URL to point to new repository/website | import husk
from setuptools import setup, find_packages
kwargs = {
'packages': find_packages(),
'include_package_data': True,
'test_suite': 'tests',
'name': 'husk',
'version': husk.__version__,
'author': 'Byron Ruth, Patrick Henning',
'author_email': 'b@devel.io',
'description': husk.__doc__,
'license': 'BSD',
'keywords': 'note-taking Cornell',
'url': 'http://husk.github.com/husk/',
'scripts': ['bin/husk'],
'classifiers': [
'Development Status :: 4 - Beta',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 2.7'
],
}
setup(**kwargs)
| import husk
from setuptools import setup, find_packages
kwargs = {
'packages': find_packages(),
'include_package_data': True,
'test_suite': 'tests',
'name': 'husk',
'version': husk.__version__,
'author': 'Byron Ruth, Patrick Henning',
'author_email': 'b@devel.io',
'description': husk.__doc__,
'license': 'BSD',
'keywords': 'note-taking Cornell',
'url': 'https://bruth.github.com/husk/',
'scripts': ['bin/husk'],
'classifiers': [
'Development Status :: 4 - Beta',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 2.7'
],
}
setup(**kwargs)
|
Fix <img> not being printed to <picture>. | <?php
namespace ResponsiveImages;
use Functional as F;
/**
* Class Slot
*/
class Slot
{
/**
* @var Size[]
*/
private $sizes = [];
/**
* @var Source[]
*/
private $sources = [];
function __construct(array $sizes)
{
$this->sizes = $sizes;
$this->groupSizesIntoSources();
}
private function groupSizesIntoSources()
{
$prev_aspect_ratio = null;
$source = [];
foreach ($this->sizes as $size) {
$aspect_ratio = $size->getAspectRatio();
if (isset($prev_aspect_ratio) and $aspect_ratio !== $prev_aspect_ratio) {
$this->sources[] = new Source($source);
$source = [];
}
$prev_aspect_ratio = $aspect_ratio;
$source[] = $size;
}
$this->sources[] = new Source($source, true);
}
public function renderFor($uri, SrcsetGeneratorInterface $srcset_gen)
{
if (count($this->sources) === 1)
return $this->sources[0]->renderFor($uri);
$html = F\reduce_left($this->sources,
function(Source $source, $i, $c, $acc) use ($uri, $srcset_gen){
return "$acc\n ".$source->renderFor($uri, $srcset_gen);
}, '');
return "<picture>$html\n</picture>";
}
}
| <?php
namespace ResponsiveImages;
use Functional as F;
/**
* Class Slot
*/
class Slot
{
/**
* @var Size[]
*/
private $sizes = [];
/**
* @var Source[]
*/
private $sources = [];
function __construct(array $sizes)
{
$this->sizes = $sizes;
$this->groupSizesIntoSources();
}
private function groupSizesIntoSources()
{
$prev_aspect_ratio = null;
$source = [];
foreach ($this->sizes as $size) {
$aspect_ratio = $size->getAspectRatio();
if (isset($prev_aspect_ratio) and $aspect_ratio !== $prev_aspect_ratio) {
$this->sources[] = new Source($source);
$source = [];
}
$prev_aspect_ratio = $aspect_ratio;
$source[] = $size;
}
$sources[] = new Source($source, true);
}
public function renderFor($uri, SrcsetGeneratorInterface $srcset_gen)
{
if (count($this->sources) === 1)
return $this->sources[0]->renderFor($uri);
$html = F\reduce_left($this->sources,
function(Source $source, $i, $c, $acc) use ($uri, $srcset_gen){
return "$acc\n ".$source->renderFor($uri, $srcset_gen);
}, '');
return "<picture>$html\n</picture>";
}
}
|
Fix wrong copy-pasted file documentation header. | <?php
/**
* This file is part of phpcq/doctrine-validation.
*
* (c) 2014 Tristan Lins
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* This project is provided in good faith and hope to be usable by anyone.
*
* @package phpcq/doctrine-validation
* @author Tristan Lins <tristan@lins.io>
* @copyright Tristan Lins <tristan@lins.io>
* @link https://github.com/phpcq/doctrine-validation
* @license https://github.com/phpcq/doctrine-validation/blob/master/LICENSE MIT
* @filesource
*/
error_reporting(E_ALL);
function includeIfExists($file)
{
return file_exists($file) ? include $file : false;
}
if ((!$loader = includeIfExists(__DIR__.'/../vendor/autoload.php')) && (!$loader = includeIfExists(__DIR__.'/../../../autoload.php'))) {
echo 'You must set up the project dependencies, run the following commands:'.PHP_EOL.
'curl -sS https://getcomposer.org/installer | php'.PHP_EOL.
'php composer.phar install'.PHP_EOL;
exit(1);
}
| <?php
/**
* This file is part of phpcq/branch-alias-validation.
*
* (c) 2014 Christian Schiffler, Tristan Lins
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* This project is provided in good faith and hope to be usable by anyone.
*
* @package phpcq/branch-alias-validation
* @author Christian Schiffler <c.schiffler@cyberspectrum.de>
* @author Tristan Lins <tristan@lins.io>
* @copyright Christian Schiffler <c.schiffler@cyberspectrum.de>, Tristan Lins <tristan@lins.io>
* @link https://github.com/phpcq/branch-alias-validation
* @license https://github.com/phpcq/branch-alias-validation/blob/master/LICENSE MIT
* @filesource
*/
error_reporting(E_ALL);
function includeIfExists($file)
{
return file_exists($file) ? include $file : false;
}
if ((!$loader = includeIfExists(__DIR__.'/../vendor/autoload.php')) && (!$loader = includeIfExists(__DIR__.'/../../../autoload.php'))) {
echo 'You must set up the project dependencies, run the following commands:'.PHP_EOL.
'curl -sS https://getcomposer.org/installer | php'.PHP_EOL.
'php composer.phar install'.PHP_EOL;
exit(1);
}
|
Fix up the unit test a bit. | package sample.java.project;
import junit.framework.TestCase;
/**
* A sample JUnit test.
*
* This test exists as a placeholder for the test unit framework.
*/
public class SampleJavaProjectTest extends TestCase {
/**
* Holds an instance of the class we are testing.
*/
private SampleJavaProject sjp;
/**
* JUnit set up method.
*/
public final void setUp() {
sjp = new SampleJavaProject();
}
/**
* Tests the add() method in the main class.
*/
public final void testAdd() {
assertEquals(sjp.add(3, 4), 7);
assertEquals(sjp.add(5, -5), 0);
assertEquals(sjp.add(-3, 4), 1);
}
}
| package sample.java.project;
import junit.framework.TestCase;
/**
* A sample JUnit test.
*
* This test exists as a placeholder for the test unit framework.
*/
public class SampleJavaProjectTest extends TestCase {
/**
* JUnit boilerplate.
*
* @param name the name string
*/
public SampleJavaProjectTest(final String name) {
super(name);
}
/**
* Holds an instance of the class we are testing.
*/
private SampleJavaProject sjp;
/**
* JUnit set up method.
*/
public final void setUp() {
sjp = new SampleJavaProject();
}
/**
* Tests the add() method in the main class.
*/
public final void testAdd() {
assertEquals(sjp.add(3, 4), 7);
}
}
|
Remove backward compatibility hack for exception subclass | """errors and exceptions."""
from distutils.version import LooseVersion
from pkg_resources import get_distribution
from six import text_type
from werkzeug import exceptions
class RateLimitExceeded(exceptions.TooManyRequests):
"""exception raised when a rate limit is hit.
The exception results in ``abort(429)`` being called.
"""
code = 429
limit = None
def __init__(self, limit):
self.limit = limit
if limit.error_message:
description = (
limit.error_message
if not callable(limit.error_message)
else limit.error_message()
)
else:
description = text_type(limit.limit)
super(RateLimitExceeded, self).__init__(description=description)
| """errors and exceptions."""
from distutils.version import LooseVersion
from pkg_resources import get_distribution
from six import text_type
from werkzeug import exceptions
werkzeug_exception = None
werkzeug_version = get_distribution("werkzeug").version
if LooseVersion(werkzeug_version) < LooseVersion("0.9"): # pragma: no cover
# sorry, for touching your internals :).
import werkzeug._internal
werkzeug._internal.HTTP_STATUS_CODES[429] = "Too Many Requests"
werkzeug_exception = exceptions.HTTPException
else:
# Werkzeug 0.9 and up have an existing exception for 429
werkzeug_exception = exceptions.TooManyRequests
class RateLimitExceeded(werkzeug_exception):
"""exception raised when a rate limit is hit.
The exception results in ``abort(429)`` being called.
"""
code = 429
limit = None
def __init__(self, limit):
self.limit = limit
if limit.error_message:
description = (
limit.error_message
if not callable(limit.error_message)
else limit.error_message()
)
else:
description = text_type(limit.limit)
super(RateLimitExceeded, self).__init__(description=description)
|
Add `handle_raw` method that does not catch all upstream exceptions | from argparse import ArgumentParser
def cached_property(func):
cach_attr = '_{}'.format(func.__name__)
@property
def wrap(self):
if not hasattr(self, cach_attr):
value = func(self)
if value is not None:
setattr(self, cach_attr, value)
return getattr(self, cach_attr, None)
return wrap
def cli(*args, **kwargs):
def decorator(func):
class Parser(ArgumentParser):
def handle(self, *args, **kwargs):
try:
func(*args, **kwargs)
except Exception, e:
self.error(e.message)
# No catching of exceptions
def handle_raw(self, *args, **kwargs):
func(*args, **kwargs)
return Parser(*args, **kwargs)
return decorator
| from argparse import ArgumentParser
def cached_property(func):
cach_attr = '_{}'.format(func.__name__)
@property
def wrap(self):
if not hasattr(self, cach_attr):
value = func(self)
if value is not None:
setattr(self, cach_attr, value)
return getattr(self, cach_attr, None)
return wrap
def cli(*args, **kwargs):
def decorator(func):
class Parser(ArgumentParser):
def handle(self, *args, **kwargs):
try:
func(*args, **kwargs)
except Exception, e:
self.error(e.message)
return Parser(*args, **kwargs)
return decorator
|
Index should be ones without a category. | from django.http import Http404
from django.views.generic import ListView, DetailView
from faq.models import Question, Category
class FAQQuestionListView(ListView):
context_object_name = "question_list"
template_name = "faq/question_list.html"
def get_queryset(self):
return Question.objects.filter(categories=None)
class FAQQuestionDetailView(DetailView):
context_object_name = 'question'
template_name = 'faq/question_detail.html'
def get_object(self):
return Question.objects.get(slug__iexact=self.kwargs['slug'])
class FAQCategoryListView(ListView):
context_object_name = "category_list"
template_name = "faq/category_list.html"
def get_queryset(self):
return Category.objects.all()
class FAQCategoryDetailView(ListView):
context_object_name = 'question_list'
template_name = "faq/question_list.html"
def get_queryset(self):
try:
self.category = Category.objects.get(slug__iexact=self.kwargs['slug'])
except Category.DoesNotExist:
raise Http404
return Question.objects.get(category=self.category) | from django.http import Http404
from django.views.generic import ListView, DetailView
from faq.models import Question, Category
class FAQQuestionListView(ListView):
context_object_name = "question_list"
template_name = "faq/question_list.html"
def get_queryset(self):
return Question.objects.all()
class FAQQuestionDetailView(DetailView):
context_object_name = 'question'
template_name = 'faq/question_detail.html'
def get_object(self):
return Question.objects.get(slug__iexact=self.kwargs['slug'])
class FAQCategoryListView(ListView):
context_object_name = "category_list"
template_name = "faq/category_list.html"
def get_queryset(self):
return Category.objects.all()
class FAQCategoryDetailView(ListView):
context_object_name = 'question_list'
template_name = "faq/question_list.html"
def get_queryset(self):
try:
self.category = Category.objects.get(slug__iexact=self.kwargs['slug'])
except Category.DoesNotExist:
raise Http404
return Question.objects.get(category=self.category) |
Make using enter valid for submitting searches | function registerHeader(doc){
class WuZhuHeader extends HTMLElement {
createdCallback(){
this._root = this.createShadowRoot();
this._template = doc.querySelector('#headerTemplate');
this._root.appendChild(doc.importNode(this._template.content, true));
this._menu = this._root.querySelector('a');
this._searchBar = this._root.querySelector('input');
this._handleKeyUp = this._handleKeyUp.bind(this);
this._addEventHandlers();
}
get search(){
return this._searchBar.value;
}
set search(v){
this._searchBar.value = v;
}
_handleClick(evt){
document.dispatchEvent(new Event("toggleNav"));
}
_handleInput(evt){
document.dispatchEvent(new CustomEvent("search", {detail: evt.target.value}));
}
_handleKeyUp(evt){
if (evt.keyCode === 13){
this._handleInput(evt);
}
return true;
}
_addEventHandlers(){
this._menu.addEventListener('click', this._handleClick);
this._searchBar.addEventListener('input', this._handleInput);
this._searchBar.addEventListener('keyup', this._handleKeyUp);
}
}
document.registerElement("wuzhu-header", WuZhuHeader);
} | function registerHeader(doc){
class WuZhuHeader extends HTMLElement {
createdCallback(){
this._root = this.createShadowRoot();
this._template = doc.querySelector('#headerTemplate');
this._root.appendChild(doc.importNode(this._template.content, true));
this._menu = this._root.querySelector('a');
this._searchBar = this._root.querySelector('input');
this._addEventHandlers();
}
get search(){
return this._searchBar.value;
}
set search(v){
this._searchBar.value = v;
}
_handleClick(evt){
document.dispatchEvent(new Event("toggleNav"));
}
_handleInput(evt){
document.dispatchEvent(new CustomEvent("search", {detail: evt.target.value}));
}
_addEventHandlers(){
this._menu.addEventListener('click', this._handleClick);
this._searchBar.addEventListener('input', this._handleInput);
}
}
document.registerElement("wuzhu-header", WuZhuHeader);
} |
Fix tests for older envs. | import test from 'tape';
import _ from 'lodash';
import { methods, isStamp } from '../';
test('methods()', nest => {
const a = { a: () => {} };
const b = { b: () => {} };
const c = { c: () => {} };
nest.test('...with no arguments', assert => {
const actual = isStamp(methods());
const expected = true;
assert.equal(actual, expected,
'should return a stamp');
assert.end();
});
nest.test('...with a single object', assert => {
const actual = methods(a).compose.methods.a;
const expected = a.a;
assert.equal(actual, expected,
'should add a single method');
assert.end();
});
nest.test('...with multiple arguments', assert => {
const actual = methods(a, b, c).compose.methods;
const expected = {a: a.a, b: b.b, c: c.c};
assert.deepEqual(actual, expected,
'should add all arguments');
assert.end();
});
nest.test('...creating instance', assert => {
const abc = _.assign(a, b, c);
const actual = Object.getPrototypeOf(methods(abc)());
const expected = abc;
assert.deepEqual(actual, expected,
'should have all methods');
assert.end();
});
});
| import test from 'tape';
import { methods, isStamp } from '../';
test('methods()', nest => {
const a = { a: () => {} };
const b = { b: () => {} };
const c = { c: () => {} };
nest.test('...with no arguments', assert => {
const actual = isStamp(methods());
const expected = true;
assert.equal(actual, expected,
'should return a stamp');
assert.end();
});
nest.test('...with a single object', assert => {
const actual = methods(a).compose.methods.a;
const expected = a.a;
assert.equal(actual, expected,
'should add a single method');
assert.end();
});
nest.test('...with multiple arguments', assert => {
const actual = methods(a, b, c).compose.methods;
const expected = {a: a.a, b: b.b, c: c.c};
assert.deepEqual(actual, expected,
'should add all arguments');
assert.end();
});
nest.test('...creating instance', assert => {
const abc = Object.assign(a, b, c);
const actual = Object.getPrototypeOf(methods(abc)());
const expected = abc;
assert.deepEqual(actual, expected,
'should have all methods');
assert.end();
});
});
|
Add more test cases for sync | <?php
/**
* This file is part of the Tarantool Client package.
*
* (c) Eugene Leonovich <gen.work@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Tarantool\Client\Tests\Integration;
use Tarantool\Client\Request\PingRequest;
final class PacketSyncTest extends TestCase
{
/**
* @dataProvider provideValidSync
*/
public function testSameSync(int $sync) : void
{
$handler = $this->client->getHandler();
$connection = $handler->getConnection();
$packer = $handler->getPacker();
$packet = $packer->pack(new PingRequest(), $sync);
$connection->open();
$packet = $connection->send($packet);
$response = $packer->unpack($packet);
self::assertSame($sync, $response->getSync());
}
public function provideValidSync() : iterable
{
return [
[0],
[127],
[255],
[65535],
[4294967295],
[9223372036854775807], // PHP_INT_MAX
];
}
}
| <?php
/**
* This file is part of the Tarantool Client package.
*
* (c) Eugene Leonovich <gen.work@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Tarantool\Client\Tests\Integration;
use Tarantool\Client\Request\PingRequest;
final class PacketSyncTest extends TestCase
{
/**
* @dataProvider provideValidSync
*/
public function testSameSync(int $sync) : void
{
$handler = $this->client->getHandler();
$connection = $handler->getConnection();
$packer = $handler->getPacker();
$packet = $packer->pack(new PingRequest(), $sync);
$connection->open();
$packet = $connection->send($packet);
$response = $packer->unpack($packet);
self::assertSame($sync, $response->getSync());
}
public function provideValidSync() : iterable
{
return [
[0],
[128],
[65535],
[4294967295],
[9223372036854775807], // PHP_INT_MAX
];
}
}
|
Change tasks key prefix to jobs.duration | """
sentry.tasks.base
~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from celery.task import task
from django_statsd.clients import statsd
from functools import wraps
def instrumented_task(name, queue, stat_suffix=None, **kwargs):
statsd_key = 'jobs.duration.{name}'.format(name=name)
if stat_suffix:
statsd_key += '.{key}'.format(key=stat_suffix)
def wrapped(func):
@wraps(func)
def _wrapped(*args, **kwargs):
with statsd.timer(statsd_key):
return func(*args, **kwargs)
return task(name=name, queue=queue, **kwargs)(func)
return wrapped
| """
sentry.tasks.base
~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from celery.task import task
from django_statsd.clients import statsd
from functools import wraps
def instrumented_task(name, queue, stat_suffix=None, **kwargs):
statsd_key = 'tasks.{name}'.format(name=name)
if stat_suffix:
statsd_key += '.{key}'.format(key=stat_suffix)
def wrapped(func):
@wraps(func)
def _wrapped(*args, **kwargs):
with statsd.timer(statsd_key):
return func(*args, **kwargs)
return task(name=name, queue=queue, **kwargs)(func)
return wrapped
|
Fix topn metric view regression on PyTorch 1.7 | """ Eval metrics and related
Hacked together by / Copyright 2020 Ross Wightman
"""
class AverageMeter:
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def accuracy(output, target, topk=(1,)):
"""Computes the accuracy over the k top predictions for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.reshape(1, -1).expand_as(pred))
return [correct[:k].reshape(-1).float().sum(0) * 100. / batch_size for k in topk]
| """ Eval metrics and related
Hacked together by / Copyright 2020 Ross Wightman
"""
class AverageMeter:
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def accuracy(output, target, topk=(1,)):
"""Computes the accuracy over the k top predictions for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
return [correct[:k].view(-1).float().sum(0) * 100. / batch_size for k in topk]
|
Add ply, stl and 3ds support to blendel_2cloud.py. | import os
import sys
import bpy
# file loader per extension
loader_factory = {
'.ply': lambda file: bpy.ops.import_mesh.ply(filepath=file),
'.stl': lambda file: bpy.ops.import_mesh.stl(filepath=file),
'.3ds': lambda file: bpy.ops.import_scene.autodesk_3ds(filepath=file, axis_forward='Y', axis_up='Z'),
'.obj': lambda file: bpy.ops.import_scene.obj(filepath=file, axis_forward='Y', axis_up='Z'),
'.wrl': lambda file: bpy.ops.import_scene.x3d(filepath=file, axis_forward='Y', axis_up='Z')
}
def convert(input_filename, output_filename):
"convert a file to a qc file."
ext = os.path.splitext(input_filename)[1]
try:
loader = loader_factory[ext]
except KeyError:
raise RuntimeError('%s is not supported' % ext)
loader(input_filename)
bpy.ops.export_scene.qc(filepath=output_filename)
def main():
argv = sys.argv
argv = argv[argv.index("--") + 1:] # get all args after "--"
fbx_in = argv[0]
fbx_out = argv[1]
convert(fbx_in, fbx_out)
if __name__ == '__main__':
main()
| import os
import sys
import bpy
# file loader per extension
loader_factory = {
'.obj': lambda file: bpy.ops.import_scene.obj(filepath=file, axis_forward='Y', axis_up='Z'),
'.wrl': lambda file: bpy.ops.import_scene.x3d(filepath=file, axis_forward='Y', axis_up='Z')
}
def convert(input_filename, output_filename):
"convert a file to a qc file."
ext = os.path.splitext(input_filename)[1]
try:
loader = loader_factory[ext]
except KeyError:
raise RuntimeError('%s is not supported' % ext)
loader(input_filename)
bpy.ops.export_scene.qc(filepath=output_filename)
def main():
argv = sys.argv
argv = argv[argv.index("--") + 1:] # get all args after "--"
fbx_in = argv[0]
fbx_out = argv[1]
convert(fbx_in, fbx_out)
if __name__ == '__main__':
main()
|
Use same version of messytables as in requirements
Also pin the version too as it is in requirements.txt. | from setuptools import setup, find_packages
long_desc = """
XYPath is aiming to be XPath for spreadsheets: it offers a framework for
navigating around and extracting values from tabular data.
"""
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers for classifiers
setup(
name='xypath',
version='1.0.12',
description="Extract fields from tabular data with complex expressions.",
long_description=long_desc,
classifiers=[
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: POSIX :: Linux",
"Programming Language :: Python",
],
keywords='',
author='The Sensible Code Company Ltd',
author_email='feedback@sensiblecode.io',
url='http://sensiblecode.io',
license='BSD',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
namespace_packages=[],
include_package_data=False,
zip_safe=False,
install_requires=[
'messytables==0.15',
],
tests_require=[],
entry_points=\
"""
""",
)
| from setuptools import setup, find_packages
long_desc = """
XYPath is aiming to be XPath for spreadsheets: it offers a framework for
navigating around and extracting values from tabular data.
"""
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers for classifiers
setup(
name='xypath',
version='1.0.12',
description="Extract fields from tabular data with complex expressions.",
long_description=long_desc,
classifiers=[
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: POSIX :: Linux",
"Programming Language :: Python",
],
keywords='',
author='The Sensible Code Company Ltd',
author_email='feedback@sensiblecode.io',
url='http://sensiblecode.io',
license='BSD',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
namespace_packages=[],
include_package_data=False,
zip_safe=False,
install_requires=[
'messytables>=0.14.5',
],
tests_require=[],
entry_points=\
"""
""",
)
|
[Chore] Add __text satitization to price and image_link | /**
* Sanitize values
*
* @param {String | Array<string>} value The value to be sanitized
* @param {Object} sanitize A sanitization type from sanitizer
* @return {String | Array<string>}
*/
const valueSanitizer = (key, value, sanitize) => {
switch (key) {
case 'image_link':
case 'images':
case 'categories':
return sanitize.arrays(value);
case 'id': {
const sanitizeTexts = sanitize.__texts(value);
const sanitizeUnderscores = sanitize.underscore(sanitizeTexts);
return sanitizeUnderscores;
}
case 'price':
return sanitize.__texts(value);
case 'installment':
return sanitize.installment(value);
case 'sku':
return sanitize.underscore(value);
default:
}
return value;
};
module.exports = valueSanitizer;
| /**
* Sanitize values
*
* @param {String | Array<string>} value The value to be sanitized
* @param {Object} sanitize A sanitization type from sanitizer
* @return {String | Array<string>}
*/
const valueSanitizer = (key, value, sanitize) => {
switch (key) {
// case 'image_link': TODO: Check if a sanitized 'image_link' field get here as it should
case 'images':
case 'categories':
return sanitize.arrays(value);
case 'id': {
const sanitizeTexts = sanitize.__texts(value);
const sanitizeUnderscores = sanitize.underscore(sanitizeTexts);
return sanitizeUnderscores;
}
case 'installment':
return sanitize.installment(value);
case 'sku':
return sanitize.underscore(value);
default:
}
return value;
};
module.exports = valueSanitizer;
|
Fix problem edit_component not shown in list if invisible
It's done like with mail_editable. | <?php
class Kwc_Editable_ComponentsModel extends Kwf_Model_Data_Abstract
{
public function __construct(array $config = array())
{
$data = array();
$components = Kwf_Component_Data_Root::getInstance()
->getComponentsByClass(array('Kwc_Editable_Component', 'Kwc_Editable_Trl_Component'), array('ignoreVisible' => true));
$user = Kwf_Registry::get('userModel')->getAuthedUser();
foreach ($components as $c) {
if (Kwf_Registry::get('acl')->getComponentAcl()->isAllowed($user, $c)) {
$data[] = array(
'id' => $c->dbId,
'name' => $c->getComponent()->getNameForEdit(),
'content_component_class' => $c->getChildComponent('-content')->componentClass,
);
}
}
$this->_data = $data;
parent::__construct($config);
}
}
| <?php
class Kwc_Editable_ComponentsModel extends Kwf_Model_Data_Abstract
{
public function __construct(array $config = array())
{
$data = array();
$components = Kwf_Component_Data_Root::getInstance()
->getComponentsByClass(array('Kwc_Editable_Component', 'Kwc_Editable_Trl_Component'));
$user = Kwf_Registry::get('userModel')->getAuthedUser();
foreach ($components as $c) {
if (Kwf_Registry::get('acl')->getComponentAcl()->isAllowed($user, $c)) {
$data[] = array(
'id' => $c->dbId,
'name' => $c->getComponent()->getNameForEdit(),
'content_component_class' => $c->getChildComponent('-content')->componentClass,
);
}
}
$this->_data = $data;
parent::__construct($config);
}
}
|
FIX test for Windows platform. | from __future__ import with_statement
import os.path
import tempfile
from nose.tools import *
from behave import configuration
# one entry of each kind handled
TEST_CONFIG='''[behave]
outfile=/tmp/spam
paths = /absolute/path
relative/path
tags = @foo,~@bar
@zap
format=pretty
tag-counter
stdout_capture=no
bogus=spam
'''
class TestConfiguration(object):
def test_read_file(self):
tn = tempfile.mktemp()
with open(tn, 'w') as f:
f.write(TEST_CONFIG)
d = configuration.read_configuration(tn)
eq_(d['outfile'], '/tmp/spam')
eq_(d['paths'], [
os.path.normpath('/absolute/path'), # -- WINDOWS-REQUIRES: normpath
os.path.normpath(os.path.join(os.path.dirname(tn), 'relative/path')),
])
eq_(d['format'], ['pretty', 'tag-counter'])
eq_(d['tags'], ['@foo,~@bar', '@zap'])
eq_(d['stdout_capture'], False)
ok_('bogus' not in d)
| from __future__ import with_statement
import os.path
import tempfile
from nose.tools import *
from behave import configuration
# one entry of each kind handled
TEST_CONFIG='''[behave]
outfile=/tmp/spam
paths = /absolute/path
relative/path
tags = @foo,~@bar
@zap
format=pretty
tag-counter
stdout_capture=no
bogus=spam
'''
class TestConfiguration(object):
def test_read_file(self):
tn = tempfile.mktemp()
with open(tn, 'w') as f:
f.write(TEST_CONFIG)
d = configuration.read_configuration(tn)
eq_(d['outfile'], '/tmp/spam')
eq_(d['paths'], [
'/absolute/path',
os.path.normpath(os.path.join(os.path.dirname(tn), 'relative/path')),
])
eq_(d['format'], ['pretty', 'tag-counter'])
eq_(d['tags'], ['@foo,~@bar', '@zap'])
eq_(d['stdout_capture'], False)
ok_('bogus' not in d)
|
Add ul tag before li to prevent left align text | <?php if (isset($msg)): ?>
<?php foreach ($msg as $type=>$list): ?>
<div class="single panel <?php echo $type; ?>">
<div class="warp">
<div>
<b><?php echo strtoupper($type); ?>!</b>
</div>
<ul>
<?php foreach ($list as $value): ?>
<li><?php echo $value; ?></li>
<?php endforeach; ?>
</ul>
</div>
</div>
<?php endforeach; ?>
<?php endif; ?>
| <?php if (isset($msg)): ?>
<?php foreach ($msg as $type=>$list): ?>
<div class="single panel <?php echo $type; ?>">
<div class="warp">
<div>
<b><?php echo strtoupper($type); ?>!</b>
</div>
<?php foreach ($list as $value): ?>
<li><?php echo $value; ?></li>
<?php endforeach; ?>
</div>
</div>
<?php endforeach; ?>
<?php endif; ?>
|
Fix syntax of generated == | const R = require('ramda')
const indentLines = require('./utils/indentLines')
const associatedNamesForCase = require('./utils/associatedNamesForCase')
const equatesForAssociatedNames = R.pipe(
R.map((associatedName) => `l.${associatedName} == r.${associatedName}`),
R.join(' && ')
)
const equatesForCase = R.converge((name, associatedNames) => (
!R.isEmpty(associatedNames) ? ([
`case let (.${name}(l), .${name}(r)):`,
`\treturn ${ equatesForAssociatedNames(associatedNames) }`
]) : ([
`case let (.${name}, .${name}):`,
`\treturn true`
])
), [
R.prop('name'),
associatedNamesForCase
])
const equatesFuncForEnum = R.converge(
(enumName, innerLines) => R.flatten([
`public func == (lhs: ${enumName}, rhs: ${enumName}) -> Bool {`,
'\tswitch (lhs, rhs) {',
indentLines(innerLines),
'default:',
'\treturn false',
'\t}',
'}'
]), [
R.prop('name'),
R.pipe(
R.prop('cases'),
R.map(equatesForCase),
R.flatten
)
]
)
module.exports = {
equatesFuncForEnum
}
| const R = require('ramda')
const indentLines = require('./utils/indentLines')
const associatedNamesForCase = require('./utils/associatedNamesForCase')
const equatesForAssociatedNames = R.pipe(
R.map((associatedName) => `l.${associatedName} == r.${associatedName}`),
R.join(' && ')
)
const equatesForCase = R.converge((name, associatedNames) => (
!R.isEmpty(associatedNames) ? ([
`case let (.${name}(l), .${name}(r)):`,
`\treturn ${ equatesForAssociatedNames(associatedNames) }`
]) : ([
`case let (.${name}, .${name}):`,
`\treturn true`
])
), [
R.prop('name'),
associatedNamesForCase
])
const equatesFuncForEnum = R.converge(
(enumName, innerLines) => R.flatten([
`public func == (lhs: ${enumName}, rhs: ${enumName}) {`,
'\tswitch (lhs, rhs) {',
indentLines(innerLines),
'\t}',
'}'
]), [
R.prop('name'),
R.pipe(
R.prop('cases'),
R.map(equatesForCase),
R.flatten
)
]
)
module.exports = {
equatesFuncForEnum
}
|
Revert "WF-1466 Memory Leak Fix Along with config file changes"
This reverts commit 4cd1f6d6fc8b039c31c399ec9c8fb660e71b1eae. | /**
* Copyright (c) 2005-2007 Intalio inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
*/
package org.intalio.tempo.workflow.dao;
import javax.persistence.EntityManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
enum ACTION {
BEGIN,
CLOSE,
LOAD,
COMMIT,
ROLLBACK,
CLEAR
}
/**
* Common class for JPA-based connection
*/
public class AbstractJPAConnection {
protected Logger _logger;
protected EntityManager entityManager;
public AbstractJPAConnection(EntityManager createEntityManager) {
_logger = LoggerFactory.getLogger(this.getClass());
_logger.debug(ACTION.LOAD.toString());
entityManager = createEntityManager;
}
public void close() {
// commit();
_logger.debug(ACTION.CLOSE.toString());
}
public void checkTransactionIsActive() {
if (!entityManager.getTransaction().isActive()) {
_logger.debug(ACTION.BEGIN.toString());
entityManager.getTransaction().begin();
}
}
public void commit() {
if (entityManager.getTransaction().isActive()) {
_logger.debug(ACTION.COMMIT.toString());
entityManager.getTransaction().commit();
}
}
}
| /**
* Copyright (c) 2005-2007 Intalio inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
*/
package org.intalio.tempo.workflow.dao;
import javax.persistence.EntityManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
enum ACTION {
BEGIN,
CLOSE,
LOAD,
COMMIT,
ROLLBACK,
CLEAR
}
/**
* Common class for JPA-based connection
*/
public class AbstractJPAConnection {
protected Logger _logger;
protected EntityManager entityManager;
public AbstractJPAConnection(EntityManager createEntityManager) {
_logger = LoggerFactory.getLogger(this.getClass());
_logger.debug(ACTION.LOAD.toString());
entityManager = createEntityManager;
}
public void close() {
// commit();
entityManager.close();
_logger.debug(ACTION.CLOSE.toString());
}
public void checkTransactionIsActive() {
if (!entityManager.getTransaction().isActive()) {
_logger.debug(ACTION.BEGIN.toString());
entityManager.getTransaction().begin();
}
}
public void commit() {
if (entityManager.getTransaction().isActive()) {
_logger.debug(ACTION.COMMIT.toString());
entityManager.getTransaction().commit();
}
}
}
|
Change version to 1.0.1 unstable | # -*- coding: utf-8 -*-
{
"name": "Account Credit Transfer",
"version": "1.0.1",
"author": "XCG Consulting",
"website": "http://www.openerp-experts.com",
"category": 'Accounting',
"description": """Account Voucher Credit Transfer Payment.
You need to set up some things before using it.
A credit transfer config link a bank with a parser
A credit transfer parser link a parser with a template that you can upload
""",
"depends": [
'base',
'account_streamline',
],
"data": [
"security/ir.model.access.csv",
"views/config.xml",
"views/parser.xml",
"views/res.bank.xml",
],
'demo_xml': [],
'test': [],
'installable': True,
'active': False,
'external_dependencies': {
'python': ['genshi']
}
}
| # -*- coding: utf-8 -*-
{
"name": "Account Credit Transfer",
"version": "1.0",
"author": "XCG Consulting",
"website": "http://www.openerp-experts.com",
"category": 'Accounting',
"description": """Account Voucher Credit Transfer Payment.
You need to set up some things before using it.
A credit transfer config link a bank with a parser
A credit transfer parser link a parser with a template that you can upload
""",
"depends": [
'base',
'account_streamline',
],
"data": [
"security/ir.model.access.csv",
"views/config.xml",
"views/parser.xml",
"views/res.bank.xml",
],
'demo_xml': [],
'test': [],
'installable': True,
'active': False,
'external_dependencies': {
'python': ['genshi']
}
}
|
Allow --ca parameter to specify trust store | #!/usr/bin/env python
"""Verify a certificate."""
import argparse
import logging
import sys
import certifi
from OpenSSL import crypto
from py509.x509 import load_x509_certificates
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--ca', required=False, default=certifi.where())
args = parser.parse_args()
trust_store = []
with open(args.ca) as fh:
trust_store = list(load_x509_certificates(fh.read()))
x509store = crypto.X509Store()
for ca in trust_store:
print ca.get_subject()
x509store.add_cert(ca)
x509cert = crypto.load_certificate(crypto.FILETYPE_PEM, sys.stdin.read())
try:
crypto.X509StoreContext(x509store, x509cert).verify_certificate()
print 'Success'
except crypto.X509StoreContextError as e:
print 'Failed on {0}'.format(e.certificate.get_subject())
print 'Issuer {0}'.format(e.certificate.get_issuer())
print 'Message: {0}'.format(e)
| #!/usr/bin/env python
"""Verify a certificate."""
import argparse
import logging
import sys
import certifi
from OpenSSL import crypto
from py509.x509 import load_x509_certificates
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
def main():
trust_store = []
with open(certifi.where()) as fh:
#with open('/Users/sholsapp/workspace/py509/test.pem') as fh:
trust_store = list(load_x509_certificates(fh.read()))
x509store = crypto.X509Store()
for ca in trust_store:
print ca.get_subject()
x509store.add_cert(ca)
x509cert = crypto.load_certificate(crypto.FILETYPE_PEM, sys.stdin.read())
try:
crypto.X509StoreContext(x509store, x509cert).verify_certificate()
print 'Success'
except crypto.X509StoreContextError as e:
print 'Failed on {0}'.format(e.certificate.get_subject())
print 'Issuer {0}'.format(e.certificate.get_issuer())
print 'Message: {0}'.format(e)
|
Use the correct env variable name | # -*- coding: utf-8 -*-
import os
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy import API
from tweepy.streaming import StreamListener
from listener import Listener
ckey = os.environ['CKEY']
consumer_secret = os.environ['CONSUMER_SECRET']
access_token_key = os.environ['ACCESS_TOKEN_KEY']
access_token_secret = os.environ['ACCESS_TOKEN_SECRET']
keywords = [
u"كيماوي",
u"غاز سام",
u"كلور",
u"اختناق",
u"سام",
u"غازات سامة",
u"الكلور",
u"الكيماوي",
u"الاختناق",
u"الغازات السامة",
u"السام"
]
def call():
auth = OAuthHandler(ckey, consumer_secret)
auth.set_access_token(access_token_key, access_token_secret)
print "Connecting to Twitter Streaming API..."
api = API(auth)
print "Done."
# initialize Stream object
twitterStream = Stream(auth, Listener(api))
# call filter on Stream object
twitterStream.filter(track=keywords, languages=["ar"])
| # -*- coding: utf-8 -*-
import os
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy import API
from tweepy.streaming import StreamListener
from listener import Listener
ckey = os.environ['CKEY']
consumer_secret = os.environ['CONSUMER_KEY']
access_token_key = os.environ['ACCESS_TOKEN_KEY']
access_token_secret = os.environ['ACCESS_TOKEN_SECRET']
keywords = [
u"كيماوي",
u"غاز سام",
u"كلور",
u"اختناق",
u"سام",
u"غازات سامة",
u"الكلور",
u"الكيماوي",
u"الاختناق",
u"الغازات السامة",
u"السام"
]
def call():
auth = OAuthHandler(ckey, consumer_secret)
auth.set_access_token(access_token_key, access_token_secret)
print "Connecting to Twitter Streaming API..."
api = API(auth)
print "Done."
# initialize Stream object
twitterStream = Stream(auth, Listener(api))
# call filter on Stream object
twitterStream.filter(track=keywords, languages=["ar"])
|
Use a spread instead of Array.from | import builder from 'xmlbuilder';
import kebabCase from 'lodash/kebabCase';
// custom stringify options for xml builder
// just kebab-cases all attributes and tag names
const customStringifyOptions = {
eleName(val = '') {
return this.assertLegalChar(kebabCase(val));
},
attName(val = '') {
return kebabCase(val);
},
};
/**
* Recursively turns jsx children into xml nodes
* @param {Array} children
* @param {XMLNode} node
*/
function renderNode(node, children = []) {
[...children].forEach(child => {
if (child && child.tag) {
node.ele(child.tag, child.props);
renderNode(child.children, node);
node.end();
} else {
node.text(child);
}
});
}
/**
* Nested JSON to pretty string
* @param {Object} data
* @return {String}
*/
export default function renderToString({ tag, children }, options = {}) {
if (tag !== 'speak') {
throw new Error(`SSML must start with a 'speak' tag, currently '${tag}'`);
}
const xml = builder.create(tag, {
stringify: customStringifyOptions,
headless: true,
});
renderNode(xml, children);
return xml.end(options);
}
| import builder from 'xmlbuilder';
import kebabCase from 'lodash/kebabCase';
// custom stringify options for xml builder
// just kebab-cases all attributes and tag names
const customStringifyOptions = {
eleName(val = '') {
return this.assertLegalChar(kebabCase(val));
},
attName(val = '') {
return kebabCase(val);
},
};
/**
* Recursively turns jsx children into xml nodes
* @param {Array} children
* @param {XMLNode} node
*/
function renderNode(node, children = []) {
Array.from(children).forEach(child => {
if (child && child.tag) {
node.ele(child.tag, child.props);
renderNode(child.children, node);
node.end();
} else {
node.text(child);
}
});
}
/**
* Nested JSON to pretty string
* @param {Object} data
* @return {String}
*/
export default function renderToString({ tag, children }, options = {}) {
if (tag !== 'speak') {
throw new Error(`SSML must start with a 'speak' tag, currently '${tag}'`);
}
const xml = builder.create(tag, {
stringify: customStringifyOptions,
headless: true,
});
renderNode(xml, children);
return xml.end(options);
}
|
Create internal.js config for javascript library test | <?php
class CM_Response_Resource_Javascript_LibraryTest extends CMTest_TestCase {
/** @var CM_File */
private $_configInternalFile;
protected function setUp() {
CMTest_TH::createLanguage();
$this->_configInternalFile = new CM_File(DIR_ROOT . 'resources/config/js/internal.js');
$this->_configInternalFile->write('console.log("hello world")');
}
protected function tearDown() {
CMTest_TH::clearEnv();
$this->_configInternalFile->delete();
}
public function testProcessLibrary() {
$render = new CM_Frontend_Render(new CM_Frontend_Environment());
$request = new CM_Request_Get($render->getUrlResource('library-js', 'library.js'));
$response = new CM_Response_Resource_Javascript_Library($request);
$response->process();
$this->assertContains('function()', $response->getContent());
}
public function testProcessTranslations() {
$render = new CM_Frontend_Render(new CM_Frontend_Environment());
$request = new CM_Request_Get($render->getUrlResource('library-js', 'translations/123.js'));
$response = new CM_Response_Resource_Javascript_Library($request);
$response->process();
$this->assertContains('cm.language.setAll', $response->getContent());
}
}
| <?php
class CM_Response_Resource_Javascript_LibraryTest extends CMTest_TestCase {
protected function setUp() {
CMTest_TH::createLanguage();
}
protected function tearDown() {
CMTest_TH::clearEnv();
}
public function testProcessLibrary() {
$render = new CM_Frontend_Render(new CM_Frontend_Environment());
$request = new CM_Request_Get($render->getUrlResource('library-js', 'library.js'));
$response = new CM_Response_Resource_Javascript_Library($request);
$response->process();
$this->assertContains('function()', $response->getContent());
}
public function testProcessTranslations() {
$render = new CM_Frontend_Render(new CM_Frontend_Environment());
$request = new CM_Request_Get($render->getUrlResource('library-js', 'translations/123.js'));
$response = new CM_Response_Resource_Javascript_Library($request);
$response->process();
$this->assertContains('cm.language.setAll', $response->getContent());
}
}
|
Fix error in service provider.. | <?php
namespace EGALL\Transformer;
use Illuminate\Support\ServiceProvider;
use EGALL\Transformer\Contracts\Transformer as TransformerContract;
use EGALL\Transformer\Contracts\CollectionTransformer as CollectionTransformerContract;
/**
* Transformer service provider.
*
* @package EGALL\Transformer
* @author Erik Galloway <erik@mybarnapp.com>
*/
class TransformerServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->app->bind(TransformerContract::class, Transformer::class);
$this->app->bind(CollectionTransformerContract::class, CollectionTransformer::class);
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return [TransformerContract::class, CollectionTransformerContract::class];
}
}
| <?php
namespace EGALL\Transformer;
use Illuminate\Support\ServiceProvider;
use EGALL\Transformer\Contracts\Transformer as TransformerContract;
use EGALL\Transformer\Contracts\CollectionTransformer as CollectionTransformerContract;
/**
* Transformer service provider.
*
* @package EGALL\Transformer
* @author Erik Galloway <erik@mybarnapp.com>
*/
class TransformerServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->app->bind(TransformerContract::class, Transformer::class);
$this->app->bind(CollectionTransformerContract::class, CollectionTransformer::class);
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return [Transformer::class, CollectionTransformer::class];
}
}
|
Add the SQLite configuration entry example | <?php
/**
* Database configuration
*
* @author David Carr - dave@daveismyname.com
* @author Edwin Hoksberg - info@edwinhoksberg.nl
* @author Virgil-Adrian Teaca - virgil@giulianaeassociati.com
* @version 3.0
*/
use Core\Config;
/**
* Setup the Database configuration.
*/
Config::set('database', array(
'default' => array(
'driver' => DB_TYPE,
'hostname' => DB_HOST,
'database' => DB_NAME,
'username' => DB_USER,
'password' => DB_PASS,
'prefix' => PREFIX,
'charset' => 'utf8',
'collation' => 'utf8_general_ci',
),
'custom' => array(
'driver' => 'sqlite',
'database' => APPDIR .'Storage' .DS .'database.sqlite',
'prefix' => PREFIX,
'charset' => 'utf8',
'collation' => 'utf8_general_ci',
),
));
| <?php
/**
* Database configuration
*
* @author David Carr - dave@daveismyname.com
* @author Edwin Hoksberg - info@edwinhoksberg.nl
* @author Virgil-Adrian Teaca - virgil@giulianaeassociati.com
* @version 3.0
*/
use Core\Config;
/**
* Setup the Database configuration.
*/
Config::set('database', array(
'default' => array(
'driver' => DB_TYPE,
'hostname' => DB_HOST,
'database' => DB_NAME,
'username' => DB_USER,
'password' => DB_PASS,
'prefix' => PREFIX,
'charset' => 'utf8',
'collation' => 'utf8_general_ci',
),
)); |
FIX Delete board now hit API | import { GET_ALL_BOARDS, ADD_BOARD, DELETE_BOARD } from './constants'
export const getAllBoards = () => (dispatch) => {
dispatch({
type: GET_ALL_BOARDS,
payload: {
request: {
method: 'GET',
url: '/api/boards',
},
},
})
}
export const addBoard = () => (dispatch) => {
dispatch({
type: ADD_BOARD,
payload: {
request: {
method: 'POST',
url: '/api/boards/',
data: {
title: 'New board',
},
},
},
})
}
export const deleteBoard = (boardId) => (dispatch) => {
dispatch({
type: DELETE_BOARD,
boardId,
payload: {
request: {
method: 'DELETE',
url: `/api/boards/${boardId}`,
},
},
})
} | import { GET_ALL_BOARDS, ADD_BOARD, DELETE_BOARD } from './constants'
export const getAllBoards = () => (dispatch) => {
dispatch({
type: GET_ALL_BOARDS,
payload: {
request: {
method: 'GET',
url: '/api/boards',
},
},
})
}
export const addBoard = () => (dispatch) => {
dispatch({
type: ADD_BOARD,
payload: {
request: {
method: 'POST',
url: '/api/boards/',
data: {
title: 'New board',
},
},
},
})
}
export const deleteBoard = (boardId) => (dispatch) => {
dispatch({
type: DELETE_BOARD,
boardId,
payload: {
request: {
method: 'DELETE',
url: `/boards/${boardId}`,
},
},
})
} |
Add a test for controllers | describe('Sock object', function() {
var socket;
var pong;
var joinRoom;
beforeEach(function() {
});
afterEach(function() {
});
it('should exist', function() {
expect(window.Tilt.Sock).toBeDefined();
});
it('should connect and return a new sock object', function() {
expect(window.Tilt.connect('10.0.0.1') instanceof window.Tilt.Sock).toBeTruthy();
});
describe('for games', function() {
it('should emit messages', function() {
var s = window.Tilt.connect('10.0.0.1');
s.emit('cntID', 'msgname', 'argblah');
var emits = io.mockGetFunctionCalls('emit');
expect(emits[emits.length - 1]).toEqual(['msg', 'cntID', ['msgname', 'argblah']]);
});
});
describe('for controllers', function() {
it('should emit messages', function() {
var s = window.Tilt.connect('10.0.0.1', 'gameidhere');
s.emit('msgname', 'argblah');
var emits = io.mockGetFunctionCalls('emit');
expect(emits[emits.length - 1]).toEqual(['msg', ['msgname', 'argblah']]);
});
});
}); | describe('Sock object', function() {
var socket;
var pong;
var joinRoom;
beforeEach(function() {
});
afterEach(function() {
});
it('should exist', function() {
expect(window.Tilt.Sock).toBeDefined();
});
it('should connect and return a new sock object', function() {
expect(window.Tilt.connect('10.0.0.1') instanceof window.Tilt.Sock).toBeTruthy();
});
describe('for games', function() {
it('should emit messages', function() {
var s = window.Tilt.connect('10.0.0.1');
s.emit('cntID', 'msgname', 'argblah');
var emits = io.mockGetFunctionCalls('emit');
expect(emits[emits.length - 1]).toEqual(['msg', 'cntID', ['msgname', 'argblah']]);
});
});
}); |
Comment out the second read to the database for debug purposes
I retain it just in case weird stuff happens to the database again, but we
certainly don't need to read it again. | // Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.controllers' is found in controllers.js
angular.module('starter',['ionic', 'starter.controllers', 'starter.directives', 'leaflet-directive'])
.config(function($ionicConfigProvider) {
// note that you can also chain configs
$ionicConfigProvider.tabs.position('bottom');
})
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
/*
BEGIN DEVICE VERSION
var db = window.sqlitePlugin.openDatabase({name: "userCacheDB", location: 0, createFromLocation: 1});
UserCacheHelper.getDocument(db, "diary/trips", function(tripListArray) {
console.log("In main, tripListArray has = "+tripListArray.length+" entries");
tripListStr = tripListArray[0];
tripList = JSON.parse(tripListStr)
console.log("In main, tripList has "+tripList.length+" entries");
// console.log("In main, first entry is "+JSON.stringify(tripList[0]));
});
*/
});
})
| // Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.controllers' is found in controllers.js
angular.module('starter',['ionic', 'starter.controllers', 'starter.directives'])
.config(function($ionicConfigProvider) {
// note that you can also chain configs
$ionicConfigProvider.tabs.position('bottom');
})
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
var db = window.sqlitePlugin.openDatabase({name: "TripSections.db", location: 0, createFromLocation: 1});
tripSectionDbHelper.getJSON(db, function(jsonTripList) {
tripList = tripSectionDbHelper.getUncommitedSections(jsonTripList);
console.log("Retrieved trips count = "+tripList.length);
});
});
})
|
Add to download links ng-csv | var path = require('path');
var rootPath = path.normalize(__dirname + '/../../');
module.exports = {
local: {
baseUrl: 'http://localhost:3030',
db: 'mongodb://localhost/rp_local',
rootPath: rootPath,
port: process.env.PORT || 3016
},
staging : {
baseUrl: 'http://dev.resourceprojects.org',
//db: '@aws-us-east-1-portal.14.dblayer.com:10669/rp_dev?ssl=true',
db: '@aws-us-east-1-portal.14.dblayer.com:10669,aws-us-east-1-portal.13.dblayer.com:10499/rp_dev?ssl=true',
rootPath: rootPath,
port: process.env.PORT || 80
}
};
| var path = require('path');
var rootPath = path.normalize(__dirname + '/../../');
module.exports = {
local: {
baseUrl: 'http://localhost:3051',
db: 'mongodb://localhost/rp_local',
rootPath: rootPath,
port: process.env.PORT || 3051
},
staging : {
baseUrl: 'http://dev.resourceprojects.org',
//db: '@aws-us-east-1-portal.14.dblayer.com:10669/rp_dev?ssl=true',
db: '@aws-us-east-1-portal.14.dblayer.com:10669,aws-us-east-1-portal.13.dblayer.com:10499/rp_dev?ssl=true',
rootPath: rootPath,
port: process.env.PORT || 80
}
};
|
Fix undefined function without parameter | <?php
declare(strict_types = 1);
namespace Embed\Detectors;
class Languages extends Detector
{
/**
* @return \Psr\Http\Message\UriInterface[]
*/
public function detect(): array
{
$document = $this->extractor->getDocument();
$languages = [];
foreach ($document->select('.//link[@hreflang]')->nodes() as $node) {
$language = $node->getAttribute('hreflang');
$href = $node->getAttribute('href');
if (self::isEmpty($language) || self::isEmpty($href)) {
continue;
}
$languages[$language] = $this->extractor->resolveUri($href);
}
return $languages;
}
private function isEmpty(string $value): bool
{
$skipValues = array(
'undefined',
);
return empty($value) || in_array($value, $skipValues);
}
}
| <?php
declare(strict_types = 1);
namespace Embed\Detectors;
class Languages extends Detector
{
/**
* @return \Psr\Http\Message\UriInterface[]
*/
public function detect(): array
{
$document = $this->extractor->getDocument();
$languages = [];
foreach ($document->select('.//link[@hreflang]')->nodes() as $node) {
$language = $node->getAttribute('hreflang');
$href = $node->getAttribute('href');
if (isEmpty()) {
continue;
}
$languages[$language] = $this->extractor->resolveUri($href);
}
return $languages;
}
private function isEmpty($value): boolval
{
$skipValues = array(
'undefined',
);
return empty($value) || in_array($value, $skipValues);
}
}
|
Make to_unicode work in Python 3 | # -*- coding: utf-8 -*-
# The following two variables and the is_unicode function are there to bridge string types across Python 2 & 3
unicode_type = u"".__class__
basestring_type = (b"".__class__, unicode_type)
def to_unicode(string):
"""
:param string: a string that needs to be unicoded
:param encoding: a string that represent the encoding type
:return: a unicode string
if the string is a python 2 str type, returns a unicode version of the string.
"""
if not isinstance(string, basestring_type):
string = str(string)
if isinstance(string, unicode_type):
return string
# Next line only gets triggered if the code is run in python 2
return string.decode('utf-8')
class Dummy(object):
"""A class that does nothing
Used by function ``empty_clone`` to create an empty instance from an existing object.
"""
pass
def empty_clone(original):
"""Create a new empty instance of the same class of the original object."""
new = Dummy()
new.__class__ = original.__class__
return new
def stringify_array(array):
"""
Generate a clean string representation of a NumPY array.
"""
return u'[{}]'.format(u', '.join(
to_unicode(cell)
for cell in array
)) if array is not None else u'None'
| # -*- coding: utf-8 -*-
# The following two variables and the is_unicode function are there to bridge string types across Python 2 & 3
unicode_type = u"".__class__
basestring_type = (b"".__class__, unicode_type)
def to_unicode(string):
"""
:param string: a string that needs to be unicoded
:param encoding: a string that represent the encoding type
:return: a unicode string
if the string is a python 2 str type, returns a unicode version of the string.
"""
if not isinstance(string, basestring_type):
string = str(string)
if isinstance(string, unicode_type):
return string
# Next line only gets triggered if the code is run in python 2
return unicode(string, 'utf-8')
class Dummy(object):
"""A class that does nothing
Used by function ``empty_clone`` to create an empty instance from an existing object.
"""
pass
def empty_clone(original):
"""Create a new empty instance of the same class of the original object."""
new = Dummy()
new.__class__ = original.__class__
return new
def stringify_array(array):
"""
Generate a clean string representation of a NumPY array.
"""
return u'[{}]'.format(u', '.join(
to_unicode(cell)
for cell in array
)) if array is not None else u'None'
|
Add initial release to Pypi. | import os
from setuptools import setup, find_packages
version = '1.0.0'
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='django-cas-client',
version=version,
description="Django Cas Client",
long_description=read('README.md'),
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: Developers",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content :: CGI Tools/Libraries",
"Topic :: Utilities",
"License :: OSI Approved :: MIT License",
],
keywords='django cas',
author='Derek Stegelman, Garrett Pennington',
author_email='derekst@k-state.edu, garrett@k-state.edu',
url='http://github.com/kstateome/django-cas/',
license='MIT',
packages=find_packages(),
include_package_data=True,
zip_safe=True,
)
| import os
from setuptools import setup, find_packages
version = '1.0.0'
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='django-cas',
version=version,
description="Django Cas Client",
long_description=read('README.md'),
classifiers=[
"Development Status :: Development",
"Environment :: Console",
"Intended Audience :: End Users/Desktop",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content :: CGI Tools/Libraries",
"Topic :: Utilities",
"License :: OSI Approved :: Private",
],
keywords='k-state-common',
author='Derek Stegelman, Garrett Pennington',
author_email='derekst@k-state.edu, garrett@k-state.edu',
url='http://github.com/kstateome/django-cas/',
license='MIT',
packages=find_packages(),
include_package_data=True,
zip_safe=True,
)
|
Add a test for the new multi-year feature | import kpub
def test_annual_count():
# Does the cumulative count match the annual count?
db = kpub.PublicationDB()
annual = db.get_annual_publication_count()
cumul = db.get_annual_publication_count_cumulative()
assert annual['k2'][2010] == 0 # K2 didn't exist in 2010
# The first K2 papers started appearing in 2014; the cumulative counts should reflect that:
assert (annual['k2'][2014] + annual['k2'][2015]) == cumul['k2'][2015]
assert (annual['k2'][2014] + annual['k2'][2015] + annual['k2'][2016]) == cumul['k2'][2016]
# Are the values returned by get_metrics consistent?
for year in range(2009, 2019):
metrics = db.get_metrics(year=year)
assert metrics['publication_count'] == annual['both'][year]
assert metrics['kepler_count'] == annual['kepler'][year]
assert metrics['k2_count'] == annual['k2'][year]
# Can we pass multiple years to get_metrics?
metrics = db.get_metrics(year=[2011, 2012])
assert metrics['publication_count'] == annual['both'][2011] + annual['both'][2012]
| import kpub
def test_annual_count():
# Does the cumulative count match the annual count?
db = kpub.PublicationDB()
annual = db.get_annual_publication_count()
cumul = db.get_annual_publication_count_cumulative()
assert annual['k2'][2010] == 0 # K2 didn't exist in 2010
# The first K2 papers started appearing in 2014; the cumulative counts should reflect that:
assert (annual['k2'][2014] + annual['k2'][2015]) == cumul['k2'][2015]
assert (annual['k2'][2014] + annual['k2'][2015] + annual['k2'][2016]) == cumul['k2'][2016]
# Are the values returned by get_metrics consistent?
for year in range(2009, 2019):
metrics = db.get_metrics(year=year)
assert metrics['publication_count'] == annual['both'][year]
assert metrics['kepler_count'] == annual['kepler'][year]
assert metrics['k2_count'] == annual['k2'][year]
|
Make Generator Create Some Hardcoded Files For Now | var Generator = require('yeoman-generator');
module.exports = class extends Generator {
init() {
this.log('Generating GraphQL Schema');
}
writing() {
this.fs.copyTpl(
this.templatePath('./schema/schema.js'),
this.destinationPath('./schema/schema.js'),
{ title: 'Generated schema file!' }
);
this.fs.copyTpl(
this.templatePath('./schema/ImType.js'),
this.destinationPath('./schema/ImType.js'),
{ title: 'Generated schema file!' }
);
this.fs.copyTpl(
this.templatePath('./schema/UserType.js'),
this.destinationPath('./schema/UserType.js'),
{ title: 'Generated schema file!' }
);
this.fs.copyTpl(
this.templatePath('./schema/MessageType.js'),
this.destinationPath('./schema/MessageType.js'),
{ title: 'Generated schema file!' }
);
}
};
| var Generator = require('yeoman-generator');
module.exports = class extends Generator {
init() {
this.log('Generating GraphQL Schema');
}
writing() {
this.fs.copyTpl(
this.templatePath('/schema/schema.js'),
this.destinationPath('/schema/schema.js'),
{ title: 'Generated schema file!' }
);
// this.fs.copyTpl(
// this.templatePath('/schema/ImType.js'),
// this.destinationPath('/schema/ImType.js'),
// { title: 'Generated schema file!' }
// );
// this.fs.copyTpl(
// this.templatePath('/schema/UserType.js'),
// this.destinationPath('/schema/UserType.js'),
// { title: 'Generated schema file!' }
// );
//
// this.fs.copyTpl(
// this.templatePath('/schema/MessageType.js'),
// this.destinationPath('/schema/MessageType.js'),
// { title: 'Generated schema file!' }
// );
//
// this.fs.copyTpl(
// this.templatePath('index.js'),
// this.destinationPath('src/index.js'),
// { title: 'Generate console logs!' }
// );
}
};
|
Update pyyaml requirement from <4.2,>=3.12 to >=3.12,<5.2
Updates the requirements on [pyyaml](https://github.com/yaml/pyyaml) to permit the latest version.
- [Release notes](https://github.com/yaml/pyyaml/releases)
- [Changelog](https://github.com/yaml/pyyaml/blob/master/CHANGES)
- [Commits](https://github.com/yaml/pyyaml/compare/3.12...5.1)
Signed-off-by: dependabot[bot] <5bdcd3c0d4d24ae3e71b3b452a024c6324c7e4bb@dependabot.com> | from setuptools import setup, find_packages
setup(
name='panoptescli',
version='1.0.2',
url='https://github.com/zooniverse/panoptes-cli',
author='Adam McMaster',
author_email='adam@zooniverse.org',
description=(
'A command-line client for Panoptes, the API behind the Zooniverse'
),
packages=find_packages(),
include_package_data=True,
install_requires=[
'Click>=6.7,<6.8',
'PyYAML>=3.12,<5.2',
'panoptes-client>=1.0,<2.0',
],
entry_points='''
[console_scripts]
panoptes=panoptes_cli.scripts.panoptes:cli
''',
)
| from setuptools import setup, find_packages
setup(
name='panoptescli',
version='1.0.2',
url='https://github.com/zooniverse/panoptes-cli',
author='Adam McMaster',
author_email='adam@zooniverse.org',
description=(
'A command-line client for Panoptes, the API behind the Zooniverse'
),
packages=find_packages(),
include_package_data=True,
install_requires=[
'Click>=6.7,<6.8',
'PyYAML>=3.12,<4.2',
'panoptes-client>=1.0,<2.0',
],
entry_points='''
[console_scripts]
panoptes=panoptes_cli.scripts.panoptes:cli
''',
)
|
Fix racey forceUpdate call when components are being rebuilt | // A helper mixin for react components.
// Use by setting this.store to your root store,
// and call this.grab(path) to get a store link that
// will also trigger forceUpdate of this component
// if the data changes.
//
// TODO: figure out react event batching
var mixin = {
componentWillMount: function() {
this._grabs = {};
},
componentWillUnmount: function() {
var s;
for(var path in this._grabs) {
s = this._grabs[path];
s.removeListener('CHANGE', this.storeUpdated);
}
delete this._grabs;
},
storeUpdated: function() {
if(this.isMounted()) {
this.forceUpdate(this.storeUpdateFinished);
}
},
grab: function(path) {
if(!this.store)
throw('grab() called before this.store set');
var s = this._grabs[path];
if(!s) {
s = this.store.Find(path);
if(!s)
throw("Grab failed: Unable to find path '" + path + "' in store '" + this.store.Name + "'");
s.addListener('CHANGE', this.storeUpdated);
this._grabs[path] = s;
}
return s;
}
};
module.exports = mixin;
| // A helper mixin for react components.
// Use by setting this.store to your root store,
// and call this.grab(path) to get a store link that
// will also trigger forceUpdate of this component
// if the data changes.
//
// TODO: figure out react event batching
var mixin = {
componentWillMount: function() {
this._grabs = {};
},
componentWillUnmount: function() {
var s;
for(var path in this._grabs) {
s = this._grabs[path];
s.removeListener('CHANGE', this.storeUpdated);
}
delete this._grabs;
},
storeUpdated: function() {
this.forceUpdate(this.storeUpdateFinished);
},
grab: function(path) {
if(!this.store)
throw('grab() called before this.store set');
var s = this._grabs[path];
if(!s) {
s = this.store.Find(path);
if(!s)
throw("Grab failed: Unable to find path '" + path + "' in store '" + this.store.Name + "'");
s.addListener('CHANGE', this.storeUpdated);
this._grabs[path] = s;
}
return s;
}
};
module.exports = mixin;
|
Remove call to the method connect() on the connection | /*
* *****************************************************
* Copyright VMware, Inc. 2010-2012. All Rights Reserved.
* *****************************************************
*
* DISCLAIMER. THIS PROGRAM IS PROVIDED TO YOU "AS IS" WITHOUT
* WARRANTIES OR CONDITIONS # OF ANY KIND, WHETHER ORAL OR WRITTEN,
* EXPRESS OR IMPLIED. THE AUTHOR SPECIFICALLY # DISCLAIMS ANY IMPLIED
* WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY # QUALITY,
* NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
*/
package com.vmware.connection.helpers;
import com.vmware.connection.Connection;
import com.vmware.vim25.ServiceContent;
import com.vmware.vim25.VimPortType;
public abstract class BaseHelper {
Connection connection = null;
public BaseHelper(final Connection connection) {
this.connection = connection;
}
public BaseHelper() { }
public class HelperException extends RuntimeException {
public HelperException(Throwable cause) {
super(cause);
}
}
}
| /*
* *****************************************************
* Copyright VMware, Inc. 2010-2012. All Rights Reserved.
* *****************************************************
*
* DISCLAIMER. THIS PROGRAM IS PROVIDED TO YOU "AS IS" WITHOUT
* WARRANTIES OR CONDITIONS # OF ANY KIND, WHETHER ORAL OR WRITTEN,
* EXPRESS OR IMPLIED. THE AUTHOR SPECIFICALLY # DISCLAIMS ANY IMPLIED
* WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY # QUALITY,
* NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
*/
package com.vmware.connection.helpers;
import com.vmware.connection.Connection;
import com.vmware.vim25.ServiceContent;
import com.vmware.vim25.VimPortType;
public abstract class BaseHelper {
Connection connection = null;
public BaseHelper(final Connection connection) {
this.connection = connection.connect();
}
public BaseHelper() { }
public class HelperException extends RuntimeException {
public HelperException(Throwable cause) {
super(cause);
}
}
}
|
Add filter_horizontal for for allowed and disallowed | from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from robots.models import Url, Rule
from robots.forms import RuleAdminForm
class RuleAdmin(admin.ModelAdmin):
form = RuleAdminForm
fieldsets = (
(None, {'fields': ('robot', 'sites')}),
(_('URL patterns'), {
'fields': ('allowed', 'disallowed'),
}),
(_('Advanced options'), {
'classes': ('collapse',),
'fields': ('crawl_delay',),
}),
)
list_filter = ('sites',)
list_display = ('robot', 'allowed_urls', 'disallowed_urls')
search_fields = ('robot', 'allowed__pattern', 'disallowed__pattern')
filter_horizontal = ('allowed', 'disallowed')
admin.site.register(Url)
admin.site.register(Rule, RuleAdmin)
| from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from robots.models import Url, Rule
from robots.forms import RuleAdminForm
class RuleAdmin(admin.ModelAdmin):
form = RuleAdminForm
fieldsets = (
(None, {'fields': ('robot', 'sites')}),
(_('URL patterns'), {
'fields': ('allowed', 'disallowed'),
}),
(_('Advanced options'), {
'classes': ('collapse',),
'fields': ('crawl_delay',),
}),
)
list_filter = ('sites',)
list_display = ('robot', 'allowed_urls', 'disallowed_urls')
search_fields = ('robot', 'allowed__pattern', 'disallowed__pattern')
admin.site.register(Url)
admin.site.register(Rule, RuleAdmin)
|
Use big company list for regex entity extraction | """
Find all company names in a piece of text
extractor = EntityExtractor()
entities = extractor.entities_from_text(text)
> ['acme incorporated', 'fubar limited', ...]
"""
COMPANY_SOURCE_FILE = '/tmp/companies_dev.csv'
import re
import csv
norm_reqs = (
('ltd.', 'limited'),
(' bv ', 'b.v.'),
)
def normalize(text):
text = text.lower()
for (rgx, replacement) in norm_reqs:
text = re.sub(rgx, replacement, text)
return text
def get_company_names():
rows = csv.reader(open(COMPANY_SOURCE_FILE, 'r'))
names = [normalize(row[0]) for row in rows]
return names
class EntityExtractor(object):
def __init__(self):
normed = [re.escape(normalize(x)) for x in get_company_names()]
joined = '|'.join(normed)
self.regex = re.compile('(' + joined + ')')
def entities_from_text(self, text):
return self.regex.findall(normalize(text))
| """
Find all company names in a piece of text
extractor = EntityExtractor()
entities = extractor.entities_from_text(text)
> ['acme incorporated', 'fubar limited', ...]
TODO:
- work out a standard form to normalize company names to
- import company names into the massive regex
"""
import re
norm_reqs = (
('ltd.', 'limited'),
(' bv ', 'b.v.'),
)
def normalize(text):
text = text.lower()
for (rgx, replacement) in norm_reqs:
text = re.sub(rgx, replacement, text)
return text
def get_company_names():
return ['ABC Inc', 'Joost Ltd.']
class EntityExtractor(object):
def __init__(self):
normed = [re.escape(normalize(x)) for x in get_company_names()]
joined = '|'.join(normed)
self.regex = re.compile('(' + joined + ')')
def entities_from_text(self, text):
return self.regex.findall(normalize(text))
|
Maintain the current context `this` context when giving the module its own scope | (function() {
function multifn() {
var types = [];
var fallback = noop;
function _multifn_() {
var i = -1;
var n = types.length;
var type;
while (++i < n) {
type = types[i];
if (!type.if.apply(_multifn_, arguments)) continue;
return type.do.apply(_multifn_, arguments);
}
return fallback.apply(_multifn_, arguments);
}
_multifn_.if = function(ifFn) {
return {do: function(doFn) {
types.push({
if: ifFn,
do: doFn
});
return _multifn_;
}};
};
_multifn_.else = function(elseFn) {
fallback = elseFn;
return _multifn_;
};
return _multifn_;
}
function noop() {}
if (typeof module != 'undefined')
module.exports = multifn;
else if (typeof define == 'function' && define.amd)
define(function() { return multifn; });
else
this.multifn = multifn;
}).call(this);
| (function() {
function multifn() {
var types = [];
var fallback = noop;
function _multifn_() {
var i = -1;
var n = types.length;
var type;
while (++i < n) {
type = types[i];
if (!type.if.apply(_multifn_, arguments)) continue;
return type.do.apply(_multifn_, arguments);
}
return fallback.apply(_multifn_, arguments);
}
_multifn_.if = function(ifFn) {
return {do: function(doFn) {
types.push({
if: ifFn,
do: doFn
});
return _multifn_;
}};
};
_multifn_.else = function(elseFn) {
fallback = elseFn;
return _multifn_;
};
return _multifn_;
}
function noop() {}
if (typeof module != 'undefined')
module.exports = multifn;
else if (typeof define == 'function' && define.amd)
define(function() { return multifn; });
else
this.multifn = multifn;
})();
|
Check whether or not selected currency exists in database upon registration | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
// use App\Http\Controllers\Controller;
use App\Currency;
use App\User;
use Hash;
class RegisterController extends Controller {
public function index() {
$currencies = Currency::all();
return view('register', compact('currencies'));
}
public function store(Request $request) {
$request->validate([
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|confirmed',
'currency' => 'required|exists:currencies,id'
]);
$user = new User;
$user->name = $request->name;
$user->email = $request->email;
$user->password = Hash::make($request->password);
$user->currency_id = $request->currency;
$user->language = 'en';
$user->save();
return redirect('/register');
}
}
| <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
// use App\Http\Controllers\Controller;
use App\Currency;
use App\User;
use Hash;
class RegisterController extends Controller {
public function index() {
$currencies = Currency::all();
return view('register', compact('currencies'));
}
public function store(Request $request) {
$request->validate([
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|confirmed',
'currency' => 'required'
]);
$user = new User;
$user->name = $request->name;
$user->email = $request->email;
$user->password = Hash::make($request->password);
$user->currency_id = $request->currency;
$user->language = 'en';
$user->save();
return redirect('/register');
}
}
|
Add "scaled" class after scaling elements. | define([
"jquery",
"../registry"
], function($, registry) {
var _ = {
name: "autoscale",
trigger: ".pat-auto-scale",
transform: $('html').hasClass('csstransforms'),
init: function($el, options) {
return $el.each(_.resizeElement);
},
resizeElement: function() {
var $this = $(this),
scale;
if (this.tagName.toLowerCase()==='body')
scale = $(window).width()/$this.outerWidth();
else
scale = $this.parent().outerWidth()/$this.outerWidth();
if (_.transform)
$this.css('transform', 'scale(' + scale + ')');
else
$this.css('zoom', scale);
$this.addClass("scaled");
},
resizeEvent: function() {
$(_.trigger).each(_.resizeElement);
}
};
$(window).resize(_.resizeEvent);
registry.register(_);
return _;
});
| define([
"jquery",
"../registry"
], function($, registry) {
var _ = {
name: "autoscale",
trigger: ".pat-auto-scale",
transform: $('html').hasClass('csstransforms'),
init: function($el, options) {
return $el.each(_.resizeElement);
},
resizeElement: function() {
var $this = $(this),
scale;
if (this.tagName.toLowerCase()==='body')
scale = $(window).width()/$this.outerWidth();
else
scale = $this.parent().outerWidth()/$this.outerWidth();
if (_.transform)
$this.css('transform', 'scale(' + scale + ')');
else
$this.css('zoom', scale);
},
resizeEvent: function() {
$(_.trigger).each(_.resizeElement);
}
};
$(window).resize(_.resizeEvent);
registry.register(_);
return _;
});
|
Add generated serial version UUID | /*
* Copyright 2016-2020 52°North Initiative for Geospatial Open Source
* Software GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.n52.javaps.rest.model;
import org.springframework.validation.annotation.Validated;
import java.util.ArrayList;
import java.util.Objects;
/**
* AllowedValues
*/
@Validated
public class AllowedValues extends ArrayList<Object> {
/**
*
*/
private static final long serialVersionUID = 3188528125357828614L;
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
return o != null && getClass() == o.getClass();
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode());
}
@Override
public String toString() {
return String.format("AllowedValues {%s}", super.toString());
}
}
| /*
* Copyright 2016-2020 52°North Initiative for Geospatial Open Source
* Software GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.n52.javaps.rest.model;
import org.springframework.validation.annotation.Validated;
import java.util.ArrayList;
import java.util.Objects;
/**
* AllowedValues
*/
@Validated
public class AllowedValues extends ArrayList<Object> {
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
return o != null && getClass() == o.getClass();
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode());
}
@Override
public String toString() {
return String.format("AllowedValues {%s}", super.toString());
}
}
|
Rename for a better term | /*
* Copyright 2015 Ryan Gilera.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.daytron.revworks.data;
/**
* Collection of file directory paths.
*
* @author Ryan Gilera
*/
public enum FilePath {
TEMP_FILE_HOLDER("/VAADIN/tempFileHolder/"),
HTML_OUTPUT_NAME("convertedWork"),
FILE_OUTPUT_NAME("pdfFile"),
TEMP_PICTURE_FOLDER("pictures/");
private final String path;
private FilePath(String path) {
this.path = path;
}
public String getPath() {
return path;
}
}
| /*
* Copyright 2015 Ryan Gilera.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.daytron.revworks.data;
/**
* Collection of file directory paths.
*
* @author Ryan Gilera
*/
public enum FilePath {
TEMP_FILE_HOLDER("/VAADIN/tempFileHolder/"),
HTML_OUTPUT_NAME("convertedWork"),
PDF_OUTPUT_NAME("pdfFile"),
TEMP_PICTURE_FOLDER("pictures/");
private final String path;
private FilePath(String path) {
this.path = path;
}
public String getPath() {
return path;
}
}
|
Use proper email format for author | #!/usr/bin/env python3
import os
import setuptools
def find_files(path):
return [os.path.join(path, f) for f in os.listdir(path)]
setuptools.setup(
name='workspace-tools',
version='3.0.10',
author='Max Zheng',
author_email='maxzheng.os@gmail.com',
description='Convenience wrapper for git/tox to simplify local development',
long_description=open('README.rst').read(),
changelog_url='https://raw.githubusercontent.com/maxzheng/workspace-tools/master/docs/CHANGELOG.rst',
url='https://github.com/maxzheng/workspace-tools',
entry_points={
'console_scripts': [
'wst = workspace.controller:Commander.main',
],
},
install_requires=open('requirements.txt').read(),
license='MIT',
packages=setuptools.find_packages(),
include_package_data=True,
setup_requires=['setuptools-git'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Topic :: Software Development',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
keywords='workspace multiple repositories git scm abstraction development tools',
)
| #!/usr/bin/env python3
import os
import setuptools
def find_files(path):
return [os.path.join(path, f) for f in os.listdir(path)]
setuptools.setup(
name='workspace-tools',
version='3.0.10',
author='Max Zheng',
author_email='maxzheng.os @t gmail.com',
description='Convenience wrapper for git/tox to simplify local development',
long_description=open('README.rst').read(),
changelog_url='https://raw.githubusercontent.com/maxzheng/workspace-tools/master/docs/CHANGELOG.rst',
url='https://github.com/maxzheng/workspace-tools',
entry_points={
'console_scripts': [
'wst = workspace.controller:Commander.main',
],
},
install_requires=open('requirements.txt').read(),
license='MIT',
packages=setuptools.find_packages(),
include_package_data=True,
setup_requires=['setuptools-git'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Topic :: Software Development',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
keywords='workspace multiple repositories git scm abstraction development tools',
)
|
Check whether iterator is already closed
Sometimes the iterator may not be null but may be already closed. This
occurs because we have used the EntryIteratorDAO previously to read up to the end
of the iterator (which will close it). This now checks for the closed iterator and
recreates it if necessary. | package uk.gov.register.db;
import org.skife.jdbi.v2.ResultIterator;
import uk.gov.register.core.Entry;
public class EntryIteratorDAO {
private final EntryQueryDAO entryDAO;
private int nextValidEntryNumber;
private ResultIterator<Entry> iterator;
public EntryIteratorDAO(EntryQueryDAO entryDAO) {
this.entryDAO = entryDAO;
this.nextValidEntryNumber = -1;
}
public Entry findByEntryNumber(int entryNumber) {
if (iterator == null || !iterator.hasNext() || entryNumber != nextValidEntryNumber) {
if (iterator != null) {
iterator.close();
}
iterator = entryDAO.entriesIteratorFrom(entryNumber);
nextValidEntryNumber = entryNumber;
}
nextValidEntryNumber++;
return iterator.next();
}
}
| package uk.gov.register.db;
import org.skife.jdbi.v2.ResultIterator;
import uk.gov.register.core.Entry;
public class EntryIteratorDAO {
private final EntryQueryDAO entryDAO;
private int nextValidEntryNumber;
private ResultIterator<Entry> iterator;
public EntryIteratorDAO(EntryQueryDAO entryDAO) {
this.entryDAO = entryDAO;
this.nextValidEntryNumber = -1;
}
public Entry findByEntryNumber(int entryNumber) {
if (iterator == null || entryNumber != nextValidEntryNumber) {
if (iterator != null) {
iterator.close();
}
iterator = entryDAO.entriesIteratorFrom(entryNumber);
nextValidEntryNumber = entryNumber;
}
nextValidEntryNumber++;
return iterator.next();
}
}
|
Fix rating types updated message
Now we save all the rating types (before we were saving one type at once). | <?php
namespace Concrete\Controller\SinglePage\Dashboard\System\Conversations;
use \Concrete\Core\Page\Controller\DashboardPageController;
use Loader;
use \Concrete\Core\Conversation\Rating\Type as ConversationRatingType;
class Points extends DashboardPageController
{
public function view()
{
$ratingTypes = array_reverse(ConversationRatingType::getList());
$this->set('ratingTypes', $ratingTypes);
}
public function success() {
$this->view();
$this->set('message', t('Rating types updated.'));
}
public function save() {
$db = Loader::db();
foreach (ConversationRatingType::getList() as $crt) {
$rtID = $crt->getConversationRatingTypeID();
$rtPoints = $this->post('rtPoints_' . $rtID);
if (is_string($rtPoints) && is_numeric($rtPoints)) {
$db->Execute('UPDATE ConversationRatingTypes SET cnvRatingTypeCommunityPoints = ? WHERE cnvRatingTypeID = ? LIMIT 1', array($rtPoints, $rtID));
}
}
$this->redirect('/dashboard/system/conversations/points', 'success');
}
}
| <?php
namespace Concrete\Controller\SinglePage\Dashboard\System\Conversations;
use \Concrete\Core\Page\Controller\DashboardPageController;
use Loader;
use \Concrete\Core\Conversation\Rating\Type as ConversationRatingType;
class Points extends DashboardPageController
{
public function view()
{
$ratingTypes = array_reverse(ConversationRatingType::getList());
$this->set('ratingTypes', $ratingTypes);
}
public function success() {
$this->view();
$this->set('message', t('Rating type updated.'));
}
public function save() {
$db = Loader::db();
foreach (ConversationRatingType::getList() as $crt) {
$rtID = $crt->getConversationRatingTypeID();
$rtPoints = $this->post('rtPoints_' . $rtID);
if (is_string($rtPoints) && is_numeric($rtPoints)) {
$db->Execute('UPDATE ConversationRatingTypes SET cnvRatingTypeCommunityPoints = ? WHERE cnvRatingTypeID = ? LIMIT 1', array($rtPoints, $rtID));
}
}
$this->redirect('/dashboard/system/conversations/points', 'success');
}
}
|
Use new Epsilon versioned feature. | from distutils.core import setup
import axiom
distobj = setup(
name="Axiom",
version=axiom.version.short(),
maintainer="Divmod, Inc.",
maintainer_email="support@divmod.org",
url="http://divmod.org/trac/wiki/DivmodAxiom",
license="MIT",
platforms=["any"],
description="An in-process object-relational database",
classifiers=[
"Intended Audience :: Developers",
"Programming Language :: Python",
"Development Status :: 2 - Pre-Alpha",
"Topic :: Database"],
scripts=['bin/axiomatic'],
packages=['axiom',
'axiom.scripts',
'axiom.plugins',
'axiom.test'],
package_data={'axiom': ['examples/*']})
from epsilon.setuphelper import regeneratePluginCache
regeneratePluginCache(distobj)
| from distutils.core import setup
distobj = setup(
name="Axiom",
version="0.1",
maintainer="Divmod, Inc.",
maintainer_email="support@divmod.org",
url="http://divmod.org/trac/wiki/AxiomProject",
license="MIT",
platforms=["any"],
description="An in-process object-relational database",
classifiers=[
"Intended Audience :: Developers",
"Programming Language :: Python",
"Development Status :: 2 - Pre-Alpha",
"Topic :: Database"],
scripts=['bin/axiomatic'],
packages=['axiom',
'axiom.scripts',
'axiom.plugins',
'axiom.test'],
package_data={'axiom': ['examples/*']})
from epsilon.setuphelper import regeneratePluginCache
regeneratePluginCache(distobj)
|
Revert "Convert relative apiURL paths to absolute paths"
This reverts commit d4649622aecd8d1cae56963fd4f214acf45b0cf3. | var packageJSON = require("../../../package.json");
var config = {
// @@ENV gets replaced by build system
environment: "@@ENV",
// If the UI is served through a proxied URL, this can be set here.
rootUrl: "",
// Defines the Marathon API URL,
// leave empty to use the same as the UI is served.
apiURL: "../",
// Intervall of API request in ms
updateInterval: 5000,
// Local http server URI while tests run
localTestserverURI: {
address: "localhost",
port: 8181
},
version: ("@@TEAMCITY_UI_VERSION".indexOf("@@TEAMCITY") === -1) ?
"@@TEAMCITY_UI_VERSION" :
`${packageJSON.version}-SNAPSHOT`
};
if (process.env.GULP_ENV === "development") {
try {
var configDev = require("./config.dev");
config = Object.assign(config, configDev);
} catch (e) {
console.info("You could copy config.template.js to config.dev.js " +
"to enable a development configuration.");
}
}
module.exports = config;
| var url = require("url");
var packageJSON = require("../../../package.json");
var config = {
// @@ENV gets replaced by build system
environment: "@@ENV",
// If the UI is served through a proxied URL, this can be set here.
rootUrl: "",
// Defines the Marathon API URL,
// leave empty to use the same as the UI is served.
apiURL: "../",
// Intervall of API request in ms
updateInterval: 5000,
// Local http server URI while tests run
localTestserverURI: {
address: "localhost",
port: 8181
},
version: ("@@TEAMCITY_UI_VERSION".indexOf("@@TEAMCITY") === -1) ?
"@@TEAMCITY_UI_VERSION" :
`${packageJSON.version}-SNAPSHOT`
};
if (process.env.GULP_ENV === "development") {
try {
var configDev = require("./config.dev");
config = Object.assign(config, configDev);
} catch (e) {
console.info("You could copy config.template.js to config.dev.js " +
"to enable a development configuration.");
}
}
// Convert relative URLs to absolute URLs for node-fetch
if (global.document != null) {
if (config.apiURL.indexOf(":") === -1) {
config.apiURL = url.resolve(
document.location.origin,
document.location.pathname + config.apiURL
);
}
}
module.exports = config;
|
Fix test for Traits listing | <?php
namespace fennecweb\ajax\listing;
use \fennecweb\WebService as WebService;
class TraitsTest extends \PHPUnit_Framework_TestCase
{
public function testExecute()
{
//Test for traits without search term or limit
list($service) = WebService::factory('listing/Traits');
$results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION, 'search' => '')));
$expected = array(
array(
"name" => "PlantHabit",
"trait_type_id" => 1,
"frequency" => 48916
)
);
$this->assertEquals($expected, $results);
}
}
| <?php
namespace fennecweb\ajax\listing;
use \fennecweb\WebService as WebService;
class TraitsTest extends \PHPUnit_Framework_TestCase
{
public function testExecute()
{
//Test for error returned by user is not logged in
list($service) = WebService::factory('listing/Traits');
$results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION, 'search' => '')));
$expected = array(
array(
"name" => "PlantHabit",
"trait_type_id" => 1,
"frequency" => 48916
)
);
$this->assertArraySubset($expected, $results);
}
}
|
Remove unneeded getPageJSFile hbs helper | //
// Copyright 2009-2014 Ilkka Oksanen <iao@iki.fi>
//
// 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.
//
'use strict';
const fs = require('fs');
const path = require('path');
let manifest;
const PREFIX = '/dist/';
try {
manifest = JSON.parse(fs.readFileSync(path.resolve(__dirname,
'..', 'public', 'dist', 'rev-manifest.json')));
} catch (e) {
manifest = false;
}
exports.registerHelpers = function registerHelpers(hbs) {
hbs.registerHelper('asset', file => {
if (manifest) {
return PREFIX + manifest[file];
}
return PREFIX + file;
});
};
| //
// Copyright 2009-2014 Ilkka Oksanen <iao@iki.fi>
//
// 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.
//
'use strict';
const fs = require('fs');
const path = require('path');
let manifest;
const PREFIX = '/dist/';
try {
manifest = JSON.parse(fs.readFileSync(path.resolve(__dirname,
'..', 'public', 'dist', 'rev-manifest.json')));
} catch (e) {
manifest = false;
}
exports.registerHelpers = function registerHelpers(hbs) {
hbs.registerHelper('getPageJSFile', () => `${this.page}.js`);
hbs.registerHelper('asset', file => {
if (manifest) {
return PREFIX + manifest[file];
}
return PREFIX + file;
});
};
|
Fix licence header in newly added file. | /*
* Copyright 2013 Mat Booth <mbooth@apache.org>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gpm.calameo;
public class SingleDrm {
private String ID;
private String SubscriptionID;
private String SubscriberLogin;
private Publication Book;
private String Extras;
public SingleDrm() {
}
public String getId() {
return ID;
}
public String getSubscriptionId() {
return SubscriptionID;
}
public String getSubscriberLogin() {
return SubscriberLogin;
}
public Publication getBook() {
return Book;
}
public String getExtras() {
return Extras;
}
@Override
public String toString() {
return String.format("{ ID: %s, Subscription ID: %s, Subscriber Login: %s, Book: %s, Extras: %s }", getId(),
getSubscriptionId(), getSubscriberLogin(), getBook(), getExtras());
}
}
| /**
* Copyright 2013 Mat Booth <mbooth@apache.org>
*/
package com.gpm.calameo;
public class SingleDrm {
private String ID;
private String SubscriptionID;
private String SubscriberLogin;
private Publication Book;
private String Extras;
public SingleDrm() {
}
public String getId() {
return ID;
}
public String getSubscriptionId() {
return SubscriptionID;
}
public String getSubscriberLogin() {
return SubscriberLogin;
}
public Publication getBook() {
return Book;
}
public String getExtras() {
return Extras;
}
@Override
public String toString() {
return String.format("{ ID: %s, Subscription ID: %s, Subscriber Login: %s, Book: %s, Extras: %s }", getId(),
getSubscriptionId(), getSubscriberLogin(), getBook(), getExtras());
}
}
|
Update the formatting using goimports
`goimports` tool is integrated into GoSublime package of Sublime
Text 2 editor. | package feature
import "sync"
var onlyonce sync.Once
var protect chan int
var singleton *Feature
func getSingleton() (r *Feature) {
onlyonce.Do(func() {
singleton = New()
})
return singleton
}
// ClearCache clears the cached features that were loaded from the object server.
func ClearCache() {
protect <- 1
defer func() { <-protect }()
getSingleton().ClearCache()
}
// SetGlobalContext sets the default global context to the given context.
func SetGlobalContext(ctx string) {
protect <- 1
defer func() { <-protect }()
getSingleton().SetGlobalContext(ctx)
}
// Bool returns the boolean value of the feature application state for the
// given tag.
func Bool(tag string) bool {
protect <- 1
defer func() { <-protect }()
return getSingleton().Bool(tag)
}
// Int returns the integer value of the feature application state for the given
// tag.
func Int(tag string) int {
protect <- 1
defer func() { <-protect }()
return getSingleton().Int(tag)
}
// Str returns the string value of the feature application state for the given
// tag.
func Str(tag string) string {
protect <- 1
defer func() { <-protect }()
return getSingleton().Str(tag)
}
func init() {
protect = make(chan int, 1) // Allocate a buffer channel
}
| package feature
import (
"sync"
)
var onlyonce sync.Once
var protect chan int
var singleton *Feature
func getSingleton() (r *Feature) {
onlyonce.Do(func() {
singleton = New()
})
return singleton
}
// ClearCache clears the cached features that were loaded from the object server.
func ClearCache() {
protect <- 1
defer func() {<-protect}()
getSingleton().ClearCache()
}
// SetGlobalContext sets the default global context to the given context.
func SetGlobalContext(ctx string) {
protect <- 1
defer func() {<-protect}()
getSingleton().SetGlobalContext(ctx)
}
// Bool returns the boolean value of the feature application state for the
// given tag.
func Bool(tag string) bool {
protect <- 1
defer func() {<-protect}()
return getSingleton().Bool(tag)
}
// Int returns the integer value of the feature application state for the given
// tag.
func Int(tag string) int {
protect <- 1
defer func() {<-protect}()
return getSingleton().Int(tag)
}
// Str returns the string value of the feature application state for the given
// tag.
func Str(tag string) string {
protect <- 1
defer func() {<-protect}()
return getSingleton().Str(tag)
}
func init() {
protect = make(chan int, 1) // Allocate a buffer channel
}
|
Fix task type export test | from tests.base import ApiDBTestCase
class TasksCsvExportTestCase(ApiDBTestCase):
def setUp(self):
super(TasksCsvExportTestCase, self).setUp()
self.generate_fixture_project_status()
self.generate_fixture_project()
self.generate_fixture_asset_type()
self.generate_fixture_department()
self.generate_fixture_task_type()
def test_get_output_files(self):
csv_task_types = self.get_raw("export/csv/task-types.csv")
expected_result = """Department;Name\r
Animation;Animation\r
Animation;Layout\r
Modeling;Shaders\r
"""
self.assertEqual(csv_task_types, expected_result)
| from tests.base import ApiDBTestCase
class TasksCsvExportTestCase(ApiDBTestCase):
def setUp(self):
super(TasksCsvExportTestCase, self).setUp()
self.generate_fixture_project_status()
self.generate_fixture_project()
self.generate_fixture_asset_type()
self.generate_fixture_department()
self.generate_fixture_task_type()
def test_get_output_files(self):
csv_task_types = self.get_raw("export/csv/task-types.csv")
expected_result = """Department;Name\r
Animation;Animation\r
Modeling;Shaders\r
"""
self.assertEqual(csv_task_types, expected_result)
|
Add some draft weather types
temperature_night_offset should possibly be the range so difference
between night and day is not always the same. | class WeatherType:
def __init__(self, weathers, temperature_range, temperature_night_offset,
wind_range, humidity_range):
self.__weathers = weathers
self.__min_temp_day, self.__max_temp_day = \
tuple(temperature_range)
self.__min_temp_night, self.__max_temp_night = \
tuple(map(lambda x: x- temperature_night_offset,
temperature_range))
self.__min_wind_speed, self.__max_wind_speed = \
tuple(wind_range)
self.__min_humidity, self.__max_humidity = \
tuple(humidity_range)
# FIXME: temperature_night_offset is always the same
weather_types = \
[WeatherType(["sunny, cloudy", "rain"],
(3, 40), 7, (2, 20), (10, 90)),
WeatherType(["sunny", "cloudy", "snow"],
(-25, 0), 7, (2, 20), (10, 90))]
| class WeatherType:
def __init__(self, weathers, temperature_range, temperature_night_offset,
wind_range, humidity_range):
self.__weathers = weathers
self.__min_temp_day, self.__max_temp_day = \
tuple(temperature_range)
self.__min_temp_night, self.__max_temp_night = \
tuple(map(lambda x: x- temperature_night_offset,
temperature_range))
self.__min_wind_speed, self.__max_wind_speed = \
tuple(wind_range)
self.__min_humidity, self.__max_humidity = \
tuple(humidity_range)
|
Add option to save model in script | import graph
# default
data = ('iOS', 'iOS-wifi', 'AC', 'IC2012')
models = ('constant', 'distance', 'countries', 'full')
plot_dir = '../../report2/figures'
show_plots = False
oa_max_delay = [5000.]
save = False
## save model
#data = 'iOS',
#models = 'full',
#plot_dir = ''
#save = True
for d in data:
print '#' * 70
print '#' * 3, d
print '#' * 70
for m in models:
print
print '#' * 4, m
graph.train_model(model=m,
data=d,
plot_dir=plot_dir,
plot_accuracy=True,
show_plots=show_plots,
oa_max_delay=oa_max_delay,
save=save)
| import graph
# default
data = ('iOS', 'iOS-wifi', 'AC', 'IC2012')
models = ('constant', 'distance', 'countries', 'full')
plot_dir = '../../report2/figures'
show_plots = False
oa_max_delay = [5000.]
for d in data:
print '#' * 70
print '#' * 3, d
print '#' * 70
for m in models:
print
print '#' * 4, m
graph.train_model(model=m,
data=d,
plot_dir=plot_dir,
plot_accuracy=True,
show_plots=show_plots,
oa_max_delay=oa_max_delay)
|
Hide release notes if not found | import React, { Component } from "react";
import PropTypes from "prop-types";
import styled from "styled-components";
import Dialog from "./Dialog.js";
class ReleaseNotes extends Component {
static propTypes = {
onReady: PropTypes.func.isRequired,
releaseNotes: PropTypes.string
};
componentDidMount() {
this.props.onReady();
}
render() {
if (!this.props.releaseNotes) {
return null;
}
return (
<Dialog title={`⚡️ What's New - v${__VERSION__}`}>
<div dangerouslySetInnerHTML={{ __html: this.props.releaseNotes }} />
</Dialog>
);
}
}
export default ReleaseNotes;
| import React, { Component } from "react";
import PropTypes from "prop-types";
import styled from "styled-components";
import Dialog from "./Dialog.js";
class ReleaseNotes extends Component {
static propTypes = {
onReady: PropTypes.func.isRequired,
releaseNotes: PropTypes.string
};
componentDidMount() {
this.props.onReady();
}
render() {
return (
<Dialog title={`⚡️ What's New - v${__VERSION__}`}>
<If condition={this.props.releaseNotes}>
<div dangerouslySetInnerHTML={{ __html: this.props.releaseNotes }} />
</If>
</Dialog>
);
}
}
export default ReleaseNotes;
|
Tidy up and test commit | var cheerio = require('cheerio');
function parseResultBody(body) {
$ = cheerio.load(body);
var headings = resultsToArray($, 'div[id^=win0divGPSSR_CLSRSLT_WRK_GROUPBOX2]');
var classesPerHeadings = resultsToArray($, 'table[id^=\'ACE_$ICField104\']');
var nbr = resultsToArray($, 'a[id^=MTG_CLASS_NBR]');
var section = resultsToArray($, 'a[id^=MTG_CLASSNAME]');
var status = resultsToArray($, 'img[class^=SSSIMAGECENTER]');
var room = resultsToArray($, 'span[id^=MTG_ROOM]');
var time = resultsToArray($, 'span[id^=MTG_DAYTIME]');
var instructors = resultsToArray($, 'span[id^=MTG_INSTR]');
for (i = 0; i < headings.length; i++) {
var heading = getHeadingInfo(i);
// create class structure
}
}
function getHeadingInfo(body) {
}
function resultsToArray(body, parseString) {
var results = body(parseString);
var resultsArray = [];
results.each(function(i) {
resultsArray[i] = $(this).text().trim();
});
return resultsArray;
}
module.exports = {
parseResultBody: parseResultBody
} | var cheerio = require('cheerio');
function parseResultBody(body) {
$ = cheerio.load(body);
var headings = resultsToArray($, 'div[id^=win0divGPSSR_CLSRSLT_WRK_GROUPBOX2]');
var classesPerHeadings = resultsToArray($, 'table[id^=\'ACE_$ICField104\']');
var nbr = resultsToArray($, 'a[id^=MTG_CLASS_NBR]');
var section = resultsToArray($, 'a[id^=MTG_CLASSNAME]');
var status = resultsToArray($, 'img[class^=SSSIMAGECENTER]');
var room = resultsToArray($, 'span[id^=MTG_ROOM]');
var time = resultsToArray($, 'span[id^=MTG_DAYTIME]');
var instructors = resultsToArray($, 'span[id^=MTG_INSTR]');
for (i = 0; i < headings.length; i++) {
var heading = getHeadingInfo(i);
// create class structure
}
}
function getHeadingInfo(body) {
}
function resultsToArray(body, parseString) {
var results = body(parseString);
var resultsArray = [];
results.each(function(i) {
resultsArray[i] = $(this).text().trim();
});
return resultsArray;
}
module.exports = {
parseResultBody: parseResultBody
} |
Fix printing tweets if theres no moderators at all | const fs = require("fs");
const path = require("path");
const glob = require("glob");
const DIR = "_data/events_gdcr2019";
const toWelcomeTweetModerators = moderators => {
const names = moderators.map(mod => {
if (typeof mod === "string") return mod;
if (mod.url && mod.url.includes("twitter.com"))
return "@" + mod.url.split("/").slice(-1)[0];
return mod.name;
});
if (names.length === 0) return "";
if (names.length === 1) return " with " + names[0];
return " with " + names.slice(0, -1).join(", ") + " & " + names.slice(-1)[0];
};
const toWelcomeTweet = event => {
const moderators = toWelcomeTweetModerators(event.moderators);
return `🌐 Welcome ${event.location.city}, ${
event.location.country
}${moderators} to the Global Day Of Coderetreat 2019! #gdcr19 #coderetreat ${
event.url
}`;
};
const events = glob
.sync(path.resolve(__dirname, "../_data/events_gdcr2019/") + "/*.json")
.sort((fa, fb) => fs.statSync(fa).mtimeMs - fs.statSync(fb).mtimeMs)
.map(file => JSON.parse(fs.readFileSync(file)))
.map(toWelcomeTweet);
console.log(events.join("\n"));
| const fs = require("fs");
const path = require("path");
const glob = require("glob");
const DIR = "_data/events_gdcr2019";
const toWelcomeTweetModerators = moderators => {
const names = moderators.map(mod => {
if (typeof mod === "string") return mod;
if (mod.url && mod.url.includes("twitter.com"))
return "@" + mod.url.split("/").slice(-1)[0];
return mod.name;
});
if (names.length === 1) return names[0];
return names.slice(0, -1).join(", ") + " & " + names.slice(-1)[0];
};
const toWelcomeTweet = event => {
const moderators = toWelcomeTweetModerators(event.moderators);
return `🌐 Welcome ${event.location.city}, ${
event.location.country
} with ${moderators} to the Global Day Of Coderetreat 2019! #gdcr19 #coderetreat ${
event.url
}`;
};
const events = glob
.sync(path.resolve(__dirname, "../_data/events_gdcr2019/") + "/*.json")
.sort((fa, fb) => fs.statSync(fa).mtimeMs - fs.statSync(fb).mtimeMs)
.map(file => JSON.parse(fs.readFileSync(file)))
.map(toWelcomeTweet);
console.log(events.join("\n"));
|
Rename "Logs" tests to "Loggregator" | package smoke
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/pivotal-cf-experimental/cf-test-helpers/cf"
. "github.com/pivotal-cf-experimental/cf-test-helpers/generator"
. "github.com/vito/cmdtest/matchers"
"os"
)
var _ = Describe("Loggregator", func() {
BeforeEach(func() {
os.Setenv("CF_COLOR", "false")
AppName = RandomName()
})
AfterEach(func() {
Expect(Cf("delete", AppName, "-f")).To(Say("OK"))
})
It("can see router requests in the logs", func() {
Expect(Cf("push", AppName, "-p", AppPath)).To(Say("App started"))
Eventually(Curling("/")).Should(Say("It just needed to be restarted!"))
// Curling multiple times because loggregator makes no garauntees about delivery of logs.
Eventually(Curling("/")).Should(Say("Healthy"))
Eventually(Cf("logs", "--recent", AppName)).Should(Say("[RTR]"))
Eventually(Curling("/")).Should(Say("Healthy"))
Eventually(Cf("logs", "--recent", AppName)).Should(Say("[App/0]"))
})
})
| package smoke
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/pivotal-cf-experimental/cf-test-helpers/cf"
. "github.com/pivotal-cf-experimental/cf-test-helpers/generator"
. "github.com/vito/cmdtest/matchers"
"os"
)
var _ = Describe("Logs", func() {
BeforeEach(func() {
os.Setenv("CF_COLOR", "false")
AppName = RandomName()
})
AfterEach(func() {
Expect(Cf("delete", AppName, "-f")).To(Say("OK"))
})
It("can see router requests in the logs", func() {
Expect(Cf("push", AppName, "-p", AppPath)).To(Say("App started"))
Eventually(Curling("/")).Should(Say("It just needed to be restarted!"))
// Curling multiple times because loggregator makes no garauntees about delivery of logs.
Eventually(Curling("/")).Should(Say("Healthy"))
Eventually(Cf("logs", "--recent", AppName)).Should(Say("[RTR]"))
Eventually(Curling("/")).Should(Say("Healthy"))
Eventually(Cf("logs", "--recent", AppName)).Should(Say("[App/0]"))
})
})
|
Change LengthGenerator to get appropriate file path | from pkg_resources import resource_filename
import pandas as pd
import numpy as np
class LengthGenerator(object):
def __init__(self,
length_file=resource_filename('synthnotes.resources',
'note_lengths.csv')):
# print(length_file)
df = pd.read_csv(length_file)
notes_count = df['count'].sum()
df['probability'] = df['count'] / notes_count
self.note_lengths = df['note_length'].as_matrix()
self.p = df['probability'].as_matrix()
def generate(self, size=1):
return np.random.choice(self.note_lengths,
size=size,
p=self.p)
| from pkg_resources import resource_filename
import pandas as pd
import numpy as np
class LengthGenerator(object):
def __init__(self,
length_file=resource_filename(__name__,
'resources/note_lengths.csv')):
# print(length_file)
df = pd.read_csv(length_file)
notes_count = df['count'].sum()
df['probability'] = df['count'] / notes_count
self.note_lengths = df['note_length'].as_matrix()
self.p = df['probability'].as_matrix()
def generate(self, size=1):
return np.random.choice(self.note_lengths,
size=size,
p=self.p)
|
Fix Trades Widget to count by isPositive rather than IRR | package name.abuchen.portfolio.ui.views.dashboard;
import java.util.List;
import com.ibm.icu.text.MessageFormat;
import name.abuchen.portfolio.model.Dashboard.Widget;
import name.abuchen.portfolio.snapshot.trades.Trade;
import name.abuchen.portfolio.ui.views.trades.TradeDetailsView;
import name.abuchen.portfolio.util.TextUtil;
public class TradesWidget extends AbstractTradesWidget
{
public TradesWidget(Widget widget, DashboardData dashboardData)
{
super(widget, dashboardData);
}
@Override
public void update(TradeDetailsView.Input input)
{
this.title.setText(TextUtil.tooltip(getWidget().getLabel()));
List<Trade> trades = input.getTrades();
long positive = trades.stream().filter(t -> t.getProfitLoss().isPositive()).count();
String text = MessageFormat.format("{0} <green>↑{1}</green> <red>↓{2}</red>", //$NON-NLS-1$
trades.size(), positive, trades.size() - positive);
this.indicator.setText(text);
}
}
| package name.abuchen.portfolio.ui.views.dashboard;
import java.util.List;
import com.ibm.icu.text.MessageFormat;
import name.abuchen.portfolio.model.Dashboard.Widget;
import name.abuchen.portfolio.snapshot.trades.Trade;
import name.abuchen.portfolio.ui.views.trades.TradeDetailsView;
import name.abuchen.portfolio.util.TextUtil;
public class TradesWidget extends AbstractTradesWidget
{
public TradesWidget(Widget widget, DashboardData dashboardData)
{
super(widget, dashboardData);
}
@Override
public void update(TradeDetailsView.Input input)
{
this.title.setText(TextUtil.tooltip(getWidget().getLabel()));
List<Trade> trades = input.getTrades();
long positive = trades.stream().filter(t -> t.getIRR() > 0).count();
String text = MessageFormat.format("{0} <green>↑{1}</green> <red>↓{2}</red>", //$NON-NLS-1$
trades.size(), positive, trades.size() - positive);
this.indicator.setText(text);
}
}
|
Fix migration to work with flows with no base_language | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-04-19 14:53
from __future__ import unicode_literals
import json
import temba.utils.models
from django.contrib.postgres.operations import HStoreExtension
from django.db import migrations
def populate_message_new(apps, schema_editor):
CampaignEvent = apps.get_model('campaigns', 'CampaignEvent')
events = list(CampaignEvent.objects.filter(event_type='M').select_related('flow'))
for event in events:
try:
event.message_new = json.loads(event.message)
except Exception:
base_lang = event.flow.base_language or 'base'
event.message_new = {base_lang: event.message}
event.save(update_fields=('message_new',))
if events:
print("Converted %d campaign events" % len(events))
class Migration(migrations.Migration):
dependencies = [
('campaigns', '0014_auto_20170228_0837'),
]
operations = [
HStoreExtension(),
migrations.AddField(
model_name='campaignevent',
name='message_new',
field=temba.utils.models.TranslatableField(max_length=640, null=True),
),
migrations.RunPython(populate_message_new)
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-04-19 14:53
from __future__ import unicode_literals
import json
import temba.utils.models
from django.contrib.postgres.operations import HStoreExtension
from django.db import migrations
def populate_message_new(apps, schema_editor):
CampaignEvent = apps.get_model('campaigns', 'CampaignEvent')
events = list(CampaignEvent.objects.filter(event_type='M').select_related('flow'))
for event in events:
try:
event.message_new = json.loads(event.message)
except Exception:
event.message_new = {event.flow.base_language: event.message}
event.save(update_fields=('message_new',))
if events:
print("Converted %d campaign events" % len(events))
class Migration(migrations.Migration):
dependencies = [
('campaigns', '0014_auto_20170228_0837'),
]
operations = [
HStoreExtension(),
migrations.AddField(
model_name='campaignevent',
name='message_new',
field=temba.utils.models.TranslatableField(max_length=640, null=True),
),
migrations.RunPython(populate_message_new)
]
|
Add const winner to improve readability | import { filter, head } from 'ramda';
import { emptyValue } from './constants';
import getPosition from './getPosition';
const positionsToCheck = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
];
/**
* Check winners for 3 winning positions
* @param {Number} board board
* @return {[Number]} winners
*/
const getWinners = (board) => {
const get = getPosition(board);
const winners = filter((positions) => {
const p0 = get(positions[0]);
const p1 = get(positions[1]);
const p2 = get(positions[2]);
return p0 !== emptyValue && p0 === p1 && p1 === p2;
}, positionsToCheck);
return head(winners) || null;
};
export default getWinners;
| import { filter, head } from 'ramda';
import { emptyValue } from './constants';
import getPosition from './getPosition';
const positionsToCheck = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
];
/**
* Check winners for 3 winning positions
* @param {Number} board board
* @return {[Number]} winners
*/
const getWinners = (board) => {
const get = getPosition(board);
return head(
filter((positions) => {
const p0 = get(positions[0]);
const p1 = get(positions[1]);
const p2 = get(positions[2]);
return p0 !== emptyValue && p0 === p1 && p1 === p2;
}, positionsToCheck)
) || null;
};
export default getWinners;
|
Build random path using os.path.join | from __future__ import unicode_literals
try:
from django.utils.encoding import force_text
except ImportError:
# Django < 1.5
from django.utils.encoding import force_unicode as force_text
from django.utils.timezone import now
from filer.utils.files import get_valid_filename
import os
def by_date(instance, filename):
datepart = force_text(now().strftime("%Y/%m/%d"))
return os.path.join(datepart, get_valid_filename(filename))
def randomized(instance, filename):
import uuid
uuid_str = str(uuid.uuid4())
return os.path.join(uuid_str[0:2], uuid_str[2:4], uuid_str,
get_valid_filename(filename))
class prefixed_factory(object):
def __init__(self, upload_to, prefix):
self.upload_to = upload_to
self.prefix = prefix
def __call__(self, instance, filename):
if callable(self.upload_to):
upload_to_str = self.upload_to(instance, filename)
else:
upload_to_str = self.upload_to
if not self.prefix:
return upload_to_str
return os.path.join(self.prefix, upload_to_str)
| from __future__ import unicode_literals
try:
from django.utils.encoding import force_text
except ImportError:
# Django < 1.5
from django.utils.encoding import force_unicode as force_text
from django.utils.timezone import now
from filer.utils.files import get_valid_filename
import os
def by_date(instance, filename):
datepart = force_text(now().strftime("%Y/%m/%d"))
return os.path.join(datepart, get_valid_filename(filename))
def randomized(instance, filename):
import uuid
uuid_str = str(uuid.uuid4())
random_path = "%s/%s/%s" % (uuid_str[0:2], uuid_str[2:4], uuid_str)
return os.path.join(random_path, get_valid_filename(filename))
class prefixed_factory(object):
def __init__(self, upload_to, prefix):
self.upload_to = upload_to
self.prefix = prefix
def __call__(self, instance, filename):
if callable(self.upload_to):
upload_to_str = self.upload_to(instance, filename)
else:
upload_to_str = self.upload_to
if not self.prefix:
return upload_to_str
return os.path.join(self.prefix, upload_to_str)
|
Trailing-spaces: Clean up code a wee bit. | /* Check for trailing spaces
*/
module.exports = function (filename, body, config, callback) {
var re = /\s$/,
lines = body.split('\n'),
errors = [];
for (var i = 0; i < lines.length; i += 1) {
if (re.test(lines[i])) {
errors.push({
filename: filename,
line: i + 1,
character: lines[i].length,
message: "Trailing whitespace.",
context: lines[i]
});
}
}
return callback(undefined, errors);
};
| /* Check for trailing spaces
*/
module.exports = function (filename, body, config, callback) {
// Check each line for trailing spaces
var re = /\s$/,
lines = body.split('\n'),
errors = [];
for (var i = 0; i < lines.length; i += 1) {
if (re.test(lines[i])) {
errors.push({
filename: filename,
line: i + 1,
character: lines[i].length,
message: "Trailing whitespace.",
context: lines[i]
});
}
}
return callback(undefined, errors);
};
|
Fix dashboard menu for older php version. | <?php
global $mysqli,$route,$session;
require_once "Modules/dashboard/dashboard_model.php";
$dashboard = new Dashboard($mysqli);
$location = 'view';
$sess = (isset($session['write']) && $session['write'] ? 'write':(isset($session['read']) && $session['read'] ? 'read':''));
if (isset($session['profile']) && $session['profile']==1) {
$dashpath = $session['username'];
$sess= 'all';
} else {
if ($route->action == "edit" && $session['write']) $location = 'edit';
$dashpath = 'dashboard/'.$location;
}
// Contains a list for the drop down with dashboards available for user session type
$listmenu = $dashboard->build_menu_array($location);
$domain = "messages";
bindtextdomain($domain, "Modules/dashboard/locale");
bind_textdomain_codeset($domain, 'UTF-8');
$menu_left[] = array('name'=> dgettext($domain, "Dashboards"), 'path'=>$dashpath , 'session'=>$sess, 'order' => 4, 'dropdown'=>$listmenu);
| <?php
global $mysqli,$route;
require_once "Modules/dashboard/dashboard_model.php";
$dashboard = new Dashboard($mysqli);
$location = 'view';
$sess = (isset($session['write']) && $session['write'] ? 'write':(isset($session['read']) && $session['read'] ? 'read':''));
if (isset($session['profile']) && $session['profile']==1) {
$dashpath = $session['username'];
$sess= 'all';
} else {
if ($route->action == "edit" && $session['write']) $location = 'edit';
$dashpath = 'dashboard/'.$location;
}
// Contains a list for the drop down with dashboards available for user session type
$listmenu = $dashboard->build_menu_array($location);
$domain = "messages";
bindtextdomain($domain, "Modules/dashboard/locale");
bind_textdomain_codeset($domain, 'UTF-8');
$menu_left[] = array('name'=> dgettext($domain, "Dashboards"), 'path'=>$dashpath , 'session'=>$sess, 'order' => 4, 'dropdown'=>$listmenu);
|
Add licencing info after captions | <?php
global $gds_image_licences;
$gds_image_licences = [
'ogl' => 'OGL',
'cc-by' => 'Attribution',
'cc-by-sa' => 'Attribution-ShareAlike',
'cc-by-nd' => 'Attribution-NoDerivs',
'cc-by-nc' => 'Attribution-NonCommercial',
'cc-by-nc-sa' => 'Attribution-NonCommercial-ShareAlike',
'cc-by-nc-nd' => 'Attribution-NonCommercial-NoDerivs',
'other' => 'Other',
];
add_filter('image_send_to_editor', function ($html, $id, $caption, $title, $align, $url, $size, $alt) {
global $gds_image_licences;
$_licence = get_post_meta($id, 'licence', true);
$licence = $gds_image_licences[$_licence];
$copyright_holder = get_post_meta($id, 'copyright_holder', true);
$link_to_source = get_post_meta($id, 'link_to_source', true);
$caption = 'Licence: '.esc_html($licence).' <a href="'.esc_attr($link_to_source).'">'.esc_html($copyright_holder).'</a>';
return '<figure>'.$html.'<figcaption>'.$caption.'</figcaption></figure>';
}, 999, 8);
| <?php
global $gds_image_licences;
$gds_image_licences = [
'ogl' => 'OGL',
'cc-by' => 'Attribution',
'cc-by-sa' => 'Attribution-ShareAlike',
'cc-by-nd' => 'Attribution-NoDerivs',
'cc-by-nc' => 'Attribution-NonCommercial',
'cc-by-nc-sa' => 'Attribution-NonCommercial-ShareAlike',
'cc-by-nc-nd' => 'Attribution-NonCommercial-NoDerivs',
'other' => 'Other',
];
add_filter('image_send_to_editor', function ($html, $id, $caption, $title, $align, $url, $size, $alt) {
global $gds_image_licences;
$_licence = get_post_meta($id, 'licence', true);
$licence = $gds_image_licences[$_licence];
$copyright_holder = get_post_meta($id, 'copyright_holder', true);
$link_to_source = get_post_meta($id, 'link_to_source', true);
$caption = 'Licence: '.esc_html($licence).' <a href="'.esc_attr($link_to_source).'">'.esc_html($copyright_holder).'</a>';
return '<figure>'.$html.'<figcaption>'.$caption.'</figcaption></figure>';
}, 10, 8);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.